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