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