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