No need to set window's position twice
[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, FALSE,
397                         keep_backup_chk, ALERT_QUESTION, G_ALERTDEFAULT) != 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
997         START_TIMING("startup");
998
999         sc_starting = TRUE;
1000
1001 #ifdef G_OS_WIN32
1002         win32_open_log();
1003 #endif
1004         if (!claws_init(&argc, &argv)) {
1005 #ifdef G_OS_WIN32
1006                 win32_close_log();
1007 #endif
1008                 return 0;
1009         }
1010
1011         prog_version = PROG_VERSION;
1012 #if (defined HAVE_LIBSM || defined CRASH_DIALOG)
1013         argv0 = g_strdup(argv[0]);
1014 #endif
1015
1016         parse_cmd_opt(argc, argv);
1017
1018         sock_init();
1019
1020         /* check and create unix domain socket for remote operation */
1021         lock_socket = prohibit_duplicate_launch();
1022         if (lock_socket < 0) {
1023 #ifdef HAVE_STARTUP_NOTIFICATION
1024                 if(gtk_init_check(&argc, &argv))
1025                         startup_notification_complete(TRUE);
1026 #endif
1027                 return 0;
1028         }
1029
1030         main_dump_features_list(TRUE);
1031         prefs_prepare_cache();
1032
1033 #ifdef CRASH_DIALOG
1034         if (cmd.crash) {
1035 #if !GTK_CHECK_VERSION(3, 0, 0)
1036                 gtk_set_locale();
1037 #endif
1038                 gtk_init(&argc, &argv);
1039                 crash_main(cmd.crash_params);
1040 #ifdef G_OS_WIN32
1041                 win32_close_log();
1042 #endif
1043                 return 0;
1044         }
1045         crash_install_handlers();
1046 #endif
1047         install_basic_sighandlers();
1048 #if (defined linux && defined SIGIO)
1049         install_memory_sighandler();
1050 #endif
1051
1052         if (cmd.status || cmd.status_full || cmd.search ||
1053                 cmd.statistics || cmd.reset_statistics || 
1054                 cmd.cancel_receiving || cmd.cancel_sending ||
1055                 cmd.debug) {
1056                 puts("0 Claws Mail not running.");
1057                 lock_socket_remove();
1058                 return 0;
1059         }
1060         
1061         if (cmd.exit)
1062                 return 0;
1063 #if !GLIB_CHECK_VERSION(2,32,0)
1064         if (!g_thread_supported())
1065                 g_thread_init(NULL);
1066 #endif
1067
1068         reset_statistics();
1069         
1070 #if !GTK_CHECK_VERSION(3, 0, 0)
1071         gtk_set_locale();
1072 #endif
1073         gtk_init(&argc, &argv);
1074
1075 #ifdef G_OS_WIN32
1076         gtk_settings_set_string_property(gtk_settings_get_default(),
1077                         "gtk-theme-name",
1078                         "MS-Windows",
1079                         "XProperty");
1080         gtk_settings_set_long_property(gtk_settings_get_default(),
1081                         "gtk-auto-mnemonics",
1082                         TRUE,
1083                         "XProperty");
1084         gtk_settings_set_long_property(gtk_settings_get_default(),
1085                         "gtk-button-images",
1086                         TRUE,
1087                         "XProperty");
1088 #endif
1089
1090 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1091         went_offline_nm = FALSE;
1092         nm_proxy = NULL;
1093 #endif
1094 #ifdef HAVE_DBUS_GLIB
1095         error = NULL;
1096         connection = dbus_g_bus_get(DBUS_BUS_SYSTEM, &error);
1097
1098         if(!connection) {
1099                 debug_print("Failed to open connection to system bus: %s\n", error->message);
1100                 g_error_free(error);
1101         }
1102         else {
1103 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1104                 nm_proxy = dbus_g_proxy_new_for_name(connection,
1105                         "org.freedesktop.NetworkManager",
1106                         "/org/freedesktop/NetworkManager",
1107                         "org.freedesktop.NetworkManager");
1108                 if (nm_proxy) {
1109 #if NM_CHECK_VERSION(0,8,992)
1110                         dbus_g_proxy_add_signal(nm_proxy, "StateChanged", G_TYPE_UINT, G_TYPE_INVALID);
1111                         dbus_g_proxy_connect_signal(nm_proxy, "StateChanged",
1112                                 G_CALLBACK(networkmanager_state_change_cb),
1113                                 NULL,NULL);
1114 #else
1115                         dbus_g_proxy_add_signal(nm_proxy, "StateChange", G_TYPE_UINT, G_TYPE_INVALID);
1116                         dbus_g_proxy_connect_signal(nm_proxy, "StateChange",
1117                                 G_CALLBACK(networkmanager_state_change_cb),
1118                                 NULL,NULL);
1119 #endif
1120                 }
1121 #endif
1122                 install_dbus_status_handler();
1123         }
1124 #endif
1125
1126 #if !GTK_CHECK_VERSION(3, 0, 0)
1127         gtk_widget_set_default_colormap(
1128                 gdk_screen_get_system_colormap(
1129                         gdk_screen_get_default()));
1130 #endif
1131
1132         gtkut_create_ui_manager();
1133
1134         /* Create container for all the menus we will be adding */
1135         MENUITEM_ADDUI("/", "Menus", NULL, GTK_UI_MANAGER_MENUBAR);
1136
1137         if (!g_thread_supported()) {
1138                 g_error(_("g_thread is not supported by glib.\n"));
1139         }
1140
1141 #ifdef G_OS_WIN32
1142         CHDIR_EXEC_CODE_RETURN_VAL_IF_FAIL(get_home_dir(), 1, win32_close_log(););
1143 #else
1144         CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
1145 #endif
1146         
1147         /* no config dir exists. See if we can migrate an old config. */
1148         if (!is_dir_exist(get_rc_dir())) {
1149                 prefs_destroy_cache();
1150                 gboolean r = FALSE;
1151                 
1152                 /* if one of the old dirs exist, we'll ask if the user 
1153                  * want to migrates, and r will be TRUE if he said yes
1154                  * and migration succeeded, and FALSE otherwise.
1155                  */
1156                 if (is_dir_exist(OLD_GTK2_RC_DIR)) {
1157                         r = migrate_old_config(OLD_GTK2_RC_DIR, get_rc_dir(),
1158                                                g_strconcat("Sylpheed-Claws 2.6.0 ", _("(or older)"), NULL));
1159                         asked_for_migration = TRUE;
1160                 } else if (is_dir_exist(OLDER_GTK2_RC_DIR)) {
1161                         r = migrate_old_config(OLDER_GTK2_RC_DIR, get_rc_dir(),
1162                                                g_strconcat("Sylpheed-Claws 1.9.15 ",_("(or older)"), NULL));
1163                         asked_for_migration = TRUE;
1164                 } else if (is_dir_exist(OLD_GTK1_RC_DIR)) {
1165                         r = migrate_old_config(OLD_GTK1_RC_DIR, get_rc_dir(),
1166                                                g_strconcat("Sylpheed-Claws 1.0.5 ",_("(or older)"), NULL));
1167                         asked_for_migration = TRUE;
1168                 } else if (is_dir_exist(SYLPHEED_RC_DIR)) {
1169                         r = migrate_old_config(SYLPHEED_RC_DIR, get_rc_dir(), "Sylpheed");
1170                         asked_for_migration = TRUE;
1171                 }
1172                 
1173                 /* If migration failed or the user didn't want to do it,
1174                  * we create a new one (and we'll hit wizard later). 
1175                  */
1176                 if (r == FALSE && !is_dir_exist(get_rc_dir())) {
1177 #ifdef G_OS_UNIX
1178                         if (copy_dir(SYSCONFDIR "/skel/.claws-mail", get_rc_dir()) < 0) {
1179 #endif
1180                                 if (!is_dir_exist(get_rc_dir()) && make_dir(get_rc_dir()) < 0) {
1181 #ifdef G_OS_WIN32
1182                                         win32_close_log();
1183 #endif
1184                                         exit(1);
1185                                 }
1186 #ifdef G_OS_UNIX
1187                         }
1188 #endif
1189                 }
1190         }
1191         
1192
1193         if (!is_file_exist(RC_DIR G_DIR_SEPARATOR_S COMMON_RC) &&
1194             is_file_exist(RC_DIR G_DIR_SEPARATOR_S OLD_COMMON_RC)) {
1195                 /* post 2.6 name change */
1196                 migrate_common_rc(RC_DIR G_DIR_SEPARATOR_S OLD_COMMON_RC,
1197                           RC_DIR G_DIR_SEPARATOR_S COMMON_RC);
1198         }
1199
1200         if (!cmd.exit)
1201                 plugin_load_all("Common");
1202
1203         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, "gtkrc-2.0", NULL);
1204         gtk_rc_parse(userrc);
1205         g_free(userrc);
1206
1207         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
1208         gtk_accel_map_load (userrc);
1209         g_free(userrc);
1210
1211 #ifdef G_OS_WIN32
1212         CHDIR_EXEC_CODE_RETURN_VAL_IF_FAIL(get_rc_dir(), 1, win32_close_log(););
1213 #else
1214         CHDIR_RETURN_VAL_IF_FAIL(get_rc_dir(), 1);
1215 #endif
1216
1217         MAKE_DIR_IF_NOT_EXIST(get_mail_base_dir());
1218         MAKE_DIR_IF_NOT_EXIST(get_imap_cache_dir());
1219         MAKE_DIR_IF_NOT_EXIST(get_news_cache_dir());
1220         MAKE_DIR_IF_NOT_EXIST(get_mime_tmp_dir());
1221         MAKE_DIR_IF_NOT_EXIST(get_tmp_dir());
1222         MAKE_DIR_IF_NOT_EXIST(UIDL_DIR);
1223
1224         crash_file_present = is_file_exist(get_crashfile_name());
1225         /* remove temporary files */
1226         remove_all_files(get_tmp_dir());
1227         remove_all_files(get_mime_tmp_dir());
1228
1229         if (!cmd.crash && crash_file_present)
1230                 claws_crashed_bool = TRUE;
1231
1232         if (is_file_exist("claws.log")) {
1233                 if (rename_force("claws.log", "claws.log.bak") < 0)
1234                         FILE_OP_ERROR("claws.log", "rename");
1235         }
1236         set_log_file(LOG_PROTOCOL, "claws.log");
1237
1238         if (is_file_exist("filtering.log")) {
1239                 if (rename_force("filtering.log", "filtering.log.bak") < 0)
1240                         FILE_OP_ERROR("filtering.log", "rename");
1241         }
1242         set_log_file(LOG_DEBUG_FILTERING, "filtering.log");
1243
1244 #ifdef G_OS_WIN32
1245         CHDIR_EXEC_CODE_RETURN_VAL_IF_FAIL(get_home_dir(), 1, win32_close_log(););
1246 #else
1247         CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
1248 #endif
1249
1250         folder_system_init();
1251         prefs_common_read_config();
1252
1253         if (prefs_update_config_version_common() < 0) {
1254                 debug_print("Main configuration file version upgrade failed, exiting\n");
1255 #ifdef G_OS_WIN32
1256                 win32_close_log();
1257 #endif
1258                 exit(200);
1259         }
1260
1261         prefs_themes_init();
1262         prefs_fonts_init();
1263         prefs_ext_prog_init();
1264         prefs_wrapping_init();
1265         prefs_compose_writing_init();
1266         prefs_msg_colors_init();
1267         image_viewer_init();
1268         prefs_image_viewer_init();
1269         prefs_quote_init();
1270         prefs_summaries_init();
1271         prefs_message_init();
1272         prefs_other_init();
1273         prefs_logging_init();
1274         prefs_receive_init();
1275         prefs_send_init();
1276         tags_read_tags();
1277         matcher_init();
1278 #ifdef USE_ENCHANT
1279         gtkaspell_checkers_init();
1280         prefs_spelling_init();
1281 #endif
1282
1283 #ifdef G_OS_WIN32
1284         if(prefs_common.gtk_theme && strcmp(prefs_common.gtk_theme, DEFAULT_W32_GTK_THEME))
1285                 gtk_settings_set_string_property(gtk_settings_get_default(),
1286                         "gtk-theme-name",
1287                         prefs_common.gtk_theme,
1288                         "XProperty");
1289 #endif
1290
1291
1292         sock_set_io_timeout(prefs_common.io_timeout_secs);
1293         prefs_actions_read_config();
1294         prefs_display_header_read_config();
1295         /* prefs_filtering_read_config(); */
1296 #ifndef USE_ALT_ADDRBOOK
1297         addressbook_read_file();
1298 #else
1299         g_clear_error(&error);
1300         if (! addressbook_start_service(&error)) {
1301                 g_warning("%s", error->message);
1302                 g_clear_error(&error);
1303         }
1304         else {
1305                 addressbook_install_hooks(&error);
1306         }
1307 #endif
1308         gtkut_widget_init();
1309         stock_pixbuf_gdk(STOCK_PIXMAP_CLAWS_MAIL_ICON, &icon);
1310         gtk_window_set_default_icon(icon);
1311
1312         folderview_initialize();
1313
1314         mh_gtk_init();
1315         imap_gtk_init();
1316         news_gtk_init();
1317
1318         mainwin = main_window_create();
1319
1320         if (!check_file_integrity())
1321                 exit(1);
1322
1323 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1324         networkmanager_state_change_cb(nm_proxy,NULL,mainwin);
1325 #endif
1326
1327         manage_window_focus_in(mainwin->window, NULL, NULL);
1328         folderview = mainwin->folderview;
1329
1330         folderview_freeze(mainwin->folderview);
1331         folder_item_update_freeze();
1332
1333         passwd_store_read_config();
1334
1335         if (prefs_update_config_version_password_store() < 0) {
1336                 debug_print("Password store configuration file version upgrade failed, exiting\n");
1337 #ifdef G_OS_WIN32
1338                 win32_close_log();
1339 #endif
1340                 exit(202);
1341         }
1342
1343         prefs_account_init();
1344         account_read_config_all();
1345
1346         if (prefs_update_config_version_accounts() < 0) {
1347                 debug_print("Accounts configuration file version upgrade failed, exiting\n");
1348 #ifdef G_OS_WIN32
1349                 win32_close_log();
1350 #endif
1351                 exit(201);
1352         }
1353
1354 #ifdef HAVE_LIBETPAN
1355         imap_main_init(prefs_common.skip_ssl_cert_check);
1356         imap_main_set_timeout(prefs_common.io_timeout_secs);
1357         nntp_main_init(prefs_common.skip_ssl_cert_check);
1358 #endif  
1359         /* If we can't read a folder list or don't have accounts,
1360          * it means the configuration's not done. Either this is
1361          * a brand new install, either a failed/refused migration.
1362          * So we'll start the wizard.
1363          */
1364         if (folder_read_list() < 0) {
1365                 prefs_destroy_cache();
1366                 
1367                 /* if run_wizard returns FALSE it's because it's
1368                  * been cancelled. We can't do much but exit.
1369                  * however, if the user was asked for a migration,
1370                  * we remove the newly created directory so that
1371                  * he's asked again for migration on next launch.*/
1372                 if (!run_wizard(mainwin, TRUE)) {
1373                         if (asked_for_migration)
1374                                 remove_dir_recursive(RC_DIR);
1375 #ifdef G_OS_WIN32
1376                         win32_close_log();
1377 #endif
1378                         exit(1);
1379                 }
1380                 main_window_reflect_prefs_all_now();
1381                 folder_write_list();
1382                 never_ran = TRUE;
1383         }
1384
1385         if (!account_get_list()) {
1386                 prefs_destroy_cache();
1387                 if (!run_wizard(mainwin, FALSE)) {
1388                         if (asked_for_migration)
1389                                 remove_dir_recursive(RC_DIR);
1390 #ifdef G_OS_WIN32
1391                         win32_close_log();
1392 #endif
1393                         exit(1);
1394                 }
1395                 if(!account_get_list()) {
1396                         exit_claws(mainwin);
1397 #ifdef G_OS_WIN32
1398                         win32_close_log();
1399 #endif
1400                         exit(1);
1401                 }
1402                 never_ran = TRUE;
1403         }
1404
1405         
1406         toolbar_main_set_sensitive(mainwin);
1407         main_window_set_menu_sensitive(mainwin);
1408
1409         /* if crashed, show window early so that the user
1410          * sees what's happening */
1411         if (claws_crashed()) {
1412                 main_window_popup(mainwin);
1413                 mainwin_shown = TRUE;
1414         }
1415
1416         account_set_missing_folder();
1417         folder_set_missing_folders();
1418         folderview_set(folderview);
1419
1420         prefs_matcher_read_config();
1421         quicksearch_set_search_strings(mainwin->summaryview->quicksearch);
1422
1423         /* make one all-folder processing before using claws */
1424         main_window_cursor_wait(mainwin);
1425         folder_func_to_all_folders(initial_processing, (gpointer *)mainwin);
1426
1427         /* if claws crashed, rebuild caches */
1428         if (claws_crashed()) {
1429                 GTK_EVENTS_FLUSH();
1430                 debug_print("Claws Mail crashed, checking for new messages in local folders\n");
1431                 folder_item_update_thaw();
1432                 folderview_check_new(NULL);
1433                 folder_clean_cache_memory_force();
1434                 folder_item_update_freeze();
1435         }
1436         /* make the crash-indicator file */
1437         str_write_to_file("foo", get_crashfile_name());
1438
1439         inc_autocheck_timer_init(mainwin);
1440
1441         /* ignore SIGPIPE signal for preventing sudden death of program */
1442 #ifdef G_OS_UNIX
1443         signal(SIGPIPE, SIG_IGN);
1444 #endif
1445         if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
1446                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
1447         }
1448         if (cmd.online_mode == ONLINE_MODE_ONLINE) {
1449                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
1450         }
1451
1452         if (cmd.status_folders) {
1453                 g_ptr_array_free(cmd.status_folders, TRUE);
1454                 cmd.status_folders = NULL;
1455         }
1456         if (cmd.status_full_folders) {
1457                 g_ptr_array_free(cmd.status_full_folders, TRUE);
1458                 cmd.status_full_folders = NULL;
1459         }
1460
1461         claws_register_idle_function(claws_gtk_idle);
1462
1463         avatars_init();
1464         prefs_toolbar_init();
1465
1466         num_folder_class = g_list_length(folder_get_list());
1467
1468         plugin_load_all("GTK2");
1469
1470         if (g_list_length(folder_get_list()) != num_folder_class) {
1471                 debug_print("new folders loaded, reloading processing rules\n");
1472                 prefs_matcher_read_config();
1473         }
1474         
1475         if ((plug_list = plugin_get_unloaded_list()) != NULL) {
1476                 GSList *cur;
1477                 gchar *list = NULL;
1478                 gint num_plugins = 0;
1479                 for (cur = plug_list; cur; cur = cur->next) {
1480                         Plugin *plugin = (Plugin *)cur->data;
1481                         gchar *tmp = g_strdup_printf("%s\n%s",
1482                                 list? list:"",
1483                                 plugin_get_name(plugin));
1484                         g_free(list);
1485                         list = tmp;
1486                         num_plugins++;
1487                 }
1488                 main_window_cursor_normal(mainwin);
1489                 main_window_popup(mainwin);
1490                 mainwin_shown = TRUE;
1491                 alertpanel_warning(ngettext(
1492                                      "The following plugin failed to load. "
1493                                      "Check the Plugins configuration "
1494                                      "for more information:\n%s",
1495                                      "The following plugins failed to load. "
1496                                      "Check the Plugins configuration "
1497                                      "for more information:\n%s", 
1498                                      num_plugins), 
1499                                      list);
1500                 main_window_cursor_wait(mainwin);
1501                 g_free(list);
1502                 g_slist_free(plug_list);
1503         }
1504
1505         if (never_ran) {
1506                 prefs_common_write_config();
1507                 plugin_load_standard_plugins ();
1508         }
1509
1510         /* if not crashed, show window now */
1511         if (!mainwin_shown) {
1512                 /* apart if something told not to show */
1513                 if (show_at_startup)
1514                         main_window_popup(mainwin);
1515         }
1516
1517         if (cmd.geometry != NULL) {
1518                 if (!gtk_window_parse_geometry(GTK_WINDOW(mainwin->window), cmd.geometry))
1519                         g_warning("failed to parse geometry '%s'", cmd.geometry);
1520                 else {
1521                         int width, height;
1522
1523                         if (sscanf(cmd.geometry, "%ux%u+", &width, &height) == 2)
1524                                 gtk_window_resize(GTK_WINDOW(mainwin->window), width, height);
1525                         else
1526                                 g_warning("failed to parse geometry's width/height");
1527                 }
1528         }
1529
1530         if (!folder_have_mailbox()) {
1531                 prefs_destroy_cache();
1532                 main_window_cursor_normal(mainwin);
1533                 if (folder_get_list() != NULL) {
1534                         alertpanel_error(_("Claws Mail has detected a configured "
1535                                    "mailbox, but it is incomplete. It is "
1536                                    "possibly due to a failing IMAP account. Use "
1537                                    "\"Rebuild folder tree\" on the mailbox parent "
1538                                    "folder's context menu to try to fix it."));
1539                 } else {
1540                         alertpanel_error(_("Claws Mail has detected a configured "
1541                                    "mailbox, but could not load it. It is "
1542                                    "probably provided by an out-of-date "
1543                                    "external plugin. Please reinstall the "
1544                                    "plugin and try again."));
1545                         exit_claws(mainwin);
1546 #ifdef G_OS_WIN32
1547                         win32_close_log();
1548 #endif
1549                         exit(1);
1550                 }
1551         }
1552         
1553         static_mainwindow = mainwin;
1554
1555 #ifdef HAVE_STARTUP_NOTIFICATION
1556         startup_notification_complete(FALSE);
1557 #endif
1558 #ifdef HAVE_LIBSM
1559         sc_session_manager_connect(mainwin);
1560 #endif
1561
1562         folder_item_update_thaw();
1563         folderview_thaw(mainwin->folderview);
1564         main_window_cursor_normal(mainwin);
1565
1566         if (!cmd.target && prefs_common.goto_last_folder_on_startup &&
1567             folder_find_item_from_identifier(prefs_common.last_opened_folder) != NULL &&
1568             !claws_crashed()) {
1569                 cmd.target = prefs_common.last_opened_folder;
1570         }
1571
1572         if (cmd.receive_all && !cmd.target) {
1573                 start_done = FALSE;
1574                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(FALSE));
1575         } else if (prefs_common.chk_on_startup && !cmd.target) {
1576                 start_done = FALSE;
1577                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(TRUE));
1578         } else if (cmd.receive && !cmd.target) {
1579                 start_done = FALSE;
1580                 g_timeout_add(1000, defer_check, NULL);
1581         }
1582         folderview_grab_focus(folderview);
1583
1584         if (cmd.compose) {
1585                 open_compose_new(cmd.compose_mailto, cmd.attach_files);
1586         }
1587         if (cmd.attach_files) {
1588                 list_free_strings(cmd.attach_files);
1589                 g_list_free(cmd.attach_files);
1590                 cmd.attach_files = NULL;
1591         }
1592         if (cmd.subscribe) {
1593                 folder_subscribe(cmd.subscribe_uri);
1594         }
1595
1596         if (cmd.send) {
1597                 send_queue();
1598         }
1599         
1600         if (cmd.target) {
1601                 start_done = FALSE;
1602                 g_timeout_add(500, defer_jump, (gpointer)cmd.target);
1603         }
1604
1605         prefs_destroy_cache();
1606         
1607         compose_reopen_exit_drafts();
1608
1609         if (start_done) {
1610                 sc_starting = FALSE;
1611                 main_window_set_menu_sensitive(mainwin);
1612                 toolbar_main_set_sensitive(mainwin);
1613         }
1614
1615         /* register the callback of unix domain socket input */
1616         lock_socket_tag = claws_input_add(lock_socket,
1617                                         G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_PRI,
1618                                         lock_socket_input_cb,
1619                                         mainwin, TRUE);
1620
1621         END_TIMING();
1622
1623         gtk_main();
1624
1625 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1626         if(nm_proxy)
1627                 g_object_unref(nm_proxy);
1628 #endif
1629 #ifdef HAVE_DBUS_GLIB
1630         uninstall_dbus_status_handler();
1631         if(connection)
1632                 dbus_g_connection_unref(connection);
1633 #endif
1634 #ifdef G_OS_WIN32
1635         win32_close_log();
1636 #endif
1637         utils_free_regex();
1638         exit_claws(mainwin);
1639
1640         return 0;
1641 }
1642
1643 static void save_all_caches(FolderItem *item, gpointer data)
1644 {
1645         if (!item->cache) {
1646                 return;
1647         }
1648
1649         if (item->opened) {
1650                 folder_item_close(item);
1651         }
1652
1653         folder_item_free_cache(item, TRUE);
1654 }
1655
1656 static void exit_claws(MainWindow *mainwin)
1657 {
1658         gchar *filename;
1659         gboolean have_connectivity;
1660         FolderItem *item;
1661
1662         sc_exiting = TRUE;
1663
1664         debug_print("shutting down\n");
1665         inc_autocheck_timer_remove();
1666
1667 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1668         if (prefs_common.work_offline && went_offline_nm)
1669                 prefs_common.work_offline = FALSE;
1670 #endif
1671
1672         /* save prefs for opened folder */
1673         if((item = folderview_get_opened_item(mainwin->folderview)) != NULL) {
1674                 summary_save_prefs_to_folderitem(
1675                         mainwin->summaryview, item);
1676                 prefs_common.last_opened_folder =
1677                         folder_item_get_identifier(item);
1678         }
1679
1680         /* save all state before exiting */
1681         folder_func_to_all_folders(save_all_caches, NULL);
1682         folder_write_list();
1683
1684         main_window_get_size(mainwin);
1685         main_window_get_position(mainwin);
1686
1687         prefs_common_write_config();
1688         account_write_config_all();
1689         passwd_store_write_config();
1690 #ifndef USE_ALT_ADDRBOOK
1691         addressbook_export_to_file();
1692 #endif
1693         filename = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
1694         gtk_accel_map_save(filename);
1695         g_free(filename);
1696
1697         /* delete temporary files */
1698         remove_all_files(get_tmp_dir());
1699         remove_all_files(get_mime_tmp_dir());
1700
1701         close_log_file(LOG_PROTOCOL);
1702         close_log_file(LOG_DEBUG_FILTERING);
1703
1704 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1705         have_connectivity = networkmanager_is_online(NULL); 
1706 #else
1707         have_connectivity = TRUE;
1708 #endif
1709 #ifdef HAVE_LIBETPAN
1710         imap_main_done(have_connectivity);
1711         nntp_main_done(have_connectivity);
1712 #endif
1713         /* delete crashfile */
1714         if (!cmd.crash)
1715                 claws_unlink(get_crashfile_name());
1716
1717         lock_socket_remove();
1718
1719 #ifdef HAVE_LIBSM
1720         if (mainwin->smc_conn)
1721                 SmcCloseConnection ((SmcConn)mainwin->smc_conn, 0, NULL);
1722         mainwin->smc_conn = NULL;
1723 #endif
1724
1725         main_window_destroy_all();
1726         
1727         plugin_unload_all("GTK2");
1728
1729         matcher_done();
1730         prefs_toolbar_done();
1731         avatars_done();
1732
1733 #ifndef USE_ALT_ADDRBOOK
1734         addressbook_destroy();
1735 #endif
1736         prefs_themes_done();
1737         prefs_fonts_done();
1738         prefs_ext_prog_done();
1739         prefs_wrapping_done();
1740         prefs_compose_writing_done();
1741         prefs_msg_colors_done();
1742         prefs_image_viewer_done();
1743         image_viewer_done();
1744         prefs_quote_done();
1745         prefs_summaries_done();
1746         prefs_message_done();
1747         prefs_other_done();
1748         prefs_receive_done();
1749         prefs_logging_done();
1750         prefs_send_done();
1751         tags_write_tags();
1752 #ifdef USE_ENCHANT       
1753         prefs_spelling_done();
1754         gtkaspell_checkers_quit();
1755 #endif
1756         plugin_unload_all("Common");
1757         claws_done();
1758 }
1759
1760 #define G_STRING_APPEND_ENCODED_URI(gstring,source)     \
1761         {                                               \
1762                 gchar tmpbuf[BUFFSIZE];                 \
1763                 encode_uri(tmpbuf, BUFFSIZE, (source)); \
1764                 g_string_append((gstring), tmpbuf);     \
1765         }
1766
1767 #define G_PRINT_EXIT(msg)       \
1768         {                       \
1769                 g_print(msg);   \
1770                 exit(1);        \
1771         }
1772
1773 static GString * parse_cmd_compose_from_file(const gchar *fn)
1774 {
1775         GString *headers = g_string_new(NULL);
1776         GString *body = g_string_new(NULL);
1777         gchar *to = NULL;
1778         gchar *h;
1779         gchar *v;
1780         gchar fb[BUFFSIZE];
1781         FILE *fp;
1782         gboolean isstdin;
1783
1784         if (fn == NULL || *fn == '\0')
1785                 G_PRINT_EXIT(_("Missing filename\n"));
1786         isstdin = (*fn == '-' && *(fn + 1) == '\0');
1787         if (isstdin)
1788                 fp = stdin;
1789         else {
1790                 fp = g_fopen(fn, "r");
1791                 if (!fp)
1792                         G_PRINT_EXIT(_("Cannot open filename for reading\n"));
1793         }
1794
1795         while (fgets(fb, sizeof(fb), fp)) {
1796                 gchar *tmp;     
1797                 strretchomp(fb);
1798                 if (*fb == '\0')
1799                         break;
1800                 h = fb;
1801                 while (*h && *h != ':') { ++h; } /* search colon */
1802                 if (*h == '\0')
1803                         G_PRINT_EXIT(_("Malformed header\n"));
1804                 v = h + 1;
1805                 while (*v && *v == ' ') { ++v; } /* trim value start */
1806                 *h = '\0';
1807                 tmp = g_ascii_strdown(fb, -1); /* get header name */
1808                 if (!strcmp(tmp, "to")) {
1809                         if (to != NULL)
1810                                 G_PRINT_EXIT(_("Duplicated 'To:' header\n"));
1811                         to = g_strdup(v);
1812                 } else {
1813                         g_string_append_c(headers, '&');
1814                         g_string_append(headers, tmp);
1815                         g_string_append_c(headers, '=');
1816                         g_string_append_uri_escaped(headers, v, NULL, TRUE);
1817                 }
1818                 g_free(tmp);
1819         }
1820         if (to == NULL)
1821                 G_PRINT_EXIT(_("Missing required 'To:' header\n"));
1822         g_string_append(body, to);
1823         g_free(to);
1824         g_string_append(body, "?body=");
1825         while (fgets(fb, sizeof(fb), fp)) {
1826                 g_string_append_uri_escaped(body, fb, NULL, TRUE);
1827         }
1828         if (!isstdin)
1829                 fclose(fp);
1830         /* append the remaining headers */
1831         g_string_append(body, headers->str);
1832         g_string_free(headers, TRUE);
1833
1834         return body;
1835 }
1836
1837 #undef G_STRING_APPEND_ENCODED_URI
1838 #undef G_PRINT_EXIT
1839
1840 static void parse_cmd_opt(int argc, char *argv[])
1841 {
1842         AttachInfo *ainfo;
1843         gint i;
1844
1845         for (i = 1; i < argc; i++) {
1846                 if (!strncmp(argv[i], "--receive-all", 13)) {
1847                         cmd.receive_all = TRUE;
1848                 } else if (!strncmp(argv[i], "--receive", 9)) {
1849                         cmd.receive = TRUE;
1850                 } else if (!strncmp(argv[i], "--cancel-receiving", 18)) {
1851                         cmd.cancel_receiving = TRUE;
1852                 } else if (!strncmp(argv[i], "--cancel-sending", 16)) {
1853                         cmd.cancel_sending = TRUE;
1854                 } else if (!strncmp(argv[i], "--compose-from-file", 19)) {
1855                         const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
1856
1857                         GString *mailto = parse_cmd_compose_from_file(p);
1858                         cmd.compose = TRUE;
1859                         cmd.compose_mailto = mailto->str;
1860                         i++;
1861                 } else if (!strncmp(argv[i], "--compose", 9)) {
1862                         const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
1863
1864                         cmd.compose = TRUE;
1865                         cmd.compose_mailto = NULL;
1866                         if (p && *p != '\0' && *p != '-') {
1867                                 if (!strncmp(p, "mailto:", 7)) {
1868                                         cmd.compose_mailto = p + 7;
1869                                 } else {
1870                                         cmd.compose_mailto = p;
1871                                 }
1872                                 i++;
1873                         }
1874                 } else if (!strncmp(argv[i], "--subscribe", 11)) {
1875                         const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
1876                         if (p && *p != '\0' && *p != '-') {
1877                                 cmd.subscribe = TRUE;
1878                                 cmd.subscribe_uri = p;
1879                         }
1880                 } else if (!strncmp(argv[i], "--attach", 8) || !strncmp(argv[i], "--insert", 8)) {
1881                         const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
1882                         gchar *file = NULL;
1883                         gboolean insert = !strncmp(argv[i], "--insert", 8);
1884
1885                         while (p && *p != '\0' && *p != '-') {
1886                                 if ((file = g_filename_from_uri(p, NULL, NULL)) != NULL) {
1887                                         if (!is_file_exist(file)) {
1888                                                 g_free(file);
1889                                                 file = NULL;
1890                                         }
1891                                 }
1892                                 if (file == NULL && *p != G_DIR_SEPARATOR) {
1893                                         file = g_strconcat(claws_get_startup_dir(),
1894                                                            G_DIR_SEPARATOR_S,
1895                                                            p, NULL);
1896                                 } else if (file == NULL) {
1897                                         file = g_strdup(p);
1898                                 }
1899
1900                                 ainfo = g_new0(AttachInfo, 1);
1901                                 ainfo->file = file;
1902                                 ainfo->insert = insert;
1903                                 cmd.attach_files = g_list_append(cmd.attach_files, ainfo);
1904                                 i++;
1905                                 p = (i+1 < argc)?argv[i+1]:NULL;
1906                         }
1907                 } else if (!strncmp(argv[i], "--send", 6)) {
1908                         cmd.send = TRUE;
1909                 } else if (!strncmp(argv[i], "--version-full", 14) ||
1910                            !strncmp(argv[i], "-V", 2)) {
1911                         g_print("Claws Mail version " VERSION_GIT_FULL "\n");
1912                         main_dump_features_list(FALSE);
1913                         exit(0);
1914                 } else if (!strncmp(argv[i], "--version", 9) ||
1915                            !strncmp(argv[i], "-v", 2)) {
1916                         g_print("Claws Mail version " VERSION "\n");
1917                         exit(0);
1918                 } else if (!strncmp(argv[i], "--status-full", 13)) {
1919                         const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
1920  
1921                         cmd.status_full = TRUE;
1922                         while (p && *p != '\0' && *p != '-') {
1923                                 if (!cmd.status_full_folders) {
1924                                         cmd.status_full_folders =
1925                                                 g_ptr_array_new();
1926                                 }
1927                                 g_ptr_array_add(cmd.status_full_folders,
1928                                                 g_strdup(p));
1929                                 i++;
1930                                 p = (i+1 < argc)?argv[i+1]:NULL;
1931                         }
1932                 } else if (!strncmp(argv[i], "--status", 8)) {
1933                         const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
1934  
1935                         cmd.status = TRUE;
1936                         while (p && *p != '\0' && *p != '-') {
1937                                 if (!cmd.status_folders)
1938                                         cmd.status_folders = g_ptr_array_new();
1939                                 g_ptr_array_add(cmd.status_folders,
1940                                                 g_strdup(p));
1941                                 i++;
1942                                 p = (i+1 < argc)?argv[i+1]:NULL;
1943                         }
1944                 } else if (!strncmp(argv[i], "--search", 8)) {
1945                         cmd.search_folder    = (i+1 < argc)?argv[i+1]:NULL;
1946                         cmd.search_type      = (i+2 < argc)?argv[i+2]:NULL;
1947                         cmd.search_request   = (i+3 < argc)?argv[i+3]:NULL;
1948                         const char* rec      = (i+4 < argc)?argv[i+4]:NULL;
1949                         cmd.search_recursive = TRUE;
1950                         if (rec && (tolower(*rec)=='n' || tolower(*rec)=='f' || *rec=='0'))
1951                                 cmd.search_recursive = FALSE;
1952                         if (cmd.search_folder && cmd.search_type && cmd.search_request)
1953                                 cmd.search = TRUE;
1954                 } else if (!strncmp(argv[i], "--online", 8)) {
1955                         cmd.online_mode = ONLINE_MODE_ONLINE;
1956                 } else if (!strncmp(argv[i], "--offline", 9)) {
1957                         cmd.online_mode = ONLINE_MODE_OFFLINE;
1958                 } else if (!strncmp(argv[i], "--toggle-debug", 14)) {
1959                         cmd.debug = TRUE;
1960                 } else if (!strncmp(argv[i], "--statistics", 12)) {
1961                         cmd.statistics = TRUE;
1962                 } else if (!strncmp(argv[i], "--reset-statistics", 18)) {
1963                         cmd.reset_statistics = TRUE;
1964                 } else if (!strncmp(argv[i], "--help", 6) ||
1965                            !strncmp(argv[i], "-h", 2)) {
1966                         gchar *base = g_path_get_basename(argv[0]);
1967                         g_print(_("Usage: %s [OPTION]...\n"), base);
1968
1969                         g_print("%s\n", _("  --compose [address]    open composition window"));
1970                         g_print("%s\n", _("  --compose-from-file file\n"
1971                                           "                         open composition window with data from given file;\n"
1972                                           "                         use - as file name for reading from standard input;\n"
1973                                           "                         content format: headers first (To: required) until an\n"
1974                                           "                         empty line, then mail body until end of file."));
1975                         g_print("%s\n", _("  --subscribe [uri]      subscribe to the given URI if possible"));
1976                         g_print("%s\n", _("  --attach file1 [file2]...\n"
1977                                           "                         open composition window with specified files\n"
1978                                           "                         attached"));
1979                         g_print("%s\n", _("  --insert file1 [file2]...\n"
1980                                           "                         open composition window with specified files\n"
1981                                           "                         inserted"));
1982                         g_print("%s\n", _("  --receive              receive new messages"));
1983                         g_print("%s\n", _("  --receive-all          receive new messages of all accounts"));
1984                         g_print("%s\n", _("  --cancel-receiving     cancel receiving of messages"));
1985                         g_print("%s\n", _("  --cancel-sending       cancel sending of messages"));
1986                         g_print("%s\n", _("  --search folder type request [recursive]\n"
1987                                           "                         searches mail\n"
1988                                           "                         folder ex.: \"#mh/Mailbox/inbox\" or \"Mail\"\n"
1989                                           "                         type: s[ubject],f[rom],t[o],e[xtended],m[ixed] or g: tag\n"
1990                                           "                         request: search string\n"
1991                                           "                         recursive: false if arg. starts with 0, n, N, f or F"));
1992
1993                         g_print("%s\n", _("  --send                 send all queued messages"));
1994                         g_print("%s\n", _("  --status [folder]...   show the total number of messages"));
1995                         g_print("%s\n", _("  --status-full [folder]...\n"
1996                                           "                         show the status of each folder"));
1997                         g_print("%s\n", _("  --statistics           show session statistics"));
1998                         g_print("%s\n", _("  --reset-statistics     reset session statistics"));
1999                         g_print("%s\n", _("  --select folder[/msg]  jumps to the specified folder/message\n" 
2000                                           "                         folder is a folder id like 'folder/sub_folder'"));
2001                         g_print("%s\n", _("  --online               switch to online mode"));
2002                         g_print("%s\n", _("  --offline              switch to offline mode"));
2003                         g_print("%s\n", _("  --exit --quit -q       exit Claws Mail"));
2004                         g_print("%s\n", _("  --debug                debug mode"));
2005                         g_print("%s\n", _("  --toggle-debug         toggle debug mode"));
2006                         g_print("%s\n", _("  --help -h              display this help and exit"));
2007                         g_print("%s\n", _("  --version -v           output version information and exit"));
2008                         g_print("%s\n", _("  --version-full -V      output version and built-in features information and exit"));
2009                         g_print("%s\n", _("  --config-dir           output configuration directory"));
2010                         g_print("%s\n", _("  --alternate-config-dir [dir]\n"
2011                                           "                         use specified configuration directory"));
2012                         g_print("%s\n", _("  --geometry -geometry WxH+X+Y\n"
2013                                           "                         set geometry for main window"));
2014
2015                         g_free(base);
2016                         exit(1);
2017                 } else if (!strncmp(argv[i], "--crash", 7)) {
2018                         cmd.crash = TRUE;
2019                         cmd.crash_params = g_strdup((i+1 < argc)?argv[i+1]:NULL);
2020                         i++;
2021                 } else if (!strncmp(argv[i], "--config-dir", sizeof "--config-dir" - 1)) {
2022                         g_print(RC_DIR "\n");
2023                         exit(0);
2024                 } else if (!strncmp(argv[i], "--alternate-config-dir", sizeof "--alternate-config-dir" - 1) && i+1 < argc) {
2025                         set_rc_dir(argv[i+1]);
2026                 } else if (!strncmp(argv[i], "--geometry", sizeof "--geometry" - 1)
2027                           || !strncmp(argv[i], "-geometry", sizeof "-geometry" - 1)) {
2028                         cmd.geometry = (i+1 < argc)? argv[i+1]: NULL;
2029                 } else if (!strncmp(argv[i], "--exit", 6) ||
2030                            !strncmp(argv[i], "--quit", 6) ||
2031                            !strncmp(argv[i], "-q", 2)) {
2032                         cmd.exit = TRUE;
2033                 } else if (!strncmp(argv[i], "--select", 8) && i+1 < argc) {
2034                         cmd.target = argv[i+1];
2035                 } else if (i == 1 && argc == 2) {
2036                         /* only one parameter. Do something intelligent about it */
2037                         if ((strstr(argv[i], "@")||!strncmp(argv[i], "mailto:", 7)) && !strstr(argv[i], "://")) {
2038                                 const gchar *p = argv[i];
2039
2040                                 cmd.compose = TRUE;
2041                                 cmd.compose_mailto = NULL;
2042                                 if (p && *p != '\0' && *p != '-') {
2043                                         if (!strncmp(p, "mailto:", 7)) {
2044                                                 cmd.compose_mailto = p + 7;
2045                                         } else {
2046                                                 cmd.compose_mailto = p;
2047                                         }
2048                                 }
2049                         } else if (!strncmp(argv[i], "file://", 7)) {
2050                                 cmd.target = argv[i];
2051                         } else if (!strncmp(argv[i], "?attach=file://", strlen("?attach=file://"))) {
2052                                 cmd.compose = TRUE;
2053                                 cmd.compose_mailto = argv[i];
2054                         } else if (strstr(argv[i], "://")) {
2055                                 const gchar *p = argv[i];
2056                                 if (p && *p != '\0' && *p != '-') {
2057                                         cmd.subscribe = TRUE;
2058                                         cmd.subscribe_uri = p;
2059                                 }
2060                         } else if (!strcmp(argv[i], "--sync")) {
2061                                 /* gtk debug */
2062                         } else if (is_dir_exist(argv[i]) || is_file_exist(argv[i])) {
2063                                 cmd.target = argv[i];
2064                         } else {
2065                                 g_print(_("Unknown option\n"));
2066                                 exit(1);
2067                         }
2068                 }
2069         }
2070
2071         if (cmd.attach_files && cmd.compose == FALSE) {
2072                 cmd.compose = TRUE;
2073                 cmd.compose_mailto = NULL;
2074         }
2075 }
2076
2077 static void initial_processing(FolderItem *item, gpointer data)
2078 {
2079         MainWindow *mainwin = (MainWindow *)data;
2080         gchar *buf;
2081
2082         cm_return_if_fail(item);
2083         buf = g_strdup_printf(_("Processing (%s)..."), 
2084                               item->path 
2085                               ? item->path 
2086                               : _("top level folder"));
2087         g_free(buf);
2088
2089         
2090         if (item->prefs->enable_processing) {
2091                 item->processing_pending = TRUE;
2092                 folder_item_apply_processing(item);
2093                 item->processing_pending = FALSE;
2094         }
2095
2096         STATUSBAR_POP(mainwin);
2097 }
2098
2099 static gboolean draft_all_messages(void)
2100 {
2101         const GList *compose_list = NULL;
2102         
2103         compose_clear_exit_drafts();
2104         compose_list = compose_get_compose_list();
2105         while (compose_list != NULL) {
2106                 Compose *c = (Compose*)compose_list->data;
2107                 if (!compose_draft(c, COMPOSE_DRAFT_FOR_EXIT))
2108                         return FALSE;
2109                 compose_list = compose_get_compose_list();
2110         }
2111         return TRUE;
2112 }
2113 gboolean clean_quit(gpointer data)
2114 {
2115         static gboolean firstrun = TRUE;
2116
2117         if (!firstrun) {
2118                 return FALSE;
2119         }
2120         firstrun = FALSE;
2121
2122         /*!< Good idea to have the main window stored in a 
2123          *   static variable so we can check that variable
2124          *   to see if we're really allowed to do things
2125          *   that actually the spawner is supposed to 
2126          *   do (like: sending mail, composing messages).
2127          *   Because, really, if we're the spawnee, and
2128          *   we touch GTK stuff, we're hosed. See the 
2129          *   next fixme. */
2130
2131         /* FIXME: Use something else to signal that we're
2132          * in the original spawner, and not in a spawned
2133          * child. */
2134         if (!static_mainwindow) {
2135                 return FALSE;
2136         }
2137                 
2138         draft_all_messages();
2139         emergency_exit = TRUE;
2140         exit_claws(static_mainwindow);
2141         exit(0);
2142
2143         return FALSE;
2144 }
2145
2146 void app_will_exit(GtkWidget *widget, gpointer data)
2147 {
2148         MainWindow *mainwin = data;
2149         
2150         if (gtk_main_level() == 0) {
2151                 debug_print("not even started\n");
2152                 return;
2153         }
2154         if (sc_exiting == TRUE) {
2155                 debug_print("exit pending\n");
2156                 return;
2157         }
2158         sc_exiting = TRUE;
2159         debug_print("exiting\n");
2160         if (compose_get_compose_list()) {
2161                 if (!draft_all_messages()) {
2162                         main_window_popup(mainwin);
2163                         sc_exiting = FALSE;
2164                         return;
2165                 }
2166         }
2167
2168         if (prefs_common.warn_queued_on_exit && procmsg_have_queued_mails_fast()) {
2169                 if (alertpanel(_("Queued messages"),
2170                                _("Some unsent messages are queued. Exit now?"),
2171                                GTK_STOCK_CANCEL, GTK_STOCK_OK, NULL)
2172                     != G_ALERTALTERNATE) {
2173                         main_window_popup(mainwin);
2174                         sc_exiting = FALSE;
2175                         return;
2176                 }
2177                 manage_window_focus_in(mainwin->window, NULL, NULL);
2178         }
2179
2180         sock_cleanup();
2181 #ifdef HAVE_VALGRIND
2182         if (RUNNING_ON_VALGRIND) {
2183                 summary_clear_list(mainwin->summaryview);
2184         }
2185 #endif
2186         if (folderview_get_selected_item(mainwin->folderview))
2187                 folder_item_close(folderview_get_selected_item(mainwin->folderview));
2188         gtk_main_quit();
2189 }
2190
2191 gboolean claws_is_exiting(void)
2192 {
2193         return sc_exiting;
2194 }
2195
2196 gboolean claws_is_starting(void)
2197 {
2198         return sc_starting;
2199 }
2200
2201 #ifdef G_OS_UNIX
2202 /*
2203  * CLAWS: want this public so crash dialog can delete the
2204  * lock file too
2205  */
2206 gchar *claws_get_socket_name(void)
2207 {
2208         static gchar *filename = NULL;
2209         gchar *socket_dir = NULL;
2210         gchar md5sum[33];
2211
2212         if (filename == NULL) {
2213                 GStatBuf st;
2214                 gint stat_ok;
2215
2216                 socket_dir = g_strdup_printf("%s%cclaws-mail-%d",
2217                                            g_get_tmp_dir(), G_DIR_SEPARATOR,
2218 #if HAVE_GETUID
2219                                            getuid());
2220 #else
2221                                            0);
2222 #endif
2223                 stat_ok = g_stat(socket_dir, &st);
2224                 if (stat_ok < 0 && errno != ENOENT) {
2225                         g_print("Error stat'ing socket_dir %s: %s\n",
2226                                 socket_dir, g_strerror(errno));
2227                 } else if (stat_ok == 0 && S_ISSOCK(st.st_mode)) {
2228                         /* old versions used a sock in $TMPDIR/claws-mail-$UID */
2229                         debug_print("Using legacy socket %s\n", socket_dir);
2230                         filename = g_strdup(socket_dir);
2231                         return filename;
2232                 }
2233
2234                 if (!is_dir_exist(socket_dir) && make_dir(socket_dir) < 0) {
2235                         g_print("Error creating socket_dir %s: %s\n",
2236                                 socket_dir, g_strerror(errno));
2237                 }
2238
2239                 md5_hex_digest(md5sum, get_rc_dir());
2240
2241                 filename = g_strdup_printf("%s%c%s", socket_dir, G_DIR_SEPARATOR,
2242                                            md5sum);
2243                 g_free(socket_dir);
2244                 debug_print("Using control socket %s\n", filename);
2245         }
2246
2247         return filename;
2248 }
2249 #endif
2250
2251 static gchar *get_crashfile_name(void)
2252 {
2253         static gchar *filename = NULL;
2254
2255         if (filename == NULL) {
2256                 filename = g_strdup_printf("%s%cclaws-crashed",
2257                                            get_tmp_dir(), G_DIR_SEPARATOR);
2258         }
2259
2260         return filename;
2261 }
2262
2263 static gint prohibit_duplicate_launch(void)
2264 {
2265         gint uxsock;
2266         GList *curr;
2267 #ifdef G_OS_UNIX
2268         gchar *path;
2269
2270         path = claws_get_socket_name();
2271         /* Try to connect to the control socket */
2272         uxsock = fd_connect_unix(path);
2273         
2274         if (x_display == NULL)
2275                 x_display = g_strdup(g_getenv("DISPLAY"));
2276
2277         if (uxsock < 0) {
2278                 gint ret;
2279 #if HAVE_FLOCK
2280                 gchar *socket_lock;
2281                 gint lock_fd;
2282                 /* If connect failed, no other process is running.
2283                  * Unlink the potentially existing socket, then
2284                  * open it. This has to be done locking a temporary
2285                  * file to avoid the race condition where another
2286                  * process could have created the socket just in
2287                  * between.
2288                  */
2289                 socket_lock = g_strconcat(path, ".lock",
2290                                           NULL);
2291                 lock_fd = g_open(socket_lock, O_RDWR|O_CREAT, 0);
2292                 if (lock_fd < 0) {
2293                         debug_print("Couldn't open %s: %s (%d)\n", socket_lock,
2294                                 g_strerror(errno), errno);
2295                         g_free(socket_lock);
2296                         return -1;
2297                 }
2298                 if (flock(lock_fd, LOCK_EX) < 0) {
2299                         debug_print("Couldn't lock %s: %s (%d)\n", socket_lock,
2300                                 g_strerror(errno), errno);
2301                         close(lock_fd);
2302                         g_free(socket_lock);
2303                         return -1;
2304                 }
2305 #endif
2306
2307                 claws_unlink(path);
2308                 debug_print("Opening socket %s\n", path);
2309                 ret = fd_open_unix(path);
2310 #if HAVE_FLOCK
2311                 flock(lock_fd, LOCK_UN);
2312                 close(lock_fd);
2313                 claws_unlink(socket_lock);
2314                 g_free(socket_lock);
2315 #endif
2316                 return ret;
2317         }
2318 #else
2319         HANDLE hmutex;
2320
2321         hmutex = CreateMutexA(NULL, FALSE, "ClawsMail");
2322         if (!hmutex) {
2323                 debug_print("cannot create Mutex\n");
2324                 return -1;
2325         }
2326         if (GetLastError() != ERROR_ALREADY_EXISTS) {
2327                 uxsock = fd_open_inet(50216);
2328                 if (uxsock < 0)
2329                         return 0;
2330                 return uxsock;
2331         }
2332
2333         uxsock = fd_connect_inet(50216);
2334         if (uxsock < 0)
2335                 return -1;
2336 #endif
2337         /* remote command mode */
2338
2339         debug_print("another Claws Mail instance is already running.\n");
2340
2341         if (cmd.receive_all) {
2342                 fd_write_all(uxsock, "receive_all\n", 12);
2343         } else if (cmd.receive) {
2344                 fd_write_all(uxsock, "receive\n", 8);
2345         } else if (cmd.cancel_receiving) {
2346                 fd_write_all(uxsock, "cancel_receiving\n", 17);
2347         } else if (cmd.cancel_sending) {
2348                 fd_write_all(uxsock, "cancel_sending\n", 15);
2349         } else if (cmd.compose && cmd.attach_files) {
2350                 gchar *str, *compose_str;
2351
2352                 if (cmd.compose_mailto) {
2353                         compose_str = g_strdup_printf("compose_attach %s\n",
2354                                                       cmd.compose_mailto);
2355                 } else {
2356                         compose_str = g_strdup("compose_attach\n");
2357                 }
2358
2359                 fd_write_all(uxsock, compose_str, strlen(compose_str));
2360                 g_free(compose_str);
2361
2362                 for (curr = cmd.attach_files; curr != NULL ; curr = curr->next) {
2363                         str = (gchar *) ((AttachInfo *)curr->data)->file;
2364                         if (((AttachInfo *)curr->data)->insert)
2365                                 fd_write_all(uxsock, "insert ", strlen("insert "));
2366                         else
2367                                 fd_write_all(uxsock, "attach ", strlen("attach "));
2368                         fd_write_all(uxsock, str, strlen(str));
2369                         fd_write_all(uxsock, "\n", 1);
2370                 }
2371
2372                 fd_write_all(uxsock, ".\n", 2);
2373         } else if (cmd.compose) {
2374                 gchar *compose_str;
2375
2376                 if (cmd.compose_mailto) {
2377                         compose_str = g_strdup_printf
2378                                 ("compose %s\n", cmd.compose_mailto);
2379                 } else {
2380                         compose_str = g_strdup("compose\n");
2381                 }
2382
2383                 fd_write_all(uxsock, compose_str, strlen(compose_str));
2384                 g_free(compose_str);
2385         } else if (cmd.subscribe) {
2386                 gchar *str = g_strdup_printf("subscribe %s\n", cmd.subscribe_uri);
2387                 fd_write_all(uxsock, str, strlen(str));
2388                 g_free(str);
2389         } else if (cmd.send) {
2390                 fd_write_all(uxsock, "send\n", 5);
2391         } else if (cmd.online_mode == ONLINE_MODE_ONLINE) {
2392                 fd_write(uxsock, "online\n", 6);
2393         } else if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
2394                 fd_write(uxsock, "offline\n", 7);
2395         } else if (cmd.debug) {
2396                 fd_write(uxsock, "debug\n", 7);
2397         } else if (cmd.status || cmd.status_full) {
2398                 gchar buf[BUFFSIZE];
2399                 gint i;
2400                 const gchar *command;
2401                 GPtrArray *folders;
2402                 gchar *folder;
2403  
2404                 command = cmd.status_full ? "status-full\n" : "status\n";
2405                 folders = cmd.status_full ? cmd.status_full_folders :
2406                         cmd.status_folders;
2407  
2408                 fd_write_all(uxsock, command, strlen(command));
2409                 for (i = 0; folders && i < folders->len; ++i) {
2410                         folder = g_ptr_array_index(folders, i);
2411                         fd_write_all(uxsock, folder, strlen(folder));
2412                         fd_write_all(uxsock, "\n", 1);
2413                 }
2414                 fd_write_all(uxsock, ".\n", 2);
2415                 for (;;) {
2416                         fd_gets(uxsock, buf, sizeof(buf) - 1);
2417                         buf[sizeof(buf) - 1] = '\0';
2418                         if (!strncmp(buf, ".\n", 2)) break;
2419                         fputs(buf, stdout);
2420                 }
2421         } else if (cmd.exit) {
2422                 fd_write_all(uxsock, "exit\n", 5);
2423         } else if (cmd.statistics) {
2424                 gchar buf[BUFSIZ];
2425                 fd_write(uxsock, "statistics\n", 11);
2426                 for (;;) {
2427                         fd_gets(uxsock, buf, sizeof(buf) - 1);
2428                         buf[sizeof(buf) - 1] = '\0';
2429                         if (!strncmp(buf, ".\n", 2)) break;
2430                         fputs(buf, stdout);
2431                 }
2432         } else if (cmd.reset_statistics) {
2433                 fd_write(uxsock, "reset_statistics\n", 17);
2434         } else if (cmd.target) {
2435                 gchar *str = g_strdup_printf("select %s\n", cmd.target);
2436                 fd_write_all(uxsock, str, strlen(str));
2437                 g_free(str);
2438         } else if (cmd.search) {
2439                 gchar buf[BUFFSIZE];
2440                 gchar *str =
2441                         g_strdup_printf("search %s\n%s\n%s\n%c\n",
2442                                                         cmd.search_folder, cmd.search_type, cmd.search_request,
2443                                                         (cmd.search_recursive==TRUE)?'1':'0');
2444                 fd_write_all(uxsock, str, strlen(str));
2445                 g_free(str);
2446                 for (;;) {
2447                         fd_gets(uxsock, buf, sizeof(buf) - 1);
2448                         buf[sizeof(buf) - 1] = '\0';
2449                         if (!strncmp(buf, ".\n", 2)) break;
2450                         fputs(buf, stdout);
2451                 }
2452         } else {
2453 #ifndef G_OS_WIN32
2454                 gchar buf[BUFSIZ];
2455                 fd_write_all(uxsock, "get_display\n", 12);
2456                 memset(buf, 0, sizeof(buf));
2457                 fd_gets(uxsock, buf, sizeof(buf) - 1);
2458                 buf[sizeof(buf) - 1] = '\0';
2459                 if (strcmp2(buf, x_display)) {
2460                         g_print("Claws Mail is already running on display %s.\n",
2461                                 buf);
2462                 } else {
2463                         fd_close(uxsock);
2464                         uxsock = fd_connect_unix(path);
2465                         fd_write_all(uxsock, "popup\n", 6);
2466                 }
2467 #else
2468                 fd_write_all(uxsock, "popup\n", 6);
2469 #endif
2470         }
2471
2472         fd_close(uxsock);
2473         return -1;
2474 }
2475
2476 static gint lock_socket_remove(void)
2477 {
2478 #ifdef G_OS_UNIX
2479         gchar *filename, *dirname;
2480 #endif
2481         if (lock_socket < 0) {
2482                 return -1;
2483         }
2484
2485         if (lock_socket_tag > 0) {
2486                 g_source_remove(lock_socket_tag);
2487         }
2488         fd_close(lock_socket);
2489
2490 #ifdef G_OS_UNIX
2491         filename = claws_get_socket_name();
2492         dirname = g_path_get_dirname(filename);
2493         claws_unlink(filename);
2494         g_rmdir(dirname);
2495         g_free(dirname);
2496 #endif
2497
2498         return 0;
2499 }
2500
2501 static GPtrArray *get_folder_item_list(gint sock)
2502 {
2503         gchar buf[BUFFSIZE];
2504         FolderItem *item;
2505         GPtrArray *folders = NULL;
2506
2507         for (;;) {
2508                 fd_gets(sock, buf, sizeof(buf) - 1);
2509                 buf[sizeof(buf) - 1] = '\0';
2510                 if (!strncmp(buf, ".\n", 2)) {
2511                         break;
2512                 }
2513                 strretchomp(buf);
2514                 if (!folders) {
2515                         folders = g_ptr_array_new();
2516                 }
2517                 item = folder_find_item_from_identifier(buf);
2518                 if (item) {
2519                         g_ptr_array_add(folders, item);
2520                 } else {
2521                         g_warning("no such folder: %s", buf);
2522                 }
2523         }
2524
2525         return folders;
2526 }
2527
2528 static void lock_socket_input_cb(gpointer data,
2529                                  gint source,
2530                                  GIOCondition condition)
2531 {
2532         MainWindow *mainwin = (MainWindow *)data;
2533         gint sock;
2534         gchar buf[BUFFSIZE];
2535
2536         sock = fd_accept(source);
2537         if (sock < 0)
2538                 return;
2539
2540         fd_gets(sock, buf, sizeof(buf) - 1);
2541         buf[sizeof(buf) - 1] = '\0';
2542
2543         if (!strncmp(buf, "popup", 5)) {
2544                 main_window_popup(mainwin);
2545         } else if (!strncmp(buf, "get_display", 11)) {
2546                 fd_write_all(sock, x_display, strlen(x_display));
2547         } else if (!strncmp(buf, "receive_all", 11)) {
2548                 inc_all_account_mail(mainwin, FALSE,
2549                                      prefs_common.newmail_notify_manu);
2550         } else if (!strncmp(buf, "receive", 7)) {
2551                 inc_mail(mainwin, prefs_common.newmail_notify_manu);
2552         } else if (!strncmp(buf, "cancel_receiving", 16)) {
2553                 inc_cancel_all();
2554                 imap_cancel_all();
2555         } else if (!strncmp(buf, "cancel_sending", 14)) {
2556                 send_cancel();
2557         } else if (!strncmp(buf, "compose_attach", 14)) {
2558                 GList *files = NULL, *curr;
2559                 AttachInfo *ainfo;
2560                 gchar *mailto;
2561
2562                 mailto = g_strdup(buf + strlen("compose_attach") + 1);
2563                 while (fd_gets(sock, buf, sizeof(buf) - 1) > 0) {
2564                         buf[sizeof(buf) - 1] = '\0';
2565                         strretchomp(buf);
2566                         if (!strcmp2(buf, "."))
2567                                 break;
2568
2569                         ainfo = g_new0(AttachInfo, 1);
2570                         ainfo->file = g_strdup(strstr(buf, " ") + 1);
2571                         ainfo->insert = !strncmp(buf, "insert ", 7);
2572                         files = g_list_append(files, ainfo);
2573                 }
2574                 open_compose_new(mailto, files);
2575                 
2576                 curr = g_list_first(files);
2577                 while (curr != NULL) {
2578                         ainfo = (AttachInfo *)curr->data;
2579                         g_free(ainfo->file);
2580                         g_free(ainfo);
2581                         curr = curr->next;
2582                 }
2583                 g_list_free(files);
2584                 g_free(mailto);
2585         } else if (!strncmp(buf, "compose", 7)) {
2586                 open_compose_new(buf + strlen("compose") + 1, NULL);
2587         } else if (!strncmp(buf, "subscribe", 9)) {
2588                 main_window_popup(mainwin);
2589                 folder_subscribe(buf + strlen("subscribe") + 1);
2590         } else if (!strncmp(buf, "send", 4)) {
2591                 send_queue();
2592         } else if (!strncmp(buf, "online", 6)) {
2593                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
2594         } else if (!strncmp(buf, "offline", 7)) {
2595                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
2596         } else if (!strncmp(buf, "debug", 5)) {
2597                 debug_set_mode(debug_get_mode() ? FALSE : TRUE);
2598         } else if (!strncmp(buf, "status-full", 11) ||
2599                    !strncmp(buf, "status", 6)) {
2600                 gchar *status;
2601                 GPtrArray *folders;
2602  
2603                 folders = get_folder_item_list(sock);
2604                 status = folder_get_status
2605                         (folders, !strncmp(buf, "status-full", 11));
2606                 fd_write_all(sock, status, strlen(status));
2607                 fd_write_all(sock, ".\n", 2);
2608                 g_free(status);
2609                 if (folders) g_ptr_array_free(folders, TRUE);
2610         } else if (!strncmp(buf, "statistics", 10)) {
2611                 gchar tmp[BUFSIZ];
2612
2613                 g_snprintf(tmp, sizeof(tmp), _("Session statistics\n"));
2614                 fd_write_all(sock, tmp, strlen(tmp));
2615
2616                 if (prefs_common.date_format) {
2617                         struct tm *lt;
2618                         gint len = 100;
2619                         gchar date[len];
2620
2621                         lt = localtime(&session_stats.time_started);
2622                         fast_strftime(date, len, prefs_common.date_format, lt);
2623                         g_snprintf(tmp, sizeof(tmp), _("Started: %s\n"),
2624                                         lt ? date : ctime(&session_stats.time_started));
2625                 } else
2626                         g_snprintf(tmp, sizeof(tmp), _("Started: %s\n"),
2627                                         ctime(&session_stats.time_started));
2628                 fd_write_all(sock, tmp, strlen(tmp));
2629
2630                 fd_write_all(sock, "\n", 1);
2631
2632                 g_snprintf(tmp, sizeof(tmp), _("Incoming traffic\n"));
2633                 fd_write_all(sock, tmp, strlen(tmp));
2634
2635                 g_snprintf(tmp, sizeof(tmp), _("Received messages: %d\n"),
2636                                 session_stats.received);
2637                 fd_write_all(sock, tmp, strlen(tmp));
2638
2639                 fd_write_all(sock, "\n", 1);
2640
2641                 g_snprintf(tmp, sizeof(tmp), _("Outgoing traffic\n"));
2642                 fd_write_all(sock, tmp, strlen(tmp));
2643
2644                 g_snprintf(tmp, sizeof(tmp), _("New/redirected messages: %d\n"),
2645                                 session_stats.sent);
2646                 fd_write_all(sock, tmp, strlen(tmp));
2647
2648                 g_snprintf(tmp, sizeof(tmp), _("Replied messages: %d\n"),
2649                                 session_stats.replied);
2650                 fd_write_all(sock, tmp, strlen(tmp));
2651
2652                 g_snprintf(tmp, sizeof(tmp), _("Forwarded messages: %d\n"),
2653                                 session_stats.forwarded);
2654                 fd_write_all(sock, tmp, strlen(tmp));
2655
2656                 g_snprintf(tmp, sizeof(tmp), _("Total outgoing messages: %d\n"),
2657                                 (session_stats.sent + session_stats.replied +
2658                                  session_stats.forwarded));
2659                 fd_write_all(sock, tmp, strlen(tmp));
2660
2661                 fd_write_all(sock, ".\n", 2);
2662         } else if (!strncmp(buf, "reset_statistics", 16)) {
2663                 reset_statistics();
2664         } else if (!strncmp(buf, "select ", 7)) {
2665                 const gchar *target = buf+7;
2666                 mainwindow_jump_to(target, TRUE);
2667         } else if (!strncmp(buf, "search ", 7)) {
2668                 FolderItem* folderItem = NULL;
2669                 GSList *messages = NULL;
2670                 gchar *folder_name = NULL;
2671                 gchar *request = NULL;
2672                 AdvancedSearch *search;
2673                 gboolean recursive;
2674                 AdvancedSearchType searchType = ADVANCED_SEARCH_EXTENDED;
2675                 
2676                 search = advsearch_new();
2677
2678                 folder_name = g_strdup(buf+7);
2679                 strretchomp(folder_name);
2680
2681                 if (fd_gets(sock, buf, sizeof(buf) - 1) <= 0) 
2682                         goto search_exit;
2683                 buf[sizeof(buf) - 1] = '\0';
2684
2685                 switch (toupper(buf[0])) {
2686                 case 'S': searchType = ADVANCED_SEARCH_SUBJECT; break;
2687                 case 'F': searchType = ADVANCED_SEARCH_FROM; break;
2688                 case 'T': searchType = ADVANCED_SEARCH_TO; break;
2689                 case 'M': searchType = ADVANCED_SEARCH_MIXED; break;
2690                 case 'G': searchType = ADVANCED_SEARCH_TAG; break;
2691                 case 'E': searchType = ADVANCED_SEARCH_EXTENDED; break;
2692                 }
2693
2694                 if (fd_gets(sock, buf, sizeof(buf) - 1) <= 0) 
2695                         goto search_exit;
2696
2697                 buf[sizeof(buf) - 1] = '\0';
2698                 request = g_strdup(buf);
2699                 strretchomp(request);
2700
2701                 recursive = TRUE;
2702                 if (fd_gets(sock, buf, sizeof(buf) - 1) > 0)
2703                         recursive = buf[0] != '0';
2704
2705                 buf[sizeof(buf) - 1] = '\0';
2706
2707                 debug_print("search: %s %i %s %i\n", folder_name, searchType, request, recursive);
2708
2709                 folderItem = folder_find_item_from_identifier(folder_name);
2710
2711                 if (folderItem == NULL) {
2712                         debug_print("Unknown folder item : '%s', searching folder\n",folder_name);
2713                         Folder* folder = folder_find_from_path(folder_name);
2714                         if (folder != NULL)
2715                                 folderItem = FOLDER_ITEM(folder->node->data);
2716                         else
2717                                 debug_print("Unknown folder: '%s'\n",folder_name);
2718                 } else {
2719                         debug_print("%s %s\n",folderItem->name, folderItem->path);
2720                 }
2721
2722                 if (folderItem != NULL) {
2723                         advsearch_set(search, searchType, request);
2724                         advsearch_search_msgs_in_folders(search, &messages, folderItem, recursive);
2725                 } else {
2726                         g_print("Folder '%s' not found.\n'", folder_name);
2727                 }
2728
2729                 GSList *cur;
2730                 for (cur = messages; cur != NULL; cur = cur->next) {
2731                         MsgInfo* msg = (MsgInfo *)cur->data;
2732                         gchar *file = procmsg_get_message_file_path(msg);
2733                         fd_write_all(sock, file, strlen(file));
2734                         fd_write_all(sock, "\n", 1);
2735                         g_free(file);
2736                 }
2737                 fd_write_all(sock, ".\n", 2);
2738
2739 search_exit:
2740                 g_free(folder_name);
2741                 g_free(request);
2742                 advsearch_free(search);
2743                 if (messages != NULL)
2744                         procmsg_msg_list_free(messages);
2745         } else if (!strncmp(buf, "exit", 4)) {
2746                 if (prefs_common.clean_on_exit && !prefs_common.ask_on_clean) {
2747                         procmsg_empty_all_trash();
2748                 }
2749                 app_will_exit(NULL, mainwin);
2750         }
2751         fd_close(sock);
2752
2753 }
2754
2755 static void open_compose_new(const gchar *address, GList *attach_files)
2756 {
2757         gchar *addr = NULL;
2758
2759         if (address) {
2760                 Xstrdup_a(addr, address, return);
2761                 g_strstrip(addr);
2762         }
2763
2764         compose_new(NULL, addr, attach_files);
2765 }
2766
2767 static void send_queue(void)
2768 {
2769         GList *list;
2770         gchar *errstr = NULL;
2771         gboolean error = FALSE;
2772         for (list = folder_get_list(); list != NULL; list = list->next) {
2773                 Folder *folder = list->data;
2774
2775                 if (folder->queue) {
2776                         gint res = procmsg_send_queue
2777                                 (folder->queue, prefs_common.savemsg,
2778                                 &errstr);
2779
2780                         if (res) {
2781                                 folder_item_scan(folder->queue);
2782                         }
2783                         
2784                         if (res < 0)
2785                                 error = TRUE;
2786                 }
2787         }
2788         if (errstr) {
2789                 alertpanel_error_log(_("Some errors occurred "
2790                                 "while sending queued messages:\n%s"), errstr);
2791                 g_free(errstr);
2792         } else if (error) {
2793                 alertpanel_error_log("Some errors occurred "
2794                                 "while sending queued messages.");
2795         }
2796 }
2797
2798 static void quit_signal_handler(int sig)
2799 {
2800         debug_print("Quitting on signal %d\n", sig);
2801
2802         g_timeout_add(0, clean_quit, NULL);
2803 }
2804
2805 static void install_basic_sighandlers()
2806 {
2807 #ifndef G_OS_WIN32
2808         sigset_t    mask;
2809         struct sigaction act;
2810
2811         sigemptyset(&mask);
2812
2813 #ifdef SIGTERM
2814         sigaddset(&mask, SIGTERM);
2815 #endif
2816 #ifdef SIGINT
2817         sigaddset(&mask, SIGINT);
2818 #endif
2819 #ifdef SIGHUP
2820         sigaddset(&mask, SIGHUP);
2821 #endif
2822
2823         act.sa_handler = quit_signal_handler;
2824         act.sa_mask    = mask;
2825         act.sa_flags   = 0;
2826
2827 #ifdef SIGTERM
2828         sigaction(SIGTERM, &act, 0);
2829 #endif
2830 #ifdef SIGINT
2831         sigaction(SIGINT, &act, 0);
2832 #endif  
2833 #ifdef SIGHUP
2834         sigaction(SIGHUP, &act, 0);
2835 #endif  
2836
2837         sigprocmask(SIG_UNBLOCK, &mask, 0);
2838 #endif /* !G_OS_WIN32 */
2839 }
2840
2841 #if (defined linux && defined SIGIO)
2842 static int mem_notify_fd = 0;
2843
2844 static gboolean clean_caches(gpointer unused)
2845 {
2846         if (static_mainwindow && static_mainwindow->lock_count > 0)
2847                 return TRUE;
2848         debug_print("/dev/mem_notify: callback: Freeing some memory now!\n");
2849         folder_clean_cache_memory_force();
2850         return FALSE;
2851 }
2852
2853 static void memory_signal_handler(int sig)
2854 {
2855         debug_print("/dev/mem_notify: Kernel says we should free up some memory!\n");
2856         g_timeout_add(10, clean_caches, NULL); 
2857 }
2858
2859 static void install_memory_sighandler()
2860 {
2861         sigset_t    mask;
2862         struct sigaction act;
2863         int flags;
2864
2865         mem_notify_fd = g_open("/dev/mem_notify", O_RDONLY|O_NONBLOCK, 0);
2866         if (mem_notify_fd == -1) {
2867                 debug_print("/dev/mem_notify not available (%s)\n", 
2868                         g_strerror(errno));
2869                 return;
2870         }
2871         
2872         fcntl(mem_notify_fd, F_SETOWN, getpid());
2873         flags = fcntl(mem_notify_fd, F_GETFL);
2874         fcntl(mem_notify_fd, flags|FASYNC);
2875
2876         sigemptyset(&mask);
2877
2878         sigaddset(&mask, SIGIO);
2879
2880         act.sa_handler = memory_signal_handler;
2881         act.sa_mask    = mask;
2882         act.sa_flags   = 0;
2883
2884         sigaction(SIGIO, &act, 0);
2885
2886         sigprocmask(SIG_UNBLOCK, &mask, 0);
2887
2888         debug_print("/dev/mem_notify: installed handler\n");
2889 }
2890 #endif /* linux && SIGIO */
2891
2892 #ifdef HAVE_NETWORKMANAGER_SUPPORT
2893 static void networkmanager_state_change_cb(DBusGProxy *proxy, gchar *dev,
2894                                          gpointer data)
2895 {
2896         MainWindow *mainWin;
2897
2898         mainWin = NULL;
2899         if (static_mainwindow)
2900                 mainWin = static_mainwindow;
2901         else if (data)
2902                 mainWin = (MainWindow*)data;
2903         
2904         if (!prefs_common.use_networkmanager)
2905                 return;
2906
2907         if (mainWin) {
2908                 GError *error = NULL;
2909                 gboolean online;
2910
2911                 online = networkmanager_is_online(&error);
2912                 if(!error) {
2913                         if(online && went_offline_nm) {
2914                                 went_offline_nm = FALSE;
2915                                 main_window_toggle_work_offline(mainWin, FALSE, FALSE);
2916                                 debug_print("NetworkManager: Went online\n");
2917                                 log_message(LOG_PROTOCOL, _("NetworkManager: network is online.\n"));
2918                         }
2919                         else if(!online) {
2920                                 went_offline_nm = TRUE;
2921                                 main_window_toggle_work_offline(mainWin, TRUE, FALSE);
2922                                 debug_print("NetworkManager: Went offline\n");
2923                                 log_message(LOG_PROTOCOL, _("NetworkManager: network is offline.\n"));
2924                         }
2925                 }
2926                 else {
2927                         debug_print("Failed to get online information from NetworkManager: %s\n",
2928                                                          error->message);
2929                         g_error_free(error);
2930                 }
2931         }
2932         else
2933                 debug_print("NetworkManager: Cannot change connection state because "
2934                                                  "main window does not exist\n");
2935 }
2936
2937 /* Returns true (and sets error appropriately, if given) in case of error */
2938 gboolean networkmanager_is_online(GError **error)
2939 {
2940         DBusGConnection *connection;
2941         DBusGProxy *proxy;
2942         GError *tmp_error = NULL;
2943         gboolean retVal;
2944         guint32 state;
2945
2946         if (!prefs_common.use_networkmanager)
2947                 return TRUE;
2948
2949         tmp_error = NULL;
2950         proxy = NULL;
2951         connection = dbus_g_bus_get(DBUS_BUS_SYSTEM, &tmp_error);
2952
2953         if(!connection) {
2954                 /* If calling code doesn't do error checking, at least print some debug */
2955                 if((error == NULL) || (*error == NULL))
2956                         debug_print("Failed to open connection to system bus: %s\n",
2957                                                          tmp_error->message);
2958                 g_propagate_error(error, tmp_error);
2959                 return TRUE;
2960         }
2961
2962         proxy = dbus_g_proxy_new_for_name(connection,
2963                         "org.freedesktop.NetworkManager",
2964                         "/org/freedesktop/NetworkManager",
2965                         "org.freedesktop.NetworkManager");
2966
2967         retVal = dbus_g_proxy_call(proxy,"state",&tmp_error, G_TYPE_INVALID,
2968                         G_TYPE_UINT, &state, G_TYPE_INVALID);
2969
2970         if(proxy)
2971                 g_object_unref(proxy);
2972         if(connection)
2973                 dbus_g_connection_unref(connection);
2974
2975         if(!retVal) {
2976                 /* If calling code doesn't do error checking, at least print some debug */
2977                 if((error == NULL) || (*error == NULL))
2978                         debug_print("Failed to get state info from NetworkManager: %s\n",
2979                                                          tmp_error->message);
2980                 g_propagate_error(error, tmp_error);
2981                 return TRUE;
2982         }
2983 #if NM_CHECK_VERSION(0,8,992)
2984         return (state == NM_STATE_CONNECTED_LOCAL ||
2985                 state == NM_STATE_CONNECTED_SITE ||
2986                 state == NM_STATE_CONNECTED_GLOBAL ||
2987                 state == NM_STATE_UNKNOWN);
2988 #else
2989         return (state == NM_STATE_CONNECTED ||
2990                 state == NM_STATE_UNKNOWN);
2991 #endif
2992 }
2993 #endif