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