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