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