2012-11-27 [wwp] 3.9.0cvs21
[claws.git] / src / main.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2012 Hiroyuki Yamamoto and the Claws Mail team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  * 
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #include "claws-features.h"
23 #endif
24
25 #include "defs.h"
26
27 #include <glib.h>
28 #include <glib/gi18n.h>
29 #include <gtk/gtk.h>
30
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <ctype.h>
35 #include <unistd.h>
36 #include <time.h>
37 #include <sys/stat.h>
38 #include <sys/types.h>
39 #ifdef G_OS_UNIX
40 #  include <signal.h>
41 #  include <errno.h>
42 #  include <fcntl.h>
43 #endif
44 #ifdef HAVE_LIBSM
45 #include <X11/SM/SMlib.h>
46 #endif
47
48 #if HAVE_FLOCK
49 #include <sys/file.h>
50 #endif
51
52 #include "wizard.h"
53 #ifdef HAVE_STARTUP_NOTIFICATION
54 # define SN_API_NOT_YET_FROZEN
55 # include <libsn/sn-launchee.h>
56 # include <gdk/gdkx.h>
57 #endif
58
59 #ifdef HAVE_DBUS_GLIB
60 #include <dbus/dbus-glib.h>
61 #endif
62 #ifdef HAVE_NETWORKMANAGER_SUPPORT
63 #include <NetworkManager.h>
64 #endif
65 #ifdef HAVE_VALGRIND
66 #include <valgrind.h>
67 #endif
68
69 #include "claws.h"
70 #include "main.h"
71 #include "mainwindow.h"
72 #include "folderview.h"
73 #include "image_viewer.h"
74 #include "summaryview.h"
75 #include "prefs_common.h"
76 #include "prefs_account.h"
77 #include "prefs_actions.h"
78 #include "prefs_ext_prog.h"
79 #include "prefs_fonts.h"
80 #include "prefs_image_viewer.h"
81 #include "prefs_message.h"
82 #include "prefs_receive.h"
83 #include "prefs_msg_colors.h"
84 #include "prefs_quote.h"
85 #include "prefs_spelling.h"
86 #include "prefs_summaries.h"
87 #include "prefs_themes.h"
88 #include "prefs_other.h"
89 #include "prefs_logging.h"
90 #include "prefs_send.h"
91 #include "prefs_wrapping.h"
92 #include "prefs_compose_writing.h"
93 #include "prefs_display_header.h"
94 #include "account.h"
95 #include "procmsg.h"
96 #include "inc.h"
97 #include "imap.h"
98 #include "import.h"
99 #include "manage_window.h"
100 #include "alertpanel.h"
101 #include "statusbar.h"
102 #ifndef USE_NEW_ADDRBOOK
103         #include "addressbook.h"
104 #else
105         #include "addressbook-dbus.h"
106 #endif
107 #include "compose.h"
108 #include "folder.h"
109 #include "folder_item_prefs.h"
110 #include "setup.h"
111 #include "utils.h"
112 #include "gtkutils.h"
113 #include "socket.h"
114 #include "log.h"
115 #include "prefs_toolbar.h"
116 #include "plugin.h"
117 #include "mh_gtk.h"
118 #include "imap_gtk.h"
119 #include "news_gtk.h"
120 #include "matcher.h"
121 #include "tags.h"
122 #include "hooks.h"
123 #include "menu.h"
124 #include "quicksearch.h"
125 #include "advsearch.h"
126
127 #ifdef HAVE_LIBETPAN
128 #include "imap-thread.h"
129 #include "nntp-thread.h"
130 #endif
131 #include "stock_pixmap.h"
132 #ifdef USE_GNUTLS
133 #  include "ssl.h"
134 #endif
135
136 #include "version.h"
137
138 #include "crash.h"
139
140 #include "timing.h"
141
142 #ifdef MAEMO
143 #ifdef CHINOOK
144 #include <hildon/hildon-banner.h>
145 #include <hildon/hildon-program.h>
146 #else
147 #include <hildon-widgets/hildon-banner.h>
148 #include <hildon-widgets/hildon-program.h>
149 #endif
150 #include <libosso.h>
151 #include <libgnomevfs/gnome-vfs-volume.h>
152 #include <libgnomevfs/gnome-vfs-volume-monitor.h>
153 #include <libgnomevfs/gnome-vfs-utils.h>
154
155 #define OSSO_NAME    "claws_mail"
156 #define OSSO_SERVICE "com.nokia."OSSO_NAME
157 #define OSSO_OBJECT  "/com/nokia/"OSSO_NAME
158 #define OSSO_IFACE   "com.nokia."OSSO_NAME
159
160 typedef struct _AppData AppData;
161 struct _AppData {
162     HildonProgram *program;
163     HildonWindow *window;
164     osso_context_t *osso_context;
165 };
166
167 static GnomeVFSVolumeMonitor *volmon;
168 #endif
169
170 #ifdef HAVE_NETWORKMANAGER_SUPPORT
171 /* Went offline due to NetworkManager */
172 static gboolean went_offline_nm;
173 #endif
174
175 #if !defined(NM_CHECK_VERSION)
176 #define NM_CHECK_VERSION(x,y,z) 0
177 #endif
178
179 #ifdef HAVE_DBUS_GLIB
180 static DBusGProxy *awn_proxy = NULL;
181 #endif
182
183 gchar *prog_version;
184 gchar *argv0;
185
186 #ifdef MAEMO
187 HildonProgram *hildon_program;
188 #endif
189
190 #ifdef HAVE_STARTUP_NOTIFICATION
191 static SnLauncheeContext *sn_context = NULL;
192 static SnDisplay *sn_display = NULL;
193 #endif
194
195 static gint lock_socket = -1;
196 static gint lock_socket_tag = 0;
197 static gchar *x_display = NULL;
198 typedef enum 
199 {
200         ONLINE_MODE_DONT_CHANGE,
201         ONLINE_MODE_ONLINE,
202         ONLINE_MODE_OFFLINE
203 } OnlineMode;
204
205 static struct RemoteCmd {
206         gboolean receive;
207         gboolean receive_all;
208         gboolean cancel_receiving;
209         gboolean cancel_sending;
210         gboolean compose;
211         const gchar *compose_mailto;
212         GList *attach_files;
213         gboolean search;
214         const gchar *search_folder;
215         const gchar *search_type;
216         const gchar *search_request;
217         gboolean search_recursive;
218         gboolean status;
219         gboolean status_full;
220         gboolean statistics;
221         gboolean reset_statistics;
222         GPtrArray *status_folders;
223         GPtrArray *status_full_folders;
224         gboolean send;
225         gboolean crash;
226         int online_mode;
227         gchar   *crash_params;
228         gboolean exit;
229         gboolean subscribe;
230         const gchar *subscribe_uri;
231         const gchar *target;
232 } cmd;
233
234 SessionStats session_stats;
235
236 static void reset_statistics(void);
237                 
238 static void parse_cmd_opt(int argc, char *argv[]);
239
240 static gint prohibit_duplicate_launch   (void);
241 static gchar * get_crashfile_name       (void);
242 static gint lock_socket_remove          (void);
243 static void lock_socket_input_cb        (gpointer          data,
244                                          gint              source,
245                                          GIOCondition      condition);
246
247 static void open_compose_new            (const gchar    *address,
248                                          GList          *attach_files);
249
250 static void send_queue                  (void);
251 static void initial_processing          (FolderItem *item, gpointer data);
252 static void quit_signal_handler         (int sig);
253 static void install_basic_sighandlers   (void);
254 #if (defined linux && defined SIGIO)
255 static void install_memory_sighandler   (void);
256 #endif
257 static void exit_claws                  (MainWindow *mainwin);
258
259 #ifdef HAVE_NETWORKMANAGER_SUPPORT
260 static void networkmanager_state_change_cb(DBusGProxy *proxy, gchar *dev,
261                                                                                                                                                                          gpointer data);
262 #endif
263
264 #define MAKE_DIR_IF_NOT_EXIST(dir) \
265 { \
266         if (!is_dir_exist(dir)) { \
267                 if (is_file_exist(dir)) { \
268                         alertpanel_warning \
269                                 (_("File '%s' already exists.\n" \
270                                    "Can't create folder."), \
271                                  dir); \
272                         return 1; \
273                 } \
274                 if (make_dir(dir) < 0) \
275                         return 1; \
276         } \
277 }
278
279 static MainWindow *static_mainwindow;
280
281 #ifdef MAEMO
282 static osso_context_t *static_osso_context;
283
284 void exit_event_handler(gboolean die_now, gpointer data)
285 {
286         AppData *appdata;
287         appdata = (AppData *) data;
288         /* Do whatever application needs to do before exiting */
289         exit_claws(static_mainwindow);
290         hildon_banner_show_information(GTK_WIDGET(appdata->window), NULL,
291                                    _("Exiting..."));
292
293 }
294
295 /* Callback for hardware D-BUS events */
296 void hw_event_handler(osso_hw_state_t *state, gpointer data)
297 {
298         AppData *appdata;
299         appdata = (AppData *) data;
300
301         if (state->shutdown_ind) {
302                 exit_claws(static_mainwindow);
303                 hildon_banner_show_information(GTK_WIDGET(appdata->window), NULL,
304                         _("Exiting..."));
305         }
306 }
307
308 /* Callback for normal D-BUS messages */
309 gint dbus_req_handler(const gchar * interface, const gchar * method,
310                       GArray * arguments, gpointer data,
311                       osso_rpc_t * retval)
312 {
313     AppData *appdata;
314     appdata = (AppData *) data;
315
316     if (!strcmp(method, "top_application")) {
317             osso_rpc_free_val(retval);
318             return OSSO_OK;
319     }
320     osso_system_note_infoprint(appdata->osso_context, method, retval);
321     osso_rpc_free_val(retval);
322
323     return OSSO_OK;
324 }
325 #endif
326 static gboolean emergency_exit = FALSE;
327
328 #ifdef HAVE_STARTUP_NOTIFICATION
329 static void sn_error_trap_push(SnDisplay *display, Display *xdisplay)
330 {
331         gdk_error_trap_push();
332 }
333
334 static void sn_error_trap_pop(SnDisplay *display, Display *xdisplay)
335 {
336         gdk_error_trap_pop();
337 }
338
339 static void startup_notification_complete(gboolean with_window)
340 {
341         Display *xdisplay;
342         GtkWidget *hack = NULL;
343
344         if (with_window) {
345                 /* this is needed to make the startup notification leave,
346                  * if we have been launched from a menu.
347                  * We have to display a window, so let it be very little */
348                 hack = gtk_window_new(GTK_WINDOW_POPUP);
349                 gtk_window_move(GTK_WINDOW(hack), 0, 0);
350                 gtk_widget_set_size_request(hack, 1, 1);
351                 gtk_widget_show(hack);
352         }
353
354         xdisplay = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
355         sn_display = sn_display_new(xdisplay,
356                                 sn_error_trap_push,
357                                 sn_error_trap_pop);
358         sn_context = sn_launchee_context_new_from_environment(sn_display,
359                                                  DefaultScreen(xdisplay));
360
361         if (sn_context != NULL) {
362                 sn_launchee_context_complete(sn_context);
363                 sn_launchee_context_unref(sn_context);
364                 sn_display_unref(sn_display);
365         }
366         if (with_window) {
367                 gtk_widget_destroy(hack);
368         }
369 }
370 #endif /* HAVE_STARTUP_NOTIFICATION */
371
372 static void claws_gtk_idle(void) 
373 {
374         while(gtk_events_pending()) {
375                 gtk_main_iteration();
376         }
377         g_usleep(50000);
378 }
379
380 static gboolean sc_starting = FALSE;
381
382 static gboolean defer_check_all(void *data)
383 {
384         gboolean autochk = GPOINTER_TO_INT(data);
385
386         inc_all_account_mail(static_mainwindow, autochk, 
387                         prefs_common.newmail_notify_manu);
388
389         /* Accounts using a specific timer need to be checked separately
390          * at startup
391          */
392         inc_all_account_spec_timer_check_mail();
393         
394         if (sc_starting) {
395                 sc_starting = FALSE;
396                 main_window_set_menu_sensitive(static_mainwindow);
397                 toolbar_main_set_sensitive(static_mainwindow);
398         }
399         return FALSE;
400 }
401
402 static gboolean defer_check(void *data)
403 {
404         inc_mail(static_mainwindow, prefs_common.newmail_notify_manu);
405
406         if (sc_starting) {
407                 sc_starting = FALSE;
408                 main_window_set_menu_sensitive(static_mainwindow);
409                 toolbar_main_set_sensitive(static_mainwindow);
410         }
411         return FALSE;
412 }
413
414 static gboolean defer_jump(void *data)
415 {
416         if (cmd.receive_all) {
417                 defer_check_all(GINT_TO_POINTER(FALSE));
418         } else if (prefs_common.chk_on_startup) {
419                 defer_check_all(GINT_TO_POINTER(TRUE));
420         } else if (cmd.receive) {
421                 defer_check(NULL);
422         } 
423         mainwindow_jump_to(data, FALSE);
424         if (sc_starting) {
425                 sc_starting = FALSE;
426                 main_window_set_menu_sensitive(static_mainwindow);
427                 toolbar_main_set_sensitive(static_mainwindow);
428         }
429         return FALSE;
430 }
431
432 static void chk_update_val(GtkWidget *widget, gpointer data)
433 {
434         gboolean *val = (gboolean *)data;
435         *val = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget));
436 }
437
438 static gboolean migrate_old_config(const gchar *old_cfg_dir, const gchar *new_cfg_dir, const gchar *oldversion)
439 {
440         gchar *message = g_strdup_printf(_("Configuration for %s found.\n"
441                          "Do you want to migrate this configuration?"), oldversion);
442         gchar *message2 = g_strdup_printf(_("\n\nYour Sylpheed filtering rules can be converted by a\n"
443                              "script available at %s."), TOOLS_URI);
444
445         if (!strcmp(oldversion, "Sylpheed"))
446                 message = g_strconcat(message, message2, NULL);
447         g_free(message2);
448
449         gint r = 0;
450         GtkWidget *window = NULL;
451         GtkWidget *keep_backup_chk;
452         gboolean backup = TRUE;
453
454         keep_backup_chk = gtk_check_button_new_with_label (_("Keep old configuration"));
455         gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(keep_backup_chk), TRUE);
456         CLAWS_SET_TIP(keep_backup_chk,
457                              _("Keeping a backup will allow you to go back to an "
458                                "older version, but may take a while if you have "
459                                "cached IMAP or News data, and will take some extra "
460                                "room on your disk."));
461
462         g_signal_connect(G_OBJECT(keep_backup_chk), "toggled", 
463                         G_CALLBACK(chk_update_val), &backup);
464
465         if (alertpanel_full(_("Migration of configuration"), message,
466                         GTK_STOCK_NO, "+" GTK_STOCK_YES, NULL, FALSE,
467                         keep_backup_chk, ALERT_QUESTION, G_ALERTDEFAULT) != G_ALERTALTERNATE) {
468                 return FALSE;
469         }
470         
471         /* we can either do a fast migration requiring not any extra disk
472          * space, or a slow one that copies the old configuration and leaves
473          * it in place. */
474         if (backup) {
475 backup_mode:
476                 window = label_window_create(_("Copying configuration... This may take a while..."));
477                 GTK_EVENTS_FLUSH();
478                 
479                 r = copy_dir(old_cfg_dir, new_cfg_dir);
480                 label_window_destroy(window);
481                 
482                 /* if copy failed, we'll remove the partially copied
483                  * new directory */
484                 if (r != 0) {
485                         alertpanel_error(_("Migration failed!"));
486                         remove_dir_recursive(new_cfg_dir);
487                 } else {
488                         if (!backup) {
489                                 /* fast mode failed, but we don't want backup */
490                                 remove_dir_recursive(old_cfg_dir);
491                         }
492                 }
493         } else {
494                 window = label_window_create(_("Migrating configuration..."));
495                 GTK_EVENTS_FLUSH();
496                 
497                 r = g_rename(old_cfg_dir, new_cfg_dir);
498                 label_window_destroy(window);
499                 
500                 /* if g_rename failed, we'll try to copy */
501                 if (r != 0) {
502                         FILE_OP_ERROR(new_cfg_dir, "g_rename failed, trying copy\n");
503                         goto backup_mode;
504                 }
505         }
506         return (r == 0);
507 }
508
509 static int migrate_common_rc(const gchar *old_rc, const gchar *new_rc)
510 {
511         FILE *oldfp, *newfp;
512         gchar *plugin_path, *old_plugin_path, *new_plugin_path;
513         gchar buf[BUFFSIZE];
514         gboolean err = FALSE;
515
516         oldfp = g_fopen(old_rc, "r");
517         if (!oldfp)
518                 return -1;
519         newfp = g_fopen(new_rc, "w");
520         if (!newfp) {
521                 fclose(oldfp);
522                 return -1;
523         }
524         
525         plugin_path = g_strdup(get_plugin_dir());
526         new_plugin_path = g_strdup(plugin_path);
527         
528         if (strstr(plugin_path, "/claws-mail/")) {
529                 gchar *end = g_strdup(strstr(plugin_path, "/claws-mail/")+strlen("/claws-mail/"));
530                 *(strstr(plugin_path, "/claws-mail/")) = '\0';
531                 old_plugin_path = g_strconcat(plugin_path, "/sylpheed-claws/", end, NULL);
532                 g_free(end);
533         } else {
534                 old_plugin_path = g_strdup(new_plugin_path);
535         }
536         debug_print("replacing %s with %s\n", old_plugin_path, new_plugin_path);
537         while (fgets(buf, sizeof(buf), oldfp)) {
538                 if (strncmp(buf, old_plugin_path, strlen(old_plugin_path))) {
539                         err |= (fputs(buf, newfp) == EOF);
540                 } else {
541                         debug_print("->replacing %s", buf);
542                         debug_print("  with %s%s", new_plugin_path, buf+strlen(old_plugin_path));
543                         err |= (fputs(new_plugin_path, newfp) == EOF);
544                         err |= (fputs(buf+strlen(old_plugin_path), newfp) == EOF);
545                 }
546         }
547         g_free(plugin_path);
548         g_free(new_plugin_path);
549         g_free(old_plugin_path);
550         fclose(oldfp);
551         if (fclose(newfp) == EOF)
552                 err = TRUE;
553         
554         return (err ? -1:0);
555 }
556
557 #ifdef HAVE_LIBSM
558 static void
559 sc_client_set_value (MainWindow *mainwin,
560                   gchar       *name,
561                   char        *type,
562                   int          num_vals,
563                   SmPropValue *vals)
564 {
565         SmProp *proplist[1];
566         SmProp prop;
567
568         prop.name = name;
569         prop.type = type;
570         prop.num_vals = num_vals;
571         prop.vals = vals;
572
573         proplist[0]= &prop;
574         if (mainwin->smc_conn)
575                 SmcSetProperties ((SmcConn) mainwin->smc_conn, 1, proplist);
576 }
577
578 static void sc_die_callback (SmcConn smc_conn, SmPointer client_data)
579 {
580         clean_quit(NULL);
581 }
582
583 static void sc_save_complete_callback(SmcConn smc_conn, SmPointer client_data)
584 {
585 }
586
587 static void sc_shutdown_cancelled_callback (SmcConn smc_conn, SmPointer client_data)
588 {
589         MainWindow *mainwin = (MainWindow *)client_data;
590         if (mainwin->smc_conn)
591                 SmcSaveYourselfDone ((SmcConn) mainwin->smc_conn, TRUE);
592 }
593
594 static void sc_save_yourself_callback (SmcConn   smc_conn,
595                                SmPointer client_data,
596                                int       save_style,
597                                gboolean  shutdown,
598                                int       interact_style,
599                                gboolean  fast) {
600
601         MainWindow *mainwin = (MainWindow *)client_data;
602         if (mainwin->smc_conn)
603                 SmcSaveYourselfDone ((SmcConn) mainwin->smc_conn, TRUE);
604 }
605
606 static IceIOErrorHandler sc_ice_installed_handler;
607
608 static void sc_ice_io_error_handler (IceConn connection)
609 {
610         if (sc_ice_installed_handler)
611                 (*sc_ice_installed_handler) (connection);
612 }
613 static gboolean sc_process_ice_messages (GIOChannel   *source,
614                                          GIOCondition  condition,
615                                          gpointer      data)
616 {
617         IceConn connection = (IceConn) data;
618         IceProcessMessagesStatus status;
619
620         status = IceProcessMessages (connection, NULL, NULL);
621
622         if (status == IceProcessMessagesIOError) {
623                 IcePointer context = IceGetConnectionContext (connection);
624
625                 if (context && G_IS_OBJECT(context)) {
626                 guint disconnect_id = g_signal_lookup ("disconnect", G_OBJECT_TYPE (context));
627
628                 if (disconnect_id > 0)
629                         g_signal_emit (context, disconnect_id, 0);
630                 } else {
631                         IceSetShutdownNegotiation (connection, False);
632                         IceCloseConnection (connection);
633                 }
634         }
635
636         return TRUE;
637 }
638
639 static void new_ice_connection (IceConn connection, IcePointer client_data, Bool opening,
640                     IcePointer *watch_data)
641 {
642         guint input_id;
643
644         if (opening) {
645                 GIOChannel *channel;
646                 /* Make sure we don't pass on these file descriptors to any
647                 exec'ed children */
648                 fcntl(IceConnectionNumber(connection),F_SETFD,
649                 fcntl(IceConnectionNumber(connection),F_GETFD,0) | FD_CLOEXEC);
650
651                 channel = g_io_channel_unix_new (IceConnectionNumber (connection));
652                 input_id = g_io_add_watch (channel,
653                 G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_PRI,
654                 sc_process_ice_messages,
655                 connection);
656                 g_io_channel_unref (channel);
657
658                 *watch_data = (IcePointer) GUINT_TO_POINTER (input_id);
659         } else {
660                 input_id = GPOINTER_TO_UINT ((gpointer) *watch_data);
661                 g_source_remove (input_id);
662         }
663 }
664
665 static void sc_session_manager_connect(MainWindow *mainwin)
666 {
667         static gboolean connected = FALSE;
668         SmcCallbacks      callbacks;
669         gchar            *client_id;
670         IceIOErrorHandler default_handler;
671
672         if (connected)
673                 return;
674         connected = TRUE;
675
676
677         sc_ice_installed_handler = IceSetIOErrorHandler (NULL);
678         default_handler = IceSetIOErrorHandler (sc_ice_io_error_handler);
679
680         if (sc_ice_installed_handler == default_handler)
681                 sc_ice_installed_handler = NULL;
682
683         IceAddConnectionWatch (new_ice_connection, NULL);
684       
685       
686         callbacks.save_yourself.callback      = sc_save_yourself_callback;
687         callbacks.die.callback                = sc_die_callback;
688         callbacks.save_complete.callback      = sc_save_complete_callback;
689         callbacks.shutdown_cancelled.callback = sc_shutdown_cancelled_callback;
690
691         callbacks.save_yourself.client_data =
692                 callbacks.die.client_data =
693                 callbacks.save_complete.client_data =
694                 callbacks.shutdown_cancelled.client_data = (SmPointer) mainwin;
695         if (g_getenv ("SESSION_MANAGER")) {
696                 gchar error_string_ret[256] = "";
697
698                 mainwin->smc_conn = (gpointer)
699                         SmcOpenConnection (NULL, mainwin,
700                                 SmProtoMajor, SmProtoMinor,
701                                 SmcSaveYourselfProcMask | SmcDieProcMask |
702                                 SmcSaveCompleteProcMask |
703                                 SmcShutdownCancelledProcMask,
704                                 &callbacks,
705                                 NULL, &client_id,
706                                 256, error_string_ret);
707
708                 if (error_string_ret[0] || mainwin->smc_conn == NULL)
709                         g_warning ("While connecting to session manager:\n%s.",
710                                 error_string_ret);
711                 else {
712                         SmPropValue *vals;
713                         vals = g_new (SmPropValue, 1);
714                         vals[0].length = strlen(argv0);
715                         vals[0].value = argv0;
716                         sc_client_set_value (mainwin, SmCloneCommand, SmLISTofARRAY8, 1, vals);
717                         sc_client_set_value (mainwin, SmRestartCommand, SmLISTofARRAY8, 1, vals);
718                         sc_client_set_value (mainwin, SmProgram, SmARRAY8, 1, vals);
719
720                         vals[0].length = strlen(g_get_user_name()?g_get_user_name():"");
721                         vals[0].value = g_strdup(g_get_user_name()?g_get_user_name():"");
722                         sc_client_set_value (mainwin, SmUserID, SmARRAY8, 1, vals);
723                 }
724         }
725 }
726 #endif
727
728 static gboolean sc_exiting = FALSE;
729 static gboolean show_at_startup = TRUE;
730 static gboolean claws_crashed_bool = FALSE;
731
732 gboolean claws_crashed(void) {
733         return claws_crashed_bool;
734 }
735
736 void main_set_show_at_startup(gboolean show)
737 {
738         show_at_startup = show;
739 }
740
741 #ifdef MAEMO
742 static void main_vol_mount_cb(GnomeVFSVolumeMonitor *vfs, GnomeVFSVolume *vol, MainWindow *mainwin)
743 {
744         gchar *uri = gnome_vfs_volume_get_activation_uri (vol);
745         gchar *mount_path = uri?gnome_vfs_get_local_path_from_uri (uri):NULL;
746         g_free (uri);
747         if (mount_path) {
748                 if(!strcmp(mount_path, prefs_common.data_root)) {
749                         gtk_widget_set_sensitive(mainwin->window, TRUE);
750                         inc_unlock();
751                 }
752         }
753         g_free(mount_path);
754 }
755 static void main_vol_unmount_cb(GnomeVFSVolumeMonitor *vfs, GnomeVFSVolume *vol, MainWindow *mainwin)
756 {
757         gchar *uri = gnome_vfs_volume_get_activation_uri (vol);
758         gchar *mount_path = uri?gnome_vfs_get_local_path_from_uri (uri):NULL;
759         g_free (uri);
760         if (mount_path) {
761                 if(!strcmp(mount_path, prefs_common.data_root)) {
762                         gtk_widget_set_sensitive(mainwin->window, FALSE);
763                         inc_lock();
764                 }
765         }
766         g_free(mount_path);
767 }
768 #endif
769
770 #ifdef G_OS_WIN32
771 static FILE* win32_debug_fp=NULL;
772 static guint win32_log_handler_app_id;
773 static guint win32_log_handler_glib_id;
774 static guint win32_log_handler_gtk_id;
775
776 static void win32_print_stdout(const gchar *string)
777 {
778         if (win32_debug_fp) {
779                 fprintf(win32_debug_fp, string);
780                 fflush(win32_debug_fp);
781         }
782 }
783
784 static void win32_print_stderr(const gchar *string)
785 {
786         if (win32_debug_fp) {
787                 fprintf(win32_debug_fp, string);
788                 fflush(win32_debug_fp);
789         }
790 }
791
792 static void win32_log(const gchar *log_domain, GLogLevelFlags log_level, const gchar* message, gpointer user_data)
793 {
794         if (win32_debug_fp) {
795                 const gchar* type;
796
797                 switch(log_level & G_LOG_LEVEL_MASK)
798                 {
799                         case G_LOG_LEVEL_ERROR:
800                                 type="error";
801                                 break;
802                         case G_LOG_LEVEL_CRITICAL:
803                                 type="critical";
804                                 break;
805                         case G_LOG_LEVEL_WARNING:
806                                 type="warning";
807                                 break;
808                         case G_LOG_LEVEL_MESSAGE:
809                                 type="message";
810                                 break;
811                         case G_LOG_LEVEL_INFO:
812                                 type="info";
813                                 break;
814                         case G_LOG_LEVEL_DEBUG:
815                                 type="debug";
816                                 break;
817                         default:
818                                 type="N/A";
819                 }
820                 if (log_domain)
821                         fprintf(win32_debug_fp, "%s: %s: %s", log_domain, type, message);
822                 else
823                         fprintf(win32_debug_fp, "%s: %s", type, message);
824                 fflush(win32_debug_fp);
825         }
826 }
827
828 static void win32_open_log(void)
829 {
830         gchar *logfile = g_strconcat(g_get_tmp_dir(), G_DIR_SEPARATOR_S, "claws-win32.log", NULL);
831         gchar *oldlogfile = g_strconcat(g_get_tmp_dir(), G_DIR_SEPARATOR_S, "claws-win32.log.bak", NULL);
832
833         if (is_file_exist(logfile)) {
834                 if (rename_force(logfile, oldlogfile) < 0)
835                         FILE_OP_ERROR(logfile, "rename");
836         }
837         win32_debug_fp = g_fopen(logfile, "w");
838         g_free(logfile);
839         g_free(oldlogfile);
840         if (win32_debug_fp)
841         {
842                 g_set_print_handler(win32_print_stdout);
843                 g_set_printerr_handler(win32_print_stdout);
844                 win32_log_handler_app_id = g_log_set_handler(NULL, G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
845                      | G_LOG_FLAG_RECURSION, win32_log, NULL);
846                 win32_log_handler_glib_id = g_log_set_handler("GLib", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
847                      | G_LOG_FLAG_RECURSION, win32_log, NULL);
848                 win32_log_handler_gtk_id = g_log_set_handler("Gtk", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
849                      | G_LOG_FLAG_RECURSION, win32_log, NULL);
850         }
851 }
852
853 static void win32_close_log(void)
854 {
855         if (win32_debug_fp)
856         {
857                 g_log_remove_handler("", win32_log_handler_app_id);
858                 g_log_remove_handler("GLib", win32_log_handler_glib_id);
859                 g_log_remove_handler("Gtk", win32_log_handler_gtk_id);
860                 fclose(win32_debug_fp);
861                 win32_debug_fp=NULL;
862         }
863 }               
864 #endif
865
866 static void main_dump_features_list(gboolean show_debug_only)
867 /* display compiled-in features list */
868 {
869         if (show_debug_only && !debug_get_mode())
870                 return;
871
872         if (show_debug_only)
873                 debug_print("runtime GTK+ %d.%d.%d / GLib %d.%d.%d\n",
874                            gtk_major_version, gtk_minor_version, gtk_micro_version,
875                            glib_major_version, glib_minor_version, glib_micro_version);
876         else
877                 g_print("runtime GTK+ %d.%d.%d / GLib %d.%d.%d\n",
878                            gtk_major_version, gtk_minor_version, gtk_micro_version,
879                            glib_major_version, glib_minor_version, glib_micro_version);
880         if (show_debug_only)
881                 debug_print("buildtime GTK+ %d.%d.%d / GLib %d.%d.%d\n",
882                            GTK_MAJOR_VERSION, GTK_MINOR_VERSION, GTK_MICRO_VERSION,
883                            GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION);
884         else
885                 g_print("buildtime GTK+ %d.%d.%d / GLib %d.%d.%d\n",
886                            GTK_MAJOR_VERSION, GTK_MINOR_VERSION, GTK_MICRO_VERSION,
887                            GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION);
888         
889         if (show_debug_only)
890                 debug_print("Compiled-in features:\n");
891         else
892                 g_print("Compiled-in features:\n");
893 #if HAVE_LIBCOMPFACE
894         if (show_debug_only)
895                 debug_print(" compface\n");
896         else
897                 g_print(" compface\n");
898 #endif
899 #if USE_ENCHANT
900         if (show_debug_only)
901                 debug_print(" aspell\n");
902         else
903                 g_print(" aspell\n");
904 #endif
905 #if USE_GNUTLS
906         if (show_debug_only)
907                 debug_print(" gnutls\n");
908         else
909                 g_print(" gnutls\n");
910 #endif
911 #if INET6
912         if (show_debug_only)
913                 debug_print(" ipv6\n");
914         else
915                 g_print(" ipv6\n");
916 #endif
917 #if HAVE_ICONV
918         if (show_debug_only)
919                 debug_print(" iconv\n");
920         else
921                 g_print(" iconv\n");
922 #endif
923 #if USE_JPILOT
924         if (show_debug_only)
925                 debug_print(" jpilot\n");
926         else
927                 g_print(" jpilot\n");
928 #endif
929 #if USE_LDAP
930         if (show_debug_only)
931                 debug_print(" ldap\n");
932         else
933                 g_print(" ldap\n");
934 #endif
935 #if HAVE_LIBETPAN
936         if (show_debug_only)
937                 debug_print(" libetpan %d.%d\n", LIBETPAN_VERSION_MAJOR, LIBETPAN_VERSION_MINOR);
938         else
939                 g_print(" libetpan %d.%d\n", LIBETPAN_VERSION_MAJOR, LIBETPAN_VERSION_MINOR);
940 #endif
941 #if HAVE_LIBSM
942         if (show_debug_only)
943                 debug_print(" libsm\n");
944         else
945                 g_print(" libsm\n");
946 #endif
947 #if HAVE_NETWORKMANAGER_SUPPORT
948         if (show_debug_only)
949                 debug_print(" NetworkManager\n");
950         else
951                 g_print(" NetworkManager\n");
952 #endif
953 }
954
955 #ifdef HAVE_DBUS_GLIB
956 static guint dbus_item_hook_id = -1;
957 static guint dbus_folder_hook_id = -1;
958
959 static void uninstall_dbus_status_handler(void)
960 {
961         if(awn_proxy)
962                 g_object_unref(awn_proxy);
963         awn_proxy = NULL;
964         if (dbus_item_hook_id != -1)
965                 hooks_unregister_hook(FOLDER_ITEM_UPDATE_HOOKLIST, dbus_item_hook_id);
966         if (dbus_folder_hook_id != -1)
967                 hooks_unregister_hook(FOLDER_UPDATE_HOOKLIST, dbus_folder_hook_id);
968 }
969
970 static void dbus_update(FolderItem *removed_item)
971 {
972         guint new, unread, unreadmarked, marked, total;
973         guint replied, forwarded, locked, ignored, watched;
974         gchar *buf;
975         GError *error = NULL;
976
977         folder_count_total_msgs(&new, &unread, &unreadmarked, &marked, &total,
978                                 &replied, &forwarded, &locked, &ignored,
979                                 &watched);
980         if (removed_item) {
981                 total -= removed_item->total_msgs;
982                 new -= removed_item->new_msgs;
983                 unread -= removed_item->unread_msgs;
984         }
985
986         if (new > 0) {
987                 buf = g_strdup_printf("%d", new);
988                 dbus_g_proxy_call(awn_proxy, "SetInfoByName", &error,
989                         G_TYPE_STRING, "claws-mail",
990                         G_TYPE_STRING, buf,
991                         G_TYPE_INVALID, G_TYPE_INVALID);
992                 g_free(buf);
993                 
994         } else {
995                 dbus_g_proxy_call(awn_proxy, "UnsetInfoByName", &error, G_TYPE_STRING,
996                         "claws-mail", G_TYPE_INVALID, G_TYPE_INVALID);
997         }
998         if (error) {
999                 debug_print("%s\n", error->message);
1000                 g_error_free(error);
1001         }
1002 }
1003
1004 static gboolean dbus_status_update_folder_hook(gpointer source, gpointer data)
1005 {
1006         FolderUpdateData *hookdata;
1007         hookdata = source;
1008         if (hookdata->update_flags & FOLDER_REMOVE_FOLDERITEM)
1009                 dbus_update(hookdata->item);
1010         else
1011                 dbus_update(NULL);
1012
1013         return FALSE;
1014 }
1015
1016 static gboolean dbus_status_update_item_hook(gpointer source, gpointer data)
1017 {
1018         dbus_update(NULL);
1019
1020         return FALSE;
1021 }
1022
1023 static void install_dbus_status_handler(void)
1024 {
1025         GError *tmp_error = NULL;
1026         DBusGConnection *connection = dbus_g_bus_get(DBUS_BUS_SESSION, &tmp_error);
1027         
1028         if(!connection) {
1029                 /* If calling code doesn't do error checking, at least print some debug */
1030                 debug_print("Failed to open connection to session bus: %s\n",
1031                                  tmp_error->message);
1032                 g_error_free(tmp_error);
1033                 return;
1034         }
1035         awn_proxy = dbus_g_proxy_new_for_name(connection,
1036                         "com.google.code.Awn",
1037                         "/com/google/code/Awn",
1038                         "com.google.code.Awn");
1039         dbus_item_hook_id = hooks_register_hook (FOLDER_ITEM_UPDATE_HOOKLIST, dbus_status_update_item_hook, NULL);
1040         if (dbus_item_hook_id == -1) {
1041                 g_warning(_("Failed to register folder item update hook"));
1042                 uninstall_dbus_status_handler();
1043                 return;
1044         }
1045
1046         dbus_folder_hook_id = hooks_register_hook (FOLDER_UPDATE_HOOKLIST, dbus_status_update_folder_hook, NULL);
1047         if (dbus_folder_hook_id == -1) {
1048                 g_warning(_("Failed to register folder update hook"));
1049                 uninstall_dbus_status_handler();
1050                 return;
1051         }
1052 }
1053 #endif
1054
1055 static void reset_statistics(void)
1056 {
1057         /* (re-)initialize session statistics */
1058         session_stats.received = 0;
1059         session_stats.sent = 0;
1060         session_stats.replied = 0;
1061         session_stats.forwarded = 0;
1062         session_stats.time_started = time(NULL);
1063 }
1064                 
1065 int main(int argc, char *argv[])
1066 {
1067 #ifdef MAEMO
1068         osso_context_t *osso_context;
1069         osso_return_t result;
1070 #endif
1071 #ifdef HAVE_DBUS_GLIB
1072         DBusGConnection *connection;
1073         GError *error;
1074 #endif
1075 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1076         DBusGProxy *nm_proxy;
1077 #endif
1078         gchar *userrc;
1079         MainWindow *mainwin;
1080         FolderView *folderview;
1081         GdkPixbuf *icon;
1082         gboolean crash_file_present = FALSE;
1083         gint num_folder_class = 0;
1084         gboolean asked_for_migration = FALSE;
1085         gboolean start_done = TRUE;
1086         GSList *plug_list = NULL;
1087         gboolean never_ran = FALSE;
1088         gboolean mainwin_shown = FALSE;
1089
1090         START_TIMING("startup");
1091
1092         sc_starting = TRUE;
1093
1094 #ifdef G_OS_WIN32
1095         win32_open_log();
1096 #endif
1097         if (!claws_init(&argc, &argv)) {
1098 #ifdef G_OS_WIN32
1099                 win32_close_log();
1100 #endif
1101                 return 0;
1102         }
1103
1104         prog_version = PROG_VERSION;
1105         argv0 = g_strdup(argv[0]);
1106
1107         parse_cmd_opt(argc, argv);
1108
1109         sock_init();
1110
1111         /* check and create unix domain socket for remote operation */
1112         lock_socket = prohibit_duplicate_launch();
1113         if (lock_socket < 0) {
1114 #ifdef HAVE_STARTUP_NOTIFICATION
1115                 if(gtk_init_check(&argc, &argv))
1116                         startup_notification_complete(TRUE);
1117 #endif
1118                 return 0;
1119         }
1120
1121         main_dump_features_list(TRUE);
1122         prefs_prepare_cache();
1123
1124 #ifdef CRASH_DIALOG
1125         if (cmd.crash) {
1126 #if !GTK_CHECK_VERSION(3, 0, 0)
1127                 gtk_set_locale();
1128 #endif
1129                 gtk_init(&argc, &argv);
1130                 crash_main(cmd.crash_params);
1131 #ifdef G_OS_WIN32
1132                 win32_close_log();
1133 #endif
1134                 return 0;
1135         }
1136         crash_install_handlers();
1137 #endif
1138         install_basic_sighandlers();
1139 #if (defined linux && defined SIGIO)
1140         install_memory_sighandler();
1141 #endif
1142
1143         if (cmd.status || cmd.status_full || cmd.search ||
1144                 cmd.statistics || cmd.reset_statistics || 
1145                 cmd.cancel_receiving || cmd.cancel_sending) {
1146                 puts("0 Claws Mail not running.");
1147                 lock_socket_remove();
1148                 return 0;
1149         }
1150         
1151         if (cmd.exit)
1152                 return 0;
1153         if (!g_thread_supported())
1154                 g_thread_init(NULL);
1155
1156         reset_statistics();
1157         
1158 #if !GTK_CHECK_VERSION(3, 0, 0)
1159         gtk_set_locale();
1160 #endif
1161         gtk_init(&argc, &argv);
1162
1163 #ifdef G_OS_WIN32
1164         gtk_settings_set_string_property(gtk_settings_get_default(),
1165                         "gtk-theme-name",
1166                         "MS-Windows",
1167                         "XProperty");
1168 #endif
1169
1170 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1171         went_offline_nm = FALSE;
1172         nm_proxy = NULL;
1173 #endif
1174 #ifdef HAVE_DBUS_GLIB
1175         error = NULL;
1176         connection = dbus_g_bus_get(DBUS_BUS_SYSTEM, &error);
1177
1178         if(!connection) {
1179                 debug_print("Failed to open connection to system bus: %s\n", error->message);
1180                 g_error_free(error);
1181         }
1182         else {
1183 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1184                 nm_proxy = dbus_g_proxy_new_for_name(connection,
1185                         "org.freedesktop.NetworkManager",
1186                         "/org/freedesktop/NetworkManager",
1187                         "org.freedesktop.NetworkManager");
1188                 if (nm_proxy) {
1189 #if NM_CHECK_VERSION(0,8,992)
1190                         dbus_g_proxy_add_signal(nm_proxy, "StateChanged", G_TYPE_UINT, G_TYPE_INVALID);
1191                         dbus_g_proxy_connect_signal(nm_proxy, "StateChanged",
1192                                 G_CALLBACK(networkmanager_state_change_cb),
1193                                 NULL,NULL);
1194 #else
1195                         dbus_g_proxy_add_signal(nm_proxy, "StateChange", G_TYPE_UINT, G_TYPE_INVALID);
1196                         dbus_g_proxy_connect_signal(nm_proxy, "StateChange",
1197                                 G_CALLBACK(networkmanager_state_change_cb),
1198                                 NULL,NULL);
1199 #endif
1200                 }
1201 #endif
1202                 install_dbus_status_handler();
1203         }
1204 #endif
1205
1206
1207 #ifdef MAEMO
1208         osso_context = osso_initialize(OSSO_SERVICE, "2.8.1", TRUE, NULL);
1209         if (osso_context == NULL) {
1210                 return OSSO_ERROR;
1211         }
1212         hildon_program = HILDON_PROGRAM(hildon_program_get_instance());
1213         static_osso_context = osso_context;
1214 #endif  
1215 #if !GTK_CHECK_VERSION(3, 0, 0)
1216         gtk_widget_set_default_colormap(
1217                 gdk_screen_get_system_colormap(
1218                         gdk_screen_get_default()));
1219 #endif
1220
1221         gtkut_create_ui_manager();
1222
1223         /* Create container for all the menus we will be adding */
1224         MENUITEM_ADDUI("/", "Menus", NULL, GTK_UI_MANAGER_MENUBAR);
1225
1226         if (!g_thread_supported()) {
1227                 g_error(_("g_thread is not supported by glib.\n"));
1228         }
1229
1230 #ifdef G_OS_WIN32
1231         CHDIR_EXEC_CODE_RETURN_VAL_IF_FAIL(get_home_dir(), 1, win32_close_log(););
1232 #else
1233         CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
1234 #endif
1235         
1236         /* no config dir exists. See if we can migrate an old config. */
1237         if (!is_dir_exist(RC_DIR)) {
1238                 prefs_destroy_cache();
1239                 gboolean r = FALSE;
1240                 
1241                 /* if one of the old dirs exist, we'll ask if the user 
1242                  * want to migrates, and r will be TRUE if he said yes
1243                  * and migration succeeded, and FALSE otherwise.
1244                  */
1245                 if (is_dir_exist(OLD_GTK2_RC_DIR)) {
1246                         r = migrate_old_config(OLD_GTK2_RC_DIR, RC_DIR, _("Sylpheed-Claws 2.6.0 (or older)"));
1247                         asked_for_migration = TRUE;
1248                 } else if (is_dir_exist(OLDER_GTK2_RC_DIR)) {
1249                         r = migrate_old_config(OLDER_GTK2_RC_DIR, RC_DIR, _("Sylpheed-Claws 1.9.15 (or older)"));
1250                         asked_for_migration = TRUE;
1251                 } else if (is_dir_exist(OLD_GTK1_RC_DIR)) {
1252                         r = migrate_old_config(OLD_GTK1_RC_DIR, RC_DIR, _("Sylpheed-Claws 1.0.5 (or older)"));
1253                         asked_for_migration = TRUE;
1254                 } else if (is_dir_exist(SYLPHEED_RC_DIR)) {
1255                         r = migrate_old_config(SYLPHEED_RC_DIR, RC_DIR, "Sylpheed");
1256                         asked_for_migration = TRUE;
1257                 }
1258                 
1259                 /* If migration failed or the user didn't want to do it,
1260                  * we create a new one (and we'll hit wizard later). 
1261                  */
1262                 if (r == FALSE && !is_dir_exist(RC_DIR)) {
1263 #ifdef G_OS_UNIX
1264                         if (copy_dir(SYSCONFDIR "/skel/.claws-mail", RC_DIR) < 0) {
1265 #endif
1266                                 if (!is_dir_exist(RC_DIR) && make_dir(RC_DIR) < 0) {
1267 #ifdef G_OS_WIN32
1268                                         win32_close_log();
1269 #endif
1270                                         exit(1);
1271                                 }
1272 #ifdef G_OS_UNIX
1273                         }
1274 #endif
1275                 }
1276         }
1277         
1278
1279         if (!is_file_exist(RC_DIR G_DIR_SEPARATOR_S COMMON_RC) &&
1280             is_file_exist(RC_DIR G_DIR_SEPARATOR_S OLD_COMMON_RC)) {
1281                 /* post 2.6 name change */
1282                 migrate_common_rc(RC_DIR G_DIR_SEPARATOR_S OLD_COMMON_RC,
1283                           RC_DIR G_DIR_SEPARATOR_S COMMON_RC);
1284         }
1285
1286         if (!cmd.exit)
1287                 plugin_load_all("Common");
1288
1289         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, "gtkrc-2.0", NULL);
1290         gtk_rc_parse(userrc);
1291         g_free(userrc);
1292
1293         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
1294         gtk_accel_map_load (userrc);
1295         g_free(userrc);
1296
1297 #ifdef G_OS_WIN32
1298         CHDIR_EXEC_CODE_RETURN_VAL_IF_FAIL(get_rc_dir(), 1, win32_close_log(););
1299 #else
1300         CHDIR_RETURN_VAL_IF_FAIL(get_rc_dir(), 1);
1301 #endif
1302
1303         MAKE_DIR_IF_NOT_EXIST(get_mail_base_dir());
1304         MAKE_DIR_IF_NOT_EXIST(get_imap_cache_dir());
1305         MAKE_DIR_IF_NOT_EXIST(get_news_cache_dir());
1306         MAKE_DIR_IF_NOT_EXIST(get_mime_tmp_dir());
1307         MAKE_DIR_IF_NOT_EXIST(get_tmp_dir());
1308         MAKE_DIR_IF_NOT_EXIST(UIDL_DIR);
1309
1310         crash_file_present = is_file_exist(get_crashfile_name());
1311         /* remove temporary files */
1312         remove_all_files(get_tmp_dir());
1313         remove_all_files(get_mime_tmp_dir());
1314
1315         if (!cmd.crash && crash_file_present)
1316                 claws_crashed_bool = TRUE;
1317
1318         if (is_file_exist("claws.log")) {
1319                 if (rename_force("claws.log", "claws.log.bak") < 0)
1320                         FILE_OP_ERROR("claws.log", "rename");
1321         }
1322         set_log_file(LOG_PROTOCOL, "claws.log");
1323
1324         if (is_file_exist("filtering.log")) {
1325                 if (rename_force("filtering.log", "filtering.log.bak") < 0)
1326                         FILE_OP_ERROR("filtering.log", "rename");
1327         }
1328         set_log_file(LOG_DEBUG_FILTERING, "filtering.log");
1329
1330 #ifdef G_OS_WIN32
1331         CHDIR_EXEC_CODE_RETURN_VAL_IF_FAIL(get_home_dir(), 1, win32_close_log(););
1332 #else
1333         CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
1334 #endif
1335
1336         folder_system_init();
1337         prefs_common_read_config();
1338
1339         prefs_themes_init();
1340         prefs_fonts_init();
1341         prefs_ext_prog_init();
1342         prefs_wrapping_init();
1343         prefs_compose_writing_init();
1344         prefs_msg_colors_init();
1345         image_viewer_init();
1346         prefs_image_viewer_init();
1347         prefs_quote_init();
1348         prefs_summaries_init();
1349         prefs_message_init();
1350         prefs_other_init();
1351         prefs_logging_init();
1352         prefs_receive_init();
1353         prefs_send_init();
1354         tags_read_tags();
1355         matcher_init();
1356 #ifdef USE_ENCHANT
1357         gtkaspell_checkers_init();
1358         prefs_spelling_init();
1359 #endif
1360
1361         sock_set_io_timeout(prefs_common.io_timeout_secs);
1362         prefs_actions_read_config();
1363         prefs_display_header_read_config();
1364         /* prefs_filtering_read_config(); */
1365 #ifndef USE_NEW_ADDRBOOK
1366         addressbook_read_file();
1367 #else
1368         g_clear_error(&error);
1369         if (! addressbook_start_service(&error)) {
1370                 g_warning("%s", error->message);
1371                 g_clear_error(&error);
1372         }
1373         else {
1374                 addressbook_install_hooks(&error);
1375         }
1376 #endif
1377         gtkut_widget_init();
1378         stock_pixbuf_gdk(NULL, STOCK_PIXMAP_CLAWS_MAIL_ICON, &icon);
1379         gtk_window_set_default_icon(icon);
1380
1381         folderview_initialize();
1382
1383         mh_gtk_init();
1384         imap_gtk_init();
1385         news_gtk_init();
1386
1387         mainwin = main_window_create();
1388
1389 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1390         networkmanager_state_change_cb(nm_proxy,NULL,mainwin);
1391 #endif
1392
1393 #ifdef MAEMO
1394         AppData *appdata;
1395         appdata = g_new0(AppData, 1);
1396         appdata->program = hildon_program;
1397         appdata->window = HILDON_WINDOW(mainwin->window);
1398         appdata->osso_context = osso_context;
1399         result = osso_rpc_set_cb_f(appdata->osso_context, 
1400                 OSSO_SERVICE, 
1401                 OSSO_OBJECT, 
1402                 OSSO_IFACE,
1403                 dbus_req_handler, appdata);
1404         if (result != OSSO_OK) {
1405                 return OSSO_ERROR;
1406         }
1407
1408 #ifndef CHINOOK
1409         /* Add handler for Exit D-BUS messages */
1410         result = osso_application_set_exit_cb(appdata->osso_context,
1411                                                 exit_event_handler,
1412                                                 (gpointer) appdata);
1413         if (result != OSSO_OK) {
1414                 return OSSO_ERROR;
1415         }
1416 #endif
1417         osso_hw_set_event_cb( appdata->osso_context,
1418                                 NULL, hw_event_handler, (gpointer) appdata );
1419 #endif
1420         manage_window_focus_in(mainwin->window, NULL, NULL);
1421         folderview = mainwin->folderview;
1422
1423         gtk_cmclist_freeze(GTK_CMCLIST(mainwin->folderview->ctree));
1424         folder_item_update_freeze();
1425
1426         prefs_account_init();
1427         account_read_config_all();
1428
1429 #ifdef HAVE_LIBETPAN
1430         imap_main_init(prefs_common.skip_ssl_cert_check);
1431         imap_main_set_timeout(prefs_common.io_timeout_secs);
1432         nntp_main_init(prefs_common.skip_ssl_cert_check);
1433 #endif  
1434         /* If we can't read a folder list or don't have accounts,
1435          * it means the configuration's not done. Either this is
1436          * a brand new install, either a failed/refused migration.
1437          * So we'll start the wizard.
1438          */
1439         if (folder_read_list() < 0) {
1440                 prefs_destroy_cache();
1441                 
1442                 /* if run_wizard returns FALSE it's because it's
1443                  * been cancelled. We can't do much but exit.
1444                  * however, if the user was asked for a migration,
1445                  * we remove the newly created directory so that
1446                  * he's asked again for migration on next launch.*/
1447                 if (!run_wizard(mainwin, TRUE)) {
1448                         if (asked_for_migration)
1449                                 remove_dir_recursive(RC_DIR);
1450 #ifdef G_OS_WIN32
1451                         win32_close_log();
1452 #endif
1453                         exit(1);
1454                 }
1455                 main_window_reflect_prefs_all_now();
1456                 folder_write_list();
1457                 never_ran = TRUE;
1458         }
1459
1460         if (!account_get_list()) {
1461                 prefs_destroy_cache();
1462                 if (!run_wizard(mainwin, FALSE)) {
1463                         if (asked_for_migration)
1464                                 remove_dir_recursive(RC_DIR);
1465 #ifdef G_OS_WIN32
1466                         win32_close_log();
1467 #endif
1468                         exit(1);
1469                 }
1470                 if(!account_get_list()) {
1471                         exit_claws(mainwin);
1472 #ifdef G_OS_WIN32
1473                         win32_close_log();
1474 #endif
1475                         exit(1);
1476                 }
1477                 never_ran = TRUE;
1478         }
1479
1480         
1481         toolbar_main_set_sensitive(mainwin);
1482         main_window_set_menu_sensitive(mainwin);
1483
1484         /* if crashed, show window early so that the user
1485          * sees what's happening */
1486         if (claws_crashed()) {
1487                 main_window_popup(mainwin);
1488                 mainwin_shown = TRUE;
1489         }
1490
1491         account_set_missing_folder();
1492         folder_set_missing_folders();
1493         folderview_set(folderview);
1494
1495         prefs_matcher_read_config();
1496         quicksearch_set_search_strings(mainwin->summaryview->quicksearch);
1497
1498         /* make one all-folder processing before using claws */
1499         main_window_cursor_wait(mainwin);
1500         folder_func_to_all_folders(initial_processing, (gpointer *)mainwin);
1501
1502         /* if claws crashed, rebuild caches */
1503         if (claws_crashed()) {
1504                 GTK_EVENTS_FLUSH();
1505                 debug_print("Claws Mail crashed, checking for new messages in local folders\n");
1506                 folder_item_update_thaw();
1507                 folderview_check_new(NULL);
1508                 folder_clean_cache_memory_force();
1509                 folder_item_update_freeze();
1510         }
1511         /* make the crash-indicator file */
1512         str_write_to_file("foo", get_crashfile_name());
1513
1514         inc_autocheck_timer_init(mainwin);
1515
1516         /* ignore SIGPIPE signal for preventing sudden death of program */
1517 #ifdef G_OS_UNIX
1518         signal(SIGPIPE, SIG_IGN);
1519 #endif
1520         if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
1521                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
1522         }
1523         if (cmd.online_mode == ONLINE_MODE_ONLINE) {
1524                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
1525         }
1526
1527         if (cmd.status_folders) {
1528                 g_ptr_array_free(cmd.status_folders, TRUE);
1529                 cmd.status_folders = NULL;
1530         }
1531         if (cmd.status_full_folders) {
1532                 g_ptr_array_free(cmd.status_full_folders, TRUE);
1533                 cmd.status_full_folders = NULL;
1534         }
1535
1536         claws_register_idle_function(claws_gtk_idle);
1537
1538         prefs_toolbar_init();
1539
1540         num_folder_class = g_list_length(folder_get_list());
1541
1542         plugin_load_all("GTK2");
1543
1544         if (g_list_length(folder_get_list()) != num_folder_class) {
1545                 debug_print("new folders loaded, reloading processing rules\n");
1546                 prefs_matcher_read_config();
1547         }
1548         
1549         if ((plug_list = plugin_get_unloaded_list()) != NULL) {
1550                 GSList *cur;
1551                 gchar *list = NULL;
1552                 gint num_plugins = 0;
1553                 for (cur = plug_list; cur; cur = cur->next) {
1554                         Plugin *plugin = (Plugin *)cur->data;
1555                         gchar *tmp = g_strdup_printf("%s\n%s",
1556                                 list? list:"",
1557                                 plugin_get_name(plugin));
1558                         g_free(list);
1559                         list = tmp;
1560                         num_plugins++;
1561                 }
1562                 main_window_cursor_normal(mainwin);
1563                 main_window_popup(mainwin);
1564                 mainwin_shown = TRUE;
1565                 alertpanel_warning(ngettext(
1566                                      "The following plugin failed to load. "
1567                                      "Check the Plugins configuration "
1568                                      "for more information:\n%s",
1569                                      "The following plugins failed to load. "
1570                                      "Check the Plugins configuration "
1571                                      "for more information:\n%s", 
1572                                      num_plugins), 
1573                                      list);
1574                 main_window_cursor_wait(mainwin);
1575                 g_free(list);
1576                 g_slist_free(plug_list);
1577         }
1578
1579         if (never_ran) {
1580                 prefs_common_write_config();
1581                 plugin_load_standard_plugins ();
1582         }
1583         /* if not crashed, show window now */
1584         if (!mainwin_shown) {
1585                 /* apart if something told not to show */
1586                 if (show_at_startup)
1587                         main_window_popup(mainwin);
1588         }
1589
1590         if (!folder_have_mailbox()) {
1591                 prefs_destroy_cache();
1592                 main_window_cursor_normal(mainwin);
1593                 if (folder_get_list() != NULL) {
1594                         alertpanel_error(_("Claws Mail has detected a configured "
1595                                    "mailbox, but it is incomplete. It is "
1596                                    "possibly due to a failing IMAP account. Use "
1597                                    "\"Rebuild folder tree\" on the mailbox parent "
1598                                    "folder's context menu to try to fix it."));
1599                 } else {
1600                         alertpanel_error(_("Claws Mail has detected a configured "
1601                                    "mailbox, but could not load it. It is "
1602                                    "probably provided by an out-of-date "
1603                                    "external plugin. Please reinstall the "
1604                                    "plugin and try again."));
1605                         exit_claws(mainwin);
1606 #ifdef G_OS_WIN32
1607                         win32_close_log();
1608 #endif
1609                         exit(1);
1610                 }
1611         }
1612         
1613         static_mainwindow = mainwin;
1614
1615 #ifdef MAEMO
1616         if (prefs_common.data_root != NULL && *prefs_common.data_root != '\0') {
1617                 GnomeVFSVolume *vol = NULL;
1618                 gchar *uri, *mount_path;
1619
1620                 volmon = gnome_vfs_get_volume_monitor();
1621                 vol = gnome_vfs_volume_monitor_get_volume_for_path(volmon, prefs_common.data_root);
1622
1623                 uri = gnome_vfs_volume_get_activation_uri (vol);
1624                 mount_path = uri?gnome_vfs_get_local_path_from_uri (uri):NULL;
1625                 g_free(uri);
1626
1627                 if (vol == NULL || !gnome_vfs_volume_is_mounted(vol) 
1628                     || strcmp(mount_path, prefs_common.data_root)) {
1629                         alertpanel_error(_("Claws Mail can not start without its data volume (%s)."), 
1630                                 prefs_common.data_root);
1631                         g_free(mount_path);
1632                         gnome_vfs_volume_unref(vol);
1633                         exit_claws(mainwin);
1634                         exit(1);
1635                 }
1636                 g_free(mount_path);
1637                 gnome_vfs_volume_unref(vol);
1638                 g_signal_connect(G_OBJECT(volmon), 
1639                                 "volume-mounted", G_CALLBACK(main_vol_mount_cb), mainwin);
1640                 g_signal_connect(G_OBJECT(volmon), 
1641                                 "volume-unmounted", G_CALLBACK(main_vol_unmount_cb), mainwin);
1642         }
1643 #endif
1644
1645 #ifdef HAVE_STARTUP_NOTIFICATION
1646         startup_notification_complete(FALSE);
1647 #endif
1648 #ifdef HAVE_LIBSM
1649         sc_session_manager_connect(mainwin);
1650 #endif
1651
1652         folder_item_update_thaw();
1653         gtk_cmclist_thaw(GTK_CMCLIST(mainwin->folderview->ctree));
1654         main_window_cursor_normal(mainwin);
1655
1656         if (!cmd.target && prefs_common.goto_last_folder_on_startup &&
1657             folder_find_item_from_identifier(prefs_common.last_opened_folder) != NULL &&
1658             !claws_crashed()) {
1659                 cmd.target = prefs_common.last_opened_folder;
1660         }
1661
1662         if (cmd.receive_all && !cmd.target) {
1663                 start_done = FALSE;
1664                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(FALSE));
1665         } else if (prefs_common.chk_on_startup && !cmd.target) {
1666                 start_done = FALSE;
1667                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(TRUE));
1668         } else if (cmd.receive && !cmd.target) {
1669                 start_done = FALSE;
1670                 g_timeout_add(1000, defer_check, NULL);
1671         } 
1672         gtk_widget_grab_focus(folderview->ctree);
1673
1674         if (cmd.compose) {
1675                 open_compose_new(cmd.compose_mailto, cmd.attach_files);
1676         }
1677         if (cmd.attach_files) {
1678                 list_free_strings(cmd.attach_files);
1679                 g_list_free(cmd.attach_files);
1680                 cmd.attach_files = NULL;
1681         }
1682         if (cmd.subscribe) {
1683                 folder_subscribe(cmd.subscribe_uri);
1684         }
1685
1686         if (cmd.send) {
1687                 send_queue();
1688         }
1689         
1690         if (cmd.target) {
1691                 start_done = FALSE;
1692                 g_timeout_add(500, defer_jump, (gpointer)cmd.target);
1693         }
1694
1695         prefs_destroy_cache();
1696         
1697         compose_reopen_exit_drafts();
1698
1699         if (start_done) {
1700                 sc_starting = FALSE;
1701                 main_window_set_menu_sensitive(mainwin);
1702                 toolbar_main_set_sensitive(mainwin);
1703         }
1704
1705         /* register the callback of unix domain socket input */
1706         lock_socket_tag = claws_input_add(lock_socket,
1707                                         G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_PRI,
1708                                         lock_socket_input_cb,
1709                                         mainwin, TRUE);
1710
1711         END_TIMING();
1712
1713         gtk_main();
1714
1715 #ifdef MAEMO
1716         osso_deinitialize(osso_context);
1717 #endif
1718 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1719         if(nm_proxy)
1720                 g_object_unref(nm_proxy);
1721 #endif
1722 #ifdef HAVE_DBUS_GLIB
1723         uninstall_dbus_status_handler();
1724         if(connection)
1725                 dbus_g_connection_unref(connection);
1726 #endif
1727 #ifdef G_OS_WIN32
1728         win32_close_log();
1729 #endif
1730         utils_free_regex();
1731         exit_claws(mainwin);
1732
1733         return 0;
1734 }
1735
1736 static void save_all_caches(FolderItem *item, gpointer data)
1737 {
1738         if (!item->cache) {
1739                 return;
1740         }
1741
1742         if (item->opened) {
1743                 folder_item_close(item);
1744         }
1745
1746         folder_item_free_cache(item, TRUE);
1747 }
1748
1749 static void exit_claws(MainWindow *mainwin)
1750 {
1751         gchar *filename;
1752         gboolean have_connectivity;
1753
1754         sc_exiting = TRUE;
1755
1756         debug_print("shutting down\n");
1757         inc_autocheck_timer_remove();
1758
1759 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1760         if (prefs_common.work_offline && went_offline_nm)
1761                 prefs_common.work_offline = FALSE;
1762 #endif
1763
1764         /* save prefs for opened folder */
1765         if(mainwin->folderview->opened) {
1766                 FolderItem *item;
1767
1768                 item = gtk_cmctree_node_get_row_data(GTK_CMCTREE(mainwin->folderview->ctree), mainwin->folderview->opened);
1769                 summary_save_prefs_to_folderitem(mainwin->folderview->summaryview, item);
1770                 prefs_common.last_opened_folder = folder_item_get_identifier(item);
1771         }
1772
1773         /* save all state before exiting */
1774         folder_func_to_all_folders(save_all_caches, NULL);
1775         folder_write_list();
1776
1777         main_window_get_size(mainwin);
1778         main_window_get_position(mainwin);
1779
1780         prefs_common_write_config();
1781         account_write_config_all();
1782 #ifndef USE_NEW_ADDRBOOK
1783         addressbook_export_to_file();
1784 #endif
1785         filename = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
1786         gtk_accel_map_save(filename);
1787         g_free(filename);
1788
1789         /* delete temporary files */
1790         remove_all_files(get_tmp_dir());
1791         remove_all_files(get_mime_tmp_dir());
1792
1793         close_log_file(LOG_PROTOCOL);
1794         close_log_file(LOG_DEBUG_FILTERING);
1795
1796 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1797         have_connectivity = networkmanager_is_online(NULL); 
1798 #else
1799         have_connectivity = TRUE;
1800 #endif
1801 #ifdef HAVE_LIBETPAN
1802         imap_main_done(have_connectivity);
1803         nntp_main_done(have_connectivity);
1804 #endif
1805         /* delete crashfile */
1806         if (!cmd.crash)
1807                 claws_unlink(get_crashfile_name());
1808
1809         lock_socket_remove();
1810
1811 #ifdef HAVE_LIBSM
1812         if (mainwin->smc_conn)
1813                 SmcCloseConnection ((SmcConn)mainwin->smc_conn, 0, NULL);
1814         mainwin->smc_conn = NULL;
1815 #endif
1816
1817         main_window_destroy_all();
1818         
1819         plugin_unload_all("GTK2");
1820
1821         matcher_done();
1822         prefs_toolbar_done();
1823
1824 #ifndef USE_NEW_ADDRBOOK
1825         addressbook_destroy();
1826 #endif
1827         prefs_themes_done();
1828         prefs_fonts_done();
1829         prefs_ext_prog_done();
1830         prefs_wrapping_done();
1831         prefs_compose_writing_done();
1832         prefs_msg_colors_done();
1833         prefs_image_viewer_done();
1834         image_viewer_done();
1835         prefs_quote_done();
1836         prefs_summaries_done();
1837         prefs_message_done();
1838         prefs_other_done();
1839         prefs_receive_done();
1840         prefs_logging_done();
1841         prefs_send_done();
1842         tags_write_tags();
1843 #ifdef USE_ENCHANT       
1844         prefs_spelling_done();
1845         gtkaspell_checkers_quit();
1846 #endif
1847         plugin_unload_all("Common");
1848         claws_done();
1849 }
1850
1851 #define G_STRING_APPEND_ENCODED_URI(gstring,source)     \
1852         {                                               \
1853                 gchar tmpbuf[BUFFSIZE];                 \
1854                 encode_uri(tmpbuf, BUFFSIZE, (source)); \
1855                 g_string_append((gstring), tmpbuf);     \
1856         }
1857
1858 #define G_PRINT_EXIT(msg)       \
1859         {                       \
1860                 g_print(msg);   \
1861                 exit(1);        \
1862         }
1863
1864 static GString * parse_cmd_compose_from_file(const gchar *fn)
1865 {
1866         GString *headers = g_string_new(NULL);
1867         GString *body = g_string_new(NULL);
1868         gchar *to = NULL;
1869         gchar *h;
1870         gchar *v;
1871         gchar fb[BUFFSIZE];
1872         FILE *fp;
1873         gboolean isstdin;
1874
1875         if (fn == NULL || *fn == '\0')
1876                 G_PRINT_EXIT(_("Missing filename\n"));
1877         isstdin = (*fn == '-' && *(fn + 1) == '\0');
1878         if (isstdin)
1879                 fp = stdin;
1880         else {
1881                 fp = g_fopen(fn, "r");
1882                 if (!fp)
1883                         G_PRINT_EXIT(_("Cannot open filename for reading\n"));
1884         }
1885
1886         while (fgets(fb, sizeof(fb), fp)) {
1887                 gchar *tmp;     
1888                 strretchomp(fb);
1889                 if (*fb == '\0')
1890                         break;
1891                 h = fb;
1892                 while (*h && *h != ':') { ++h; } /* search colon */
1893                 if (*h == '\0')
1894                         G_PRINT_EXIT(_("Malformed header\n"));
1895                 v = h + 1;
1896                 while (*v && *v == ' ') { ++v; } /* trim value start */
1897                 *h = '\0';
1898                 tmp = g_ascii_strdown(fb, -1); /* get header name */
1899                 if (!strcmp(tmp, "to")) {
1900                         if (to != NULL)
1901                                 G_PRINT_EXIT(_("Duplicated 'To:' header\n"));
1902                         to = g_strdup(v);
1903                 } else {
1904                         g_string_append_c(headers, '&');
1905                         g_string_append(headers, tmp);
1906                         g_string_append_c(headers, '=');
1907 #if GLIB_CHECK_VERSION(2,16,0)
1908                         g_string_append_uri_escaped(headers, v, NULL, TRUE);
1909 #else
1910                         G_STRING_APPEND_ENCODED_URI(headers, v);
1911 #endif  
1912                 }
1913                 g_free(tmp);
1914         }
1915         if (to == NULL)
1916                 G_PRINT_EXIT(_("Missing required 'To:' header\n"));
1917         g_string_append(body, to);
1918         g_free(to);
1919         g_string_append(body, "?body=");
1920         while (fgets(fb, sizeof(fb), fp)) {
1921 #if GLIB_CHECK_VERSION(2,16,0)
1922                 g_string_append_uri_escaped(body, fb, NULL, TRUE);
1923 #else
1924                 G_STRING_APPEND_ENCODED_URI(body, fb);
1925 #endif
1926         }
1927         if (!isstdin)
1928                 fclose(fp);
1929         /* append the remaining headers */
1930         g_string_append(body, headers->str);
1931         g_string_free(headers, TRUE);
1932
1933         return body;
1934 }
1935
1936 #undef G_STRING_APPEND_ENCODED_URI
1937 #undef G_PRINT_EXIT
1938
1939 static void parse_cmd_opt(int argc, char *argv[])
1940 {
1941         AttachInfo *ainfo;
1942         gint i;
1943
1944         for (i = 1; i < argc; i++) {
1945                 if (!strncmp(argv[i], "--receive-all", 13)) {
1946                         cmd.receive_all = TRUE;
1947                 } else if (!strncmp(argv[i], "--receive", 9)) {
1948                         cmd.receive = TRUE;
1949                 } else if (!strncmp(argv[i], "--cancel-receiving", 18)) {
1950                         cmd.cancel_receiving = TRUE;
1951                 } else if (!strncmp(argv[i], "--cancel-sending", 16)) {
1952                         cmd.cancel_sending = TRUE;
1953                 } else if (!strncmp(argv[i], "--compose-from-file", 19)) {
1954                         const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
1955
1956                         GString *mailto = parse_cmd_compose_from_file(p);
1957                         cmd.compose = TRUE;
1958                         cmd.compose_mailto = mailto->str;
1959                         i++;
1960                 } else if (!strncmp(argv[i], "--compose", 9)) {
1961                         const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
1962
1963                         cmd.compose = TRUE;
1964                         cmd.compose_mailto = NULL;
1965                         if (p && *p != '\0' && *p != '-') {
1966                                 if (!strncmp(p, "mailto:", 7)) {
1967                                         cmd.compose_mailto = p + 7;
1968                                 } else {
1969                                         cmd.compose_mailto = p;
1970                                 }
1971                                 i++;
1972                         }
1973                 } else if (!strncmp(argv[i], "--subscribe", 11)) {
1974                         const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
1975                         if (p && *p != '\0' && *p != '-') {
1976                                 cmd.subscribe = TRUE;
1977                                 cmd.subscribe_uri = p;
1978                         }
1979                 } else if (!strncmp(argv[i], "--attach", 8)) {
1980                         const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
1981                         gchar *file = NULL;
1982
1983                         while (p && *p != '\0' && *p != '-') {
1984                                 if ((file = g_filename_from_uri(p, NULL, NULL)) != NULL) {
1985                                         if (!is_file_exist(file)) {
1986                                                 g_free(file);
1987                                                 file = NULL;
1988                                         }
1989                                 }
1990                                 if (file == NULL && *p != G_DIR_SEPARATOR) {
1991                                         file = g_strconcat(claws_get_startup_dir(),
1992                                                            G_DIR_SEPARATOR_S,
1993                                                            p, NULL);
1994                                 } else if (file == NULL) {
1995                                         file = g_strdup(p);
1996                                 }
1997                                 ainfo = g_new0(AttachInfo, 1);
1998                                 ainfo->file = file;
1999                                 cmd.attach_files = g_list_append(cmd.attach_files, ainfo);
2000                                 i++;
2001                                 p = (i+1 < argc)?argv[i+1]:NULL;
2002                         }
2003                 } else if (!strncmp(argv[i], "--send", 6)) {
2004                         cmd.send = TRUE;
2005                 } else if (!strncmp(argv[i], "--version-full", 14) ||
2006                            !strncmp(argv[i], "-V", 2)) {
2007                         g_print("Claws Mail version " VERSION "\n");
2008                         main_dump_features_list(FALSE);
2009                         exit(0);
2010                 } else if (!strncmp(argv[i], "--version", 9) ||
2011                            !strncmp(argv[i], "-v", 2)) {
2012                         g_print("Claws Mail version " VERSION "\n");
2013                         exit(0);
2014                 } else if (!strncmp(argv[i], "--status-full", 13)) {
2015                         const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
2016  
2017                         cmd.status_full = TRUE;
2018                         while (p && *p != '\0' && *p != '-') {
2019                                 if (!cmd.status_full_folders) {
2020                                         cmd.status_full_folders =
2021                                                 g_ptr_array_new();
2022                                 }
2023                                 g_ptr_array_add(cmd.status_full_folders,
2024                                                 g_strdup(p));
2025                                 i++;
2026                                 p = (i+1 < argc)?argv[i+1]:NULL;
2027                         }
2028                 } else if (!strncmp(argv[i], "--status", 8)) {
2029                         const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
2030  
2031                         cmd.status = TRUE;
2032                         while (p && *p != '\0' && *p != '-') {
2033                                 if (!cmd.status_folders)
2034                                         cmd.status_folders = g_ptr_array_new();
2035                                 g_ptr_array_add(cmd.status_folders,
2036                                                 g_strdup(p));
2037                                 i++;
2038                                 p = (i+1 < argc)?argv[i+1]:NULL;
2039                         }
2040                 } else if (!strncmp(argv[i], "--search", 8)) {
2041                         cmd.search_folder    = (i+1 < argc)?argv[i+1]:NULL;
2042                         cmd.search_type      = (i+2 < argc)?argv[i+2]:NULL;
2043                         cmd.search_request   = (i+3 < argc)?argv[i+3]:NULL;
2044                         const char* rec      = (i+4 < argc)?argv[i+4]:NULL;
2045                         cmd.search_recursive = TRUE;
2046                         if (rec && (tolower(*rec)=='n' || tolower(*rec)=='f' || *rec=='0'))
2047                                 cmd.search_recursive = FALSE;
2048                         if (cmd.search_folder && cmd.search_type && cmd.search_request)
2049                                 cmd.search = TRUE;
2050                 } else if (!strncmp(argv[i], "--online", 8)) {
2051                         cmd.online_mode = ONLINE_MODE_ONLINE;
2052                 } else if (!strncmp(argv[i], "--offline", 9)) {
2053                         cmd.online_mode = ONLINE_MODE_OFFLINE;
2054                 } else if (!strncmp(argv[i], "--statistics", 12)) {
2055                         cmd.statistics = TRUE;
2056                 } else if (!strncmp(argv[i], "--reset-statistics", 18)) {
2057                         cmd.reset_statistics = TRUE;
2058                 } else if (!strncmp(argv[i], "--help", 6) ||
2059                            !strncmp(argv[i], "-h", 2)) {
2060                         gchar *base = g_path_get_basename(argv[0]);
2061                         g_print(_("Usage: %s [OPTION]...\n"), base);
2062
2063                         g_print("%s\n", _("  --compose [address]    open composition window"));
2064                         g_print("%s\n", _("  --compose-from-file file\n"
2065                                           "                         open composition window with data from given file;\n"
2066                                           "                         use - as file name for reading from standard input;\n"
2067                                           "                         content format: headers first (To: required) until an\n"
2068                                           "                         empty line, then mail body until end of file."));
2069                         g_print("%s\n", _("  --subscribe [uri]      subscribe to the given URI if possible"));
2070                         g_print("%s\n", _("  --attach file1 [file2]...\n"
2071                                           "                         open composition window with specified files\n"
2072                                           "                         attached"));
2073                         g_print("%s\n", _("  --receive              receive new messages"));
2074                         g_print("%s\n", _("  --receive-all          receive new messages of all accounts"));
2075                         g_print("%s\n", _("  --cancel-receiving     cancel receiving of messages"));
2076                         g_print("%s\n", _("  --cancel-sending       cancel sending of messages"));
2077                         g_print("%s\n", _("  --search folder type request [recursive]\n"
2078                                           "                         searches mail\n"
2079                                           "                         folder ex.: \"#mh/Mailbox/inbox\" or \"Mail\"\n"
2080                                           "                         type: s[ubject],f[rom],t[o],e[xtended],m[ixed] or g: tag\n"
2081                                           "                         request: search string\n"
2082                                           "                         recursive: false if arg. starts with 0, n, N, f or F"));
2083
2084                         g_print("%s\n", _("  --send                 send all queued messages"));
2085                         g_print("%s\n", _("  --status [folder]...   show the total number of messages"));
2086                         g_print("%s\n", _("  --status-full [folder]...\n"
2087                                           "                         show the status of each folder"));
2088                         g_print("%s\n", _("  --statistics           show session statistics"));
2089                         g_print("%s\n", _("  --reset-statistics     reset session statistics"));
2090                         g_print("%s\n", _("  --select folder[/msg]  jumps to the specified folder/message\n" 
2091                                           "                         folder is a folder id like 'folder/sub_folder'"));
2092                         g_print("%s\n", _("  --online               switch to online mode"));
2093                         g_print("%s\n", _("  --offline              switch to offline mode"));
2094                         g_print("%s\n", _("  --exit --quit -q       exit Claws Mail"));
2095                         g_print("%s\n", _("  --debug                debug mode"));
2096                         g_print("%s\n", _("  --help -h              display this help and exit"));
2097                         g_print("%s\n", _("  --version -v           output version information and exit"));
2098                         g_print("%s\n", _("  --version-full -V      output version and built-in features information and exit"));
2099                         g_print("%s\n", _("  --config-dir           output configuration directory"));
2100                         g_print("%s\n", _("  --alternate-config-dir [dir]\n"
2101                                           "                         use specified configuration directory"));
2102
2103                         g_free(base);
2104                         exit(1);
2105                 } else if (!strncmp(argv[i], "--crash", 7)) {
2106                         cmd.crash = TRUE;
2107                         cmd.crash_params = g_strdup((i+1 < argc)?argv[i+1]:NULL);
2108                         i++;
2109                 } else if (!strncmp(argv[i], "--config-dir", sizeof "--config-dir" - 1)) {
2110                         g_print(RC_DIR "\n");
2111                         exit(0);
2112                 } else if (!strncmp(argv[i], "--alternate-config-dir", sizeof "--alternate-config-dir" - 1) && i+1 < argc) {
2113                         set_rc_dir(argv[i+1]);
2114                 } else if (!strncmp(argv[i], "--exit", 6) ||
2115                            !strncmp(argv[i], "--quit", 6) ||
2116                            !strncmp(argv[i], "-q", 2)) {
2117                         cmd.exit = TRUE;
2118                 } else if (!strncmp(argv[i], "--select", 8) && i+1 < argc) {
2119                         cmd.target = argv[i+1];
2120                 } else if (i == 1 && argc == 2) {
2121                         /* only one parameter. Do something intelligent about it */
2122                         if ((strstr(argv[i], "@")||!strncmp(argv[i], "mailto:", 7)) && !strstr(argv[i], "://")) {
2123                                 const gchar *p = argv[i];
2124
2125                                 cmd.compose = TRUE;
2126                                 cmd.compose_mailto = NULL;
2127                                 if (p && *p != '\0' && *p != '-') {
2128                                         if (!strncmp(p, "mailto:", 7)) {
2129                                                 cmd.compose_mailto = p + 7;
2130                                         } else {
2131                                                 cmd.compose_mailto = p;
2132                                         }
2133                                 }
2134                         } else if (!strncmp(argv[i], "file://", 7)) {
2135                                 cmd.target = argv[i];
2136                         } else if (!strncmp(argv[i], "?attach=file://", strlen("?attach=file://"))) {
2137                                 cmd.compose = TRUE;
2138                                 cmd.compose_mailto = argv[i];
2139                         } else if (strstr(argv[i], "://")) {
2140                                 const gchar *p = argv[i];
2141                                 if (p && *p != '\0' && *p != '-') {
2142                                         cmd.subscribe = TRUE;
2143                                         cmd.subscribe_uri = p;
2144                                 }
2145                         } else if (!strcmp(argv[i], "--sync")) {
2146                                 /* gtk debug */
2147                         } else if (is_dir_exist(argv[i]) || is_file_exist(argv[i])) {
2148                                 cmd.target = argv[i];
2149                         } else {
2150                                 g_print(_("Unknown option\n"));
2151                                 exit(1);
2152                         }
2153                 }
2154         }
2155
2156         if (cmd.attach_files && cmd.compose == FALSE) {
2157                 cmd.compose = TRUE;
2158                 cmd.compose_mailto = NULL;
2159         }
2160 }
2161
2162 static void initial_processing(FolderItem *item, gpointer data)
2163 {
2164         MainWindow *mainwin = (MainWindow *)data;
2165         gchar *buf;
2166
2167         cm_return_if_fail(item);
2168         buf = g_strdup_printf(_("Processing (%s)..."), 
2169                               item->path 
2170                               ? item->path 
2171                               : _("top level folder"));
2172         g_free(buf);
2173
2174         
2175         if (item->prefs->enable_processing) {
2176                 item->processing_pending = TRUE;
2177                 folder_item_apply_processing(item);
2178                 item->processing_pending = FALSE;
2179         }
2180
2181         STATUSBAR_POP(mainwin);
2182 }
2183
2184 static gboolean draft_all_messages(void)
2185 {
2186         GList *compose_list = NULL;
2187         
2188         compose_clear_exit_drafts();
2189         compose_list = compose_get_compose_list();
2190         while (compose_list != NULL) {
2191                 Compose *c = (Compose*)compose_list->data;
2192                 if (!compose_draft(c, COMPOSE_DRAFT_FOR_EXIT))
2193                         return FALSE;
2194                 compose_list = compose_get_compose_list();
2195         }
2196         return TRUE;
2197 }
2198 gboolean clean_quit(gpointer data)
2199 {
2200         static gboolean firstrun = TRUE;
2201
2202         if (!firstrun) {
2203                 return FALSE;
2204         }
2205         firstrun = FALSE;
2206
2207         /*!< Good idea to have the main window stored in a 
2208          *   static variable so we can check that variable
2209          *   to see if we're really allowed to do things
2210          *   that actually the spawner is supposed to 
2211          *   do (like: sending mail, composing messages).
2212          *   Because, really, if we're the spawnee, and
2213          *   we touch GTK stuff, we're hosed. See the 
2214          *   next fixme. */
2215
2216         /* FIXME: Use something else to signal that we're
2217          * in the original spawner, and not in a spawned
2218          * child. */
2219         if (!static_mainwindow) {
2220                 return FALSE;
2221         }
2222                 
2223         draft_all_messages();
2224         emergency_exit = TRUE;
2225         exit_claws(static_mainwindow);
2226         exit(0);
2227
2228         return FALSE;
2229 }
2230
2231 void app_will_exit(GtkWidget *widget, gpointer data)
2232 {
2233         MainWindow *mainwin = data;
2234         
2235         if (gtk_main_level() == 0) {
2236                 debug_print("not even started\n");
2237                 return;
2238         }
2239         if (sc_exiting == TRUE) {
2240                 debug_print("exit pending\n");
2241                 return;
2242         }
2243         sc_exiting = TRUE;
2244         debug_print("exiting\n");
2245         if (compose_get_compose_list()) {
2246                 if (!draft_all_messages()) {
2247                         main_window_popup(mainwin);
2248                         sc_exiting = FALSE;
2249                         return;
2250                 }
2251         }
2252
2253         if (prefs_common.warn_queued_on_exit && procmsg_have_queued_mails_fast()) {
2254                 if (alertpanel(_("Queued messages"),
2255                                _("Some unsent messages are queued. Exit now?"),
2256                                GTK_STOCK_CANCEL, GTK_STOCK_OK, NULL)
2257                     != G_ALERTALTERNATE) {
2258                         main_window_popup(mainwin);
2259                         sc_exiting = FALSE;
2260                         return;
2261                 }
2262                 manage_window_focus_in(mainwin->window, NULL, NULL);
2263         }
2264
2265         sock_cleanup();
2266 #ifdef HAVE_VALGRIND
2267         if (RUNNING_ON_VALGRIND) {
2268                 summary_clear_list(mainwin->summaryview);
2269         }
2270 #endif
2271         if (folderview_get_selected_item(mainwin->folderview))
2272                 folder_item_close(folderview_get_selected_item(mainwin->folderview));
2273         gtk_main_quit();
2274 }
2275
2276 gboolean claws_is_exiting(void)
2277 {
2278         return sc_exiting;
2279 }
2280
2281 gboolean claws_is_starting(void)
2282 {
2283         return sc_starting;
2284 }
2285
2286 /*
2287  * CLAWS: want this public so crash dialog can delete the
2288  * lock file too
2289  */
2290 gchar *claws_get_socket_name(void)
2291 {
2292         static gchar *filename = NULL;
2293         const gchar *socket_dir = NULL;
2294         
2295         if (rc_dir_is_alt())
2296                 socket_dir = get_rc_dir();
2297         else
2298                 socket_dir = g_get_tmp_dir();
2299         if (filename == NULL) {
2300                 filename = g_strdup_printf("%s%cclaws-mail-%d",
2301                                            socket_dir, G_DIR_SEPARATOR,
2302 #if HAVE_GETUID
2303                                            getuid());
2304 #else
2305                                            0);                                          
2306 #endif
2307         }
2308
2309         return filename;
2310 }
2311
2312 static gchar *get_crashfile_name(void)
2313 {
2314         static gchar *filename = NULL;
2315
2316         if (filename == NULL) {
2317                 filename = g_strdup_printf("%s%cclaws-crashed",
2318                                            get_tmp_dir(), G_DIR_SEPARATOR);
2319         }
2320
2321         return filename;
2322 }
2323
2324 static gint prohibit_duplicate_launch(void)
2325 {
2326         gint uxsock;
2327         GList *curr;
2328 #ifdef G_OS_UNIX
2329         gchar *path;
2330
2331         path = claws_get_socket_name();
2332         /* Try to connect to the control socket */
2333         uxsock = fd_connect_unix(path);
2334         
2335         if (x_display == NULL)
2336                 x_display = g_strdup(g_getenv("DISPLAY"));
2337
2338         if (uxsock < 0) {
2339 #if HAVE_FLOCK
2340                 gchar *socket_lock;
2341                 gint lock_fd;
2342                 gint ret;
2343                 /* If connect failed, no other process is running.
2344                  * Unlink the potentially existing socket, then
2345                  * open it. This has to be done locking a temporary
2346                  * file to avoid the race condition where another
2347                  * process could have created the socket just in
2348                  * between.
2349                  */
2350                 socket_lock = g_strconcat(path, ".lock",
2351                                           NULL);
2352                 lock_fd = g_open(socket_lock, O_RDWR|O_CREAT, 0);
2353                 if (lock_fd < 0) {
2354                         debug_print("Couldn't open %s: %s (%d)\n", socket_lock,
2355                                 strerror(errno), errno);
2356                         g_free(socket_lock);
2357                         return -1;
2358                 }
2359                 if (flock(lock_fd, LOCK_EX) < 0) {
2360                         debug_print("Couldn't lock %s: %s (%d)\n", socket_lock,
2361                                 strerror(errno), errno);
2362                         close(lock_fd);
2363                         g_free(socket_lock);
2364                         return -1;
2365                 }
2366 #endif
2367
2368                 claws_unlink(path);
2369                 debug_print("Opening socket %s\n", path);
2370                 ret = fd_open_unix(path);
2371 #if HAVE_FLOCK
2372                 flock(lock_fd, LOCK_UN);
2373                 claws_unlink(socket_lock);
2374                 g_free(socket_lock);
2375 #endif
2376                 return ret;
2377         }
2378 #else
2379         HANDLE hmutex;
2380
2381         hmutex = CreateMutexA(NULL, FALSE, "ClawsMail");
2382         if (!hmutex) {
2383                 debug_print("cannot create Mutex\n");
2384                 return -1;
2385         }
2386         if (GetLastError() != ERROR_ALREADY_EXISTS) {
2387                 uxsock = fd_open_inet(50216);
2388                 if (uxsock < 0)
2389                         return 0;
2390                 return uxsock;
2391         }
2392
2393         uxsock = fd_connect_inet(50216);
2394         if (uxsock < 0)
2395                 return -1;
2396 #endif
2397         /* remote command mode */
2398
2399         debug_print("another Claws Mail instance is already running.\n");
2400
2401         if (cmd.receive_all) {
2402                 fd_write_all(uxsock, "receive_all\n", 12);
2403         } else if (cmd.receive) {
2404                 fd_write_all(uxsock, "receive\n", 8);
2405         } else if (cmd.cancel_receiving) {
2406                 fd_write_all(uxsock, "cancel_receiving\n", 17);
2407         } else if (cmd.cancel_sending) {
2408                 fd_write_all(uxsock, "cancel_sending\n", 15);
2409         } else if (cmd.compose && cmd.attach_files) {
2410                 gchar *str, *compose_str;
2411
2412                 if (cmd.compose_mailto) {
2413                         compose_str = g_strdup_printf("compose_attach %s\n",
2414                                                       cmd.compose_mailto);
2415                 } else {
2416                         compose_str = g_strdup("compose_attach\n");
2417                 }
2418
2419                 fd_write_all(uxsock, compose_str, strlen(compose_str));
2420                 g_free(compose_str);
2421
2422                 for (curr = cmd.attach_files; curr != NULL ; curr = curr->next) {
2423                         str = (gchar *) ((AttachInfo *)curr->data)->file;
2424                         fd_write_all(uxsock, str, strlen(str));
2425                         fd_write_all(uxsock, "\n", 1);
2426                 }
2427
2428                 fd_write_all(uxsock, ".\n", 2);
2429         } else if (cmd.compose) {
2430                 gchar *compose_str;
2431
2432                 if (cmd.compose_mailto) {
2433                         compose_str = g_strdup_printf
2434                                 ("compose %s\n", cmd.compose_mailto);
2435                 } else {
2436                         compose_str = g_strdup("compose\n");
2437                 }
2438
2439                 fd_write_all(uxsock, compose_str, strlen(compose_str));
2440                 g_free(compose_str);
2441         } else if (cmd.subscribe) {
2442                 gchar *str = g_strdup_printf("subscribe %s\n", cmd.subscribe_uri);
2443                 fd_write_all(uxsock, str, strlen(str));
2444                 g_free(str);
2445         } else if (cmd.send) {
2446                 fd_write_all(uxsock, "send\n", 5);
2447         } else if (cmd.online_mode == ONLINE_MODE_ONLINE) {
2448                 fd_write(uxsock, "online\n", 6);
2449         } else if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
2450                 fd_write(uxsock, "offline\n", 7);
2451         } else if (cmd.status || cmd.status_full) {
2452                 gchar buf[BUFFSIZE];
2453                 gint i;
2454                 const gchar *command;
2455                 GPtrArray *folders;
2456                 gchar *folder;
2457  
2458                 command = cmd.status_full ? "status-full\n" : "status\n";
2459                 folders = cmd.status_full ? cmd.status_full_folders :
2460                         cmd.status_folders;
2461  
2462                 fd_write_all(uxsock, command, strlen(command));
2463                 for (i = 0; folders && i < folders->len; ++i) {
2464                         folder = g_ptr_array_index(folders, i);
2465                         fd_write_all(uxsock, folder, strlen(folder));
2466                         fd_write_all(uxsock, "\n", 1);
2467                 }
2468                 fd_write_all(uxsock, ".\n", 2);
2469                 for (;;) {
2470                         fd_gets(uxsock, buf, sizeof(buf));
2471                         if (!strncmp(buf, ".\n", 2)) break;
2472                         fputs(buf, stdout);
2473                 }
2474         } else if (cmd.exit) {
2475                 fd_write_all(uxsock, "exit\n", 5);
2476         } else if (cmd.statistics) {
2477                 gchar buf[BUFSIZ];
2478                 fd_write(uxsock, "statistics\n", 11);
2479                 for (;;) {
2480                         fd_gets(uxsock, buf, sizeof(buf));
2481                         if (!strncmp(buf, ".\n", 2)) break;
2482                         fputs(buf, stdout);
2483                 }
2484         } else if (cmd.reset_statistics) {
2485                 fd_write(uxsock, "reset_statistics\n", 17);
2486         } else if (cmd.target) {
2487                 gchar *str = g_strdup_printf("select %s\n", cmd.target);
2488                 fd_write_all(uxsock, str, strlen(str));
2489                 g_free(str);
2490         } else if (cmd.search) {
2491                 gchar buf[BUFFSIZE];
2492                 gchar *str =
2493                         g_strdup_printf("search %s\n%s\n%s\n%c\n",
2494                                                         cmd.search_folder, cmd.search_type, cmd.search_request,
2495                                                         (cmd.search_recursive==TRUE)?'1':'0');
2496                 fd_write_all(uxsock, str, strlen(str));
2497                 g_free(str);
2498                 for (;;) {
2499                         fd_gets(uxsock, buf, sizeof(buf));
2500                         if (!strncmp(buf, ".\n", 2)) break;
2501                         fputs(buf, stdout);
2502                 }
2503         } else {
2504 #ifndef G_OS_WIN32
2505                 gchar buf[BUFSIZ];
2506                 fd_write_all(uxsock, "get_display\n", 12);
2507                 memset(buf, 0, sizeof(buf));
2508                 fd_gets(uxsock, buf, sizeof(buf));
2509                 if (strcmp2(buf, x_display)) {
2510                         g_print("Claws Mail is already running on display %s.\n",
2511                                 buf);
2512                 } else {
2513                         fd_close(uxsock);
2514                         uxsock = fd_connect_unix(path);
2515                         fd_write_all(uxsock, "popup\n", 6);
2516                 }
2517 #else
2518                 fd_write_all(uxsock, "popup\n", 6);
2519 #endif
2520         }
2521
2522         fd_close(uxsock);
2523         return -1;
2524 }
2525
2526 static gint lock_socket_remove(void)
2527 {
2528 #ifdef G_OS_UNIX
2529         gchar *filename;
2530 #endif
2531         if (lock_socket < 0) {
2532                 return -1;
2533         }
2534
2535         if (lock_socket_tag > 0) {
2536                 g_source_remove(lock_socket_tag);
2537         }
2538         fd_close(lock_socket);
2539
2540 #ifdef G_OS_UNIX
2541         filename = claws_get_socket_name();
2542         claws_unlink(filename);
2543 #endif
2544
2545         return 0;
2546 }
2547
2548 static GPtrArray *get_folder_item_list(gint sock)
2549 {
2550         gchar buf[BUFFSIZE];
2551         FolderItem *item;
2552         GPtrArray *folders = NULL;
2553
2554         for (;;) {
2555                 fd_gets(sock, buf, sizeof(buf));
2556                 if (!strncmp(buf, ".\n", 2)) {
2557                         break;
2558                 }
2559                 strretchomp(buf);
2560                 if (!folders) {
2561                         folders = g_ptr_array_new();
2562                 }
2563                 item = folder_find_item_from_identifier(buf);
2564                 if (item) {
2565                         g_ptr_array_add(folders, item);
2566                 } else {
2567                         g_warning("no such folder: %s\n", buf);
2568                 }
2569         }
2570
2571         return folders;
2572 }
2573
2574 static void lock_socket_input_cb(gpointer data,
2575                                  gint source,
2576                                  GIOCondition condition)
2577 {
2578         MainWindow *mainwin = (MainWindow *)data;
2579         gint sock;
2580         gchar buf[BUFFSIZE];
2581
2582         sock = fd_accept(source);
2583         fd_gets(sock, buf, sizeof(buf));
2584
2585         if (!strncmp(buf, "popup", 5)) {
2586                 main_window_popup(mainwin);
2587         } else if (!strncmp(buf, "get_display", 11)) {
2588                 fd_write_all(sock, x_display, strlen(x_display));
2589         } else if (!strncmp(buf, "receive_all", 11)) {
2590                 inc_all_account_mail(mainwin, FALSE,
2591                                      prefs_common.newmail_notify_manu);
2592         } else if (!strncmp(buf, "receive", 7)) {
2593                 inc_mail(mainwin, prefs_common.newmail_notify_manu);
2594         } else if (!strncmp(buf, "cancel_receiving", 16)) {
2595                 inc_cancel_all();
2596                 imap_cancel_all();
2597         } else if (!strncmp(buf, "cancel_sending", 14)) {
2598                 send_cancel();
2599         } else if (!strncmp(buf, "compose_attach", 14)) {
2600                 GList *files = NULL, *curr;
2601                 AttachInfo *ainfo;
2602                 gchar *mailto;
2603
2604                 mailto = g_strdup(buf + strlen("compose_attach") + 1);
2605                 while (fd_gets(sock, buf, sizeof(buf)) > 0) {
2606                         strretchomp(buf);
2607                         if (!strcmp2(buf, "."))
2608                                 break;
2609                                 
2610                         ainfo = g_new0(AttachInfo, 1);
2611                         ainfo->file = g_strdup(buf);
2612                         files = g_list_append(files, ainfo);
2613                 }
2614                 open_compose_new(mailto, files);
2615                 
2616                 curr = g_list_first(files);
2617                 while (curr != NULL) {
2618                         ainfo = (AttachInfo *)curr->data;
2619                         g_free(ainfo->file);
2620                         g_free(ainfo);
2621                         curr = curr->next;
2622                 }
2623                 g_list_free(files);
2624                 g_free(mailto);
2625         } else if (!strncmp(buf, "compose", 7)) {
2626                 open_compose_new(buf + strlen("compose") + 1, NULL);
2627         } else if (!strncmp(buf, "subscribe", 9)) {
2628                 main_window_popup(mainwin);
2629                 folder_subscribe(buf + strlen("subscribe") + 1);
2630         } else if (!strncmp(buf, "send", 4)) {
2631                 send_queue();
2632         } else if (!strncmp(buf, "online", 6)) {
2633                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
2634         } else if (!strncmp(buf, "offline", 7)) {
2635                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
2636         } else if (!strncmp(buf, "status-full", 11) ||
2637                    !strncmp(buf, "status", 6)) {
2638                 gchar *status;
2639                 GPtrArray *folders;
2640  
2641                 folders = get_folder_item_list(sock);
2642                 status = folder_get_status
2643                         (folders, !strncmp(buf, "status-full", 11));
2644                 fd_write_all(sock, status, strlen(status));
2645                 fd_write_all(sock, ".\n", 2);
2646                 g_free(status);
2647                 if (folders) g_ptr_array_free(folders, TRUE);
2648         } else if (!strncmp(buf, "statistics", 10)) {
2649                 gchar tmp[BUFSIZ];
2650
2651                 g_snprintf(tmp, sizeof(tmp), _("Session statistics\n"));
2652                 fd_write_all(sock, tmp, strlen(tmp));
2653
2654                 if (prefs_common.date_format) {
2655                         struct tm *lt;
2656                         gint len = 100;
2657                         gchar date[len];
2658
2659                         lt = localtime(&session_stats.time_started);
2660                         fast_strftime(date, len, prefs_common.date_format, lt);
2661                         g_snprintf(tmp, sizeof(tmp), _("Started: %s\n"),
2662                                         lt ? date : ctime(&session_stats.time_started));
2663                 } else
2664                         g_snprintf(tmp, sizeof(tmp), _("Started: %s\n"),
2665                                         ctime(&session_stats.time_started));
2666                 fd_write_all(sock, tmp, strlen(tmp));
2667
2668                 fd_write_all(sock, "\n", 1);
2669
2670                 g_snprintf(tmp, sizeof(tmp), _("Incoming traffic\n"));
2671                 fd_write_all(sock, tmp, strlen(tmp));
2672
2673                 g_snprintf(tmp, sizeof(tmp), _("Received messages: %d\n"),
2674                                 session_stats.received);
2675                 fd_write_all(sock, tmp, strlen(tmp));
2676
2677                 fd_write_all(sock, "\n", 1);
2678
2679                 g_snprintf(tmp, sizeof(tmp), _("Outgoing traffic\n"));
2680                 fd_write_all(sock, tmp, strlen(tmp));
2681
2682                 g_snprintf(tmp, sizeof(tmp), _("New/redirected messages: %d\n"),
2683                                 session_stats.sent);
2684                 fd_write_all(sock, tmp, strlen(tmp));
2685
2686                 g_snprintf(tmp, sizeof(tmp), _("Replied messages: %d\n"),
2687                                 session_stats.replied);
2688                 fd_write_all(sock, tmp, strlen(tmp));
2689
2690                 g_snprintf(tmp, sizeof(tmp), _("Forwarded messages: %d\n"),
2691                                 session_stats.forwarded);
2692                 fd_write_all(sock, tmp, strlen(tmp));
2693
2694                 g_snprintf(tmp, sizeof(tmp), _("Total outgoing messages: %d\n"),
2695                                 (session_stats.sent + session_stats.replied +
2696                                  session_stats.forwarded));
2697                 fd_write_all(sock, tmp, strlen(tmp));
2698
2699                 fd_write_all(sock, ".\n", 2);
2700         } else if (!strncmp(buf, "reset_statistics", 16)) {
2701                 reset_statistics();
2702         } else if (!strncmp(buf, "select ", 7)) {
2703                 const gchar *target = buf+7;
2704                 mainwindow_jump_to(target, TRUE);
2705         } else if (!strncmp(buf, "search ", 7)) {
2706                 FolderItem* folderItem = NULL;
2707                 GSList *messages = NULL;
2708                 gchar *folder_name = NULL;
2709                 gchar *request = NULL;
2710                 AdvancedSearch *search;
2711                 gboolean recursive;
2712                 AdvancedSearchType searchType = ADVANCED_SEARCH_EXTENDED;
2713                 
2714                 search = advsearch_new();
2715
2716                 folder_name = g_strdup(buf+7);
2717                 strretchomp(folder_name);
2718
2719                 if (fd_gets(sock, buf, sizeof(buf)) <= 0) 
2720                         goto search_exit;
2721
2722                 switch (toupper(buf[0])) {
2723                 case 'S': searchType = ADVANCED_SEARCH_SUBJECT; break;
2724                 case 'F': searchType = ADVANCED_SEARCH_FROM; break;
2725                 case 'T': searchType = ADVANCED_SEARCH_TO; break;
2726                 case 'M': searchType = ADVANCED_SEARCH_MIXED; break;
2727                 case 'G': searchType = ADVANCED_SEARCH_TAG; break;
2728                 case 'E': searchType = ADVANCED_SEARCH_EXTENDED; break;
2729                 }
2730
2731                 if (fd_gets(sock, buf, sizeof(buf)) <= 0) 
2732                         goto search_exit;
2733
2734                 request = g_strdup(buf);
2735                 strretchomp(request);
2736
2737                 recursive = TRUE;
2738                 if (fd_gets(sock, buf, sizeof(buf)) > 0)
2739                         recursive = buf[0] != '0';
2740
2741                 debug_print("search: %s %i %s %i\n", folder_name, searchType, request, recursive);
2742
2743                 if (folder_name)
2744                         folderItem = folder_find_item_from_identifier(folder_name);
2745
2746                 if (folder_name && folderItem == NULL) {
2747                         debug_print("Unknown folder item : '%s', searching folder\n",folder_name);
2748                         Folder* folder = folder_find_from_path(folder_name);
2749                         if (folder != NULL)
2750                                 folderItem = FOLDER_ITEM(folder->node->data);
2751                         else
2752                                 debug_print("Unknown folder: '%s'\n",folder_name);
2753                 } else {
2754                         debug_print("%s %s\n",folderItem->name, folderItem->path);
2755                 }
2756
2757                 if (folderItem != NULL) {
2758                         advsearch_set(search, searchType, request);
2759                         advsearch_search_msgs_in_folders(search, &messages, folderItem, recursive);
2760                 } else {
2761                         g_print("Folder '%s' not found.\n'", folder_name);
2762                 }
2763
2764                 GSList *cur;
2765                 for (cur = messages; cur != NULL; cur = cur->next) {
2766                         MsgInfo* msg = (MsgInfo *)cur->data;
2767                         gchar *file = procmsg_get_message_file_path(msg);
2768                         fd_write_all(sock, file, strlen(file));
2769                         fd_write_all(sock, "\n", 1);
2770                         g_free(file);
2771                 }
2772                 fd_write_all(sock, ".\n", 2);
2773
2774 search_exit:
2775                 g_free(folder_name);
2776                 g_free(request);
2777                 advsearch_free(search);
2778                 if (messages != NULL)
2779                         procmsg_msg_list_free(messages);
2780         } else if (!strncmp(buf, "exit", 4)) {
2781                 if (prefs_common.clean_on_exit && !prefs_common.ask_on_clean) {
2782                         procmsg_empty_all_trash();
2783                 }
2784                 app_will_exit(NULL, mainwin);
2785         }
2786         fd_close(sock);
2787
2788 }
2789
2790 static void open_compose_new(const gchar *address, GList *attach_files)
2791 {
2792         gchar *addr = NULL;
2793
2794         if (address) {
2795                 Xstrdup_a(addr, address, return);
2796                 g_strstrip(addr);
2797         }
2798
2799         compose_new(NULL, addr, attach_files);
2800 }
2801
2802 static void send_queue(void)
2803 {
2804         GList *list;
2805         gchar *errstr = NULL;
2806         gboolean error = FALSE;
2807         for (list = folder_get_list(); list != NULL; list = list->next) {
2808                 Folder *folder = list->data;
2809
2810                 if (folder->queue) {
2811                         gint res = procmsg_send_queue
2812                                 (folder->queue, prefs_common.savemsg,
2813                                 &errstr);
2814
2815                         if (res) {
2816                                 folder_item_scan(folder->queue);
2817                         }
2818                         
2819                         if (res < 0)
2820                                 error = TRUE;
2821                 }
2822         }
2823         if (errstr) {
2824                 alertpanel_error_log(_("Some errors occurred "
2825                                 "while sending queued messages:\n%s"), errstr);
2826                 g_free(errstr);
2827         } else if (error) {
2828                 alertpanel_error_log("Some errors occurred "
2829                                 "while sending queued messages.");
2830         }
2831 }
2832
2833 static void quit_signal_handler(int sig)
2834 {
2835         debug_print("Quitting on signal %d\n", sig);
2836
2837         g_timeout_add(0, clean_quit, NULL);
2838 }
2839
2840 static void install_basic_sighandlers()
2841 {
2842 #ifndef G_OS_WIN32
2843         sigset_t    mask;
2844         struct sigaction act;
2845
2846         sigemptyset(&mask);
2847
2848 #ifdef SIGTERM
2849         sigaddset(&mask, SIGTERM);
2850 #endif
2851 #ifdef SIGINT
2852         sigaddset(&mask, SIGINT);
2853 #endif
2854 #ifdef SIGHUP
2855         sigaddset(&mask, SIGHUP);
2856 #endif
2857
2858         act.sa_handler = quit_signal_handler;
2859         act.sa_mask    = mask;
2860         act.sa_flags   = 0;
2861
2862 #ifdef SIGTERM
2863         sigaction(SIGTERM, &act, 0);
2864 #endif
2865 #ifdef SIGINT
2866         sigaction(SIGINT, &act, 0);
2867 #endif  
2868 #ifdef SIGHUP
2869         sigaction(SIGHUP, &act, 0);
2870 #endif  
2871
2872         sigprocmask(SIG_UNBLOCK, &mask, 0);
2873 #endif /* !G_OS_WIN32 */
2874 }
2875
2876 #if (defined linux && defined SIGIO)
2877 static int mem_notify_fd = 0;
2878
2879 static gboolean clean_caches(gpointer unused)
2880 {
2881         if (static_mainwindow && static_mainwindow->lock_count > 0)
2882                 return TRUE;
2883         debug_print("/dev/mem_notify: callback: Freeing some memory now!\n");
2884         folder_clean_cache_memory_force();
2885         return FALSE;
2886 }
2887
2888 static void memory_signal_handler(int sig)
2889 {
2890         debug_print("/dev/mem_notify: Kernel says we should free up some memory!\n");
2891         g_timeout_add(10, clean_caches, NULL); 
2892 }
2893
2894 static void install_memory_sighandler()
2895 {
2896         sigset_t    mask;
2897         struct sigaction act;
2898         int flags;
2899
2900         mem_notify_fd = g_open("/dev/mem_notify", O_RDONLY|O_NONBLOCK, 0);
2901         if (mem_notify_fd == -1) {
2902                 debug_print("/dev/mem_notify not available (%s)\n", 
2903                         strerror(errno));
2904                 return;
2905         }
2906         
2907         fcntl(mem_notify_fd, F_SETOWN, getpid());
2908         flags = fcntl(mem_notify_fd, F_GETFL);
2909         fcntl(mem_notify_fd, flags|FASYNC);
2910
2911         sigemptyset(&mask);
2912
2913         sigaddset(&mask, SIGIO);
2914
2915         act.sa_handler = memory_signal_handler;
2916         act.sa_mask    = mask;
2917         act.sa_flags   = 0;
2918
2919         sigaction(SIGIO, &act, 0);
2920
2921         sigprocmask(SIG_UNBLOCK, &mask, 0);
2922
2923         debug_print("/dev/mem_notify: installed handler\n");
2924 }
2925 #endif /* linux && SIGIO */
2926
2927 #ifdef MAEMO
2928 osso_context_t *get_osso_context(void)
2929 {
2930         return static_osso_context;
2931 }
2932 #endif
2933
2934
2935 #ifdef HAVE_NETWORKMANAGER_SUPPORT
2936 static void networkmanager_state_change_cb(DBusGProxy *proxy, gchar *dev,
2937                                          gpointer data)
2938 {
2939         MainWindow *mainWin;
2940
2941         mainWin = NULL;
2942         if (static_mainwindow)
2943                 mainWin = static_mainwindow;
2944         else if (data)
2945                 mainWin = (MainWindow*)data;
2946         
2947         if (!prefs_common.use_networkmanager)
2948                 return;
2949
2950         if (mainWin) {
2951                 GError *error;
2952                 gboolean online;
2953
2954                 error = NULL;           
2955                 online = networkmanager_is_online(&error);
2956                 if(!error) {
2957                         if(online && went_offline_nm) {
2958                                 went_offline_nm = FALSE;
2959                                 main_window_toggle_work_offline(mainWin, FALSE, FALSE);
2960                                 debug_print("NetworkManager: Went online\n");
2961                                 log_message(LOG_PROTOCOL, _("NetworkManager: network is online.\n"));
2962                         }
2963                         else if(!online) {
2964                                 went_offline_nm = TRUE;
2965                                 main_window_toggle_work_offline(mainWin, TRUE, FALSE);
2966                                 debug_print("NetworkManager: Went offline\n");
2967                                 log_message(LOG_PROTOCOL, _("NetworkManager: network is offline.\n"));
2968                         }
2969                 }
2970                 else {
2971                         debug_print("Failed to get online information from NetworkManager: %s\n",
2972                                                          error->message);
2973                         g_error_free(error);
2974                 }
2975         }
2976         else
2977                 debug_print("NetworkManager: Cannot change connection state because "
2978                                                  "main window does not exist\n");
2979 }
2980
2981 /* Returns true (and sets error appropriately, if given) in case of error */
2982 gboolean networkmanager_is_online(GError **error)
2983 {
2984         DBusGConnection *connection;
2985         DBusGProxy *proxy;
2986         GError *tmp_error = NULL;
2987         gboolean retVal;
2988         guint32 state;
2989
2990         if (!prefs_common.use_networkmanager)
2991                 return TRUE;
2992
2993         tmp_error = NULL;
2994         proxy = NULL;
2995         connection = dbus_g_bus_get(DBUS_BUS_SYSTEM, &tmp_error);
2996
2997         if(!connection) {
2998                 /* If calling code doesn't do error checking, at least print some debug */
2999                 if((error == NULL) || (*error == NULL))
3000                         debug_print("Failed to open connection to system bus: %s\n",
3001                                                          tmp_error->message);
3002                 g_propagate_error(error, tmp_error);
3003                 return TRUE;
3004         }
3005
3006         proxy = dbus_g_proxy_new_for_name(connection,
3007                         "org.freedesktop.NetworkManager",
3008                         "/org/freedesktop/NetworkManager",
3009                         "org.freedesktop.NetworkManager");
3010
3011         retVal = dbus_g_proxy_call(proxy,"state",&tmp_error, G_TYPE_INVALID,
3012                         G_TYPE_UINT, &state, G_TYPE_INVALID);
3013
3014         if(proxy)
3015                 g_object_unref(proxy);
3016         if(connection)
3017                 dbus_g_connection_unref(connection);
3018
3019         if(!retVal) {
3020                 /* If calling code doesn't do error checking, at least print some debug */
3021                 if((error == NULL) || (*error == NULL))
3022                         debug_print("Failed to get state info from NetworkManager: %s\n",
3023                                                          tmp_error->message);
3024                 g_propagate_error(error, tmp_error);
3025                 return TRUE;
3026         }
3027 #if NM_CHECK_VERSION(0,8,992)
3028         return (state == NM_STATE_CONNECTED_LOCAL ||
3029                 state == NM_STATE_CONNECTED_SITE ||
3030                 state == NM_STATE_CONNECTED_GLOBAL ||
3031                 state == NM_STATE_UNKNOWN);
3032 #else
3033         return (state == NM_STATE_CONNECTED ||
3034                 state == NM_STATE_UNKNOWN);
3035 #endif
3036 }
3037 #endif