17d0e12074cd67ef855e386cd2c18d168ffe7497
[claws.git] / src / main.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2007 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 2 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, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <glib.h>
27 #include <glib/gi18n.h>
28 #include <gtk/gtkmain.h>
29 #include <gtk/gtkrc.h>
30
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <ctype.h>
35 #include <unistd.h>
36 #include <time.h>
37 #include <sys/stat.h>
38 #include <sys/types.h>
39 #ifdef G_OS_UNIX
40 #  include <signal.h>
41 #endif
42 #ifdef HAVE_LIBSM
43 #include <X11/SM/SMlib.h>
44 #include <fcntl.h>
45 #endif
46
47 #include "wizard.h"
48 #ifdef HAVE_STARTUP_NOTIFICATION
49 # define SN_API_NOT_YET_FROZEN
50 # include <libsn/sn-launchee.h>
51 # include <gdk/gdkx.h>
52 #endif
53
54 #include "claws.h"
55 #include "main.h"
56 #include "mainwindow.h"
57 #include "folderview.h"
58 #include "image_viewer.h"
59 #include "summaryview.h"
60 #include "prefs_common.h"
61 #include "prefs_account.h"
62 #include "prefs_actions.h"
63 #include "prefs_ext_prog.h"
64 #include "prefs_fonts.h"
65 #include "prefs_image_viewer.h"
66 #include "prefs_message.h"
67 #include "prefs_receive.h"
68 #include "prefs_msg_colors.h"
69 #include "prefs_quote.h"
70 #include "prefs_spelling.h"
71 #include "prefs_summaries.h"
72 #include "prefs_themes.h"
73 #include "prefs_other.h"
74 #include "prefs_logging.h"
75 #include "prefs_send.h"
76 #include "prefs_wrapping.h"
77 #include "prefs_compose_writing.h"
78 #include "prefs_display_header.h"
79 #include "account.h"
80 #include "procmsg.h"
81 #include "inc.h"
82 #include "import.h"
83 #include "manage_window.h"
84 #include "alertpanel.h"
85 #include "statusbar.h"
86 #include "addressbook.h"
87 #include "compose.h"
88 #include "folder.h"
89 #include "setup.h"
90 #include "utils.h"
91 #include "gtkutils.h"
92 #include "socket.h"
93 #include "log.h"
94 #include "prefs_toolbar.h"
95 #include "plugin.h"
96 #include "mh_gtk.h"
97 #include "imap_gtk.h"
98 #include "news_gtk.h"
99 #include "matcher.h"
100 #ifdef HAVE_LIBETPAN
101 #include "imap-thread.h"
102 #endif
103 #include "stock_pixmap.h"
104 #ifdef HAVE_VALGRIND
105 #include "valgrind.h"
106 #endif
107 #if USE_OPENSSL
108 #  include "ssl.h"
109 #endif
110
111 #include "version.h"
112
113 #include "crash.h"
114
115 #include "timing.h"
116
117 gchar *prog_version;
118 gchar *argv0;
119
120 #ifdef HAVE_STARTUP_NOTIFICATION
121 static SnLauncheeContext *sn_context = NULL;
122 static SnDisplay *sn_display = NULL;
123 #endif
124
125 static gint lock_socket = -1;
126 static gint lock_socket_tag = 0;
127 static gchar *x_display = NULL;
128 typedef enum 
129 {
130         ONLINE_MODE_DONT_CHANGE,
131         ONLINE_MODE_ONLINE,
132         ONLINE_MODE_OFFLINE
133 } OnlineMode;
134
135 static struct RemoteCmd {
136         gboolean receive;
137         gboolean receive_all;
138         gboolean compose;
139         const gchar *compose_mailto;
140         GPtrArray *attach_files;
141         gboolean status;
142         gboolean status_full;
143         GPtrArray *status_folders;
144         GPtrArray *status_full_folders;
145         gboolean send;
146         gboolean crash;
147         int online_mode;
148         gchar   *crash_params;
149         gboolean exit;
150         gboolean subscribe;
151         const gchar *subscribe_uri;
152         const gchar *target;
153 } cmd;
154
155 static void parse_cmd_opt(int argc, char *argv[]);
156
157 static gint prohibit_duplicate_launch   (void);
158 static gchar * get_crashfile_name       (void);
159 static gint lock_socket_remove          (void);
160 static void lock_socket_input_cb        (gpointer          data,
161                                          gint              source,
162                                          GdkInputCondition condition);
163
164 static void open_compose_new            (const gchar    *address,
165                                          GPtrArray      *attach_files);
166
167 static void send_queue                  (void);
168 static void initial_processing          (FolderItem *item, gpointer data);
169 static void quit_signal_handler         (int sig);
170 static void install_basic_sighandlers   (void);
171 static void exit_claws                  (MainWindow *mainwin);
172
173 #define MAKE_DIR_IF_NOT_EXIST(dir) \
174 { \
175         if (!is_dir_exist(dir)) { \
176                 if (is_file_exist(dir)) { \
177                         alertpanel_warning \
178                                 (_("File '%s' already exists.\n" \
179                                    "Can't create folder."), \
180                                  dir); \
181                         return 1; \
182                 } \
183                 if (make_dir(dir) < 0) \
184                         return 1; \
185         } \
186 }
187
188 static MainWindow *static_mainwindow;
189 static gboolean emergency_exit = FALSE;
190
191 #ifdef HAVE_STARTUP_NOTIFICATION
192 static void sn_error_trap_push(SnDisplay *display, Display *xdisplay)
193 {
194         gdk_error_trap_push();
195 }
196
197 static void sn_error_trap_pop(SnDisplay *display, Display *xdisplay)
198 {
199         gdk_error_trap_pop();
200 }
201
202 static void startup_notification_complete(gboolean with_window)
203 {
204         Display *xdisplay;
205         GtkWidget *hack = NULL;
206
207         if (with_window) {
208                 /* this is needed to make the startup notification leave,
209                  * if we have been launched from a menu.
210                  * We have to display a window, so let it be very little */
211                 hack = gtk_window_new(GTK_WINDOW_POPUP);
212                 gtk_widget_set_uposition(hack, 0, 0);
213                 gtk_widget_set_size_request(hack, 1, 1);
214                 gtk_widget_show(hack);
215         }
216
217         xdisplay = GDK_DISPLAY();
218         sn_display = sn_display_new(xdisplay,
219                                 sn_error_trap_push,
220                                 sn_error_trap_pop);
221         sn_context = sn_launchee_context_new_from_environment(sn_display,
222                                                  DefaultScreen(xdisplay));
223
224         if (sn_context != NULL) {
225                 sn_launchee_context_complete(sn_context);
226                 sn_launchee_context_unref(sn_context);
227                 sn_display_unref(sn_display);
228         }
229         if (with_window) {
230                 gtk_widget_destroy(hack);
231         }
232 }
233 #endif /* HAVE_STARTUP_NOTIFICATION */
234
235 static void claws_gtk_idle(void) 
236 {
237         while(gtk_events_pending()) {
238                 gtk_main_iteration();
239         }
240         g_usleep(50000);
241 }
242
243 static gboolean defer_check_all(void *data)
244 {
245         gboolean autochk = GPOINTER_TO_INT(data);
246
247         inc_all_account_mail(static_mainwindow, autochk, 
248                         prefs_common.newmail_notify_manu);
249
250         return FALSE;
251 }
252
253 static gboolean defer_check(void *data)
254 {
255         inc_mail(static_mainwindow, prefs_common.newmail_notify_manu);
256
257         return FALSE;
258 }
259
260 static gboolean defer_jump(void *data)
261 {
262         mainwindow_jump_to(data);
263         return FALSE;
264 }
265
266 static void chk_update_val(GtkWidget *widget, gpointer data)
267 {
268         gboolean *val = (gboolean *)data;
269         *val = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget));
270 }
271
272 static gboolean migrate_old_config(const gchar *old_cfg_dir, const gchar *new_cfg_dir, const gchar *oldversion)
273 {
274         gchar *message = g_strdup_printf(_("Configuration for %s (or previous) found.\n"
275                          "Do you want to migrate this configuration?"), oldversion);
276         gint r = 0;
277         GtkWidget *window = NULL;
278         GtkWidget *keep_backup_chk;
279         GtkTooltips *tips = gtk_tooltips_new();
280         gboolean backup = TRUE;
281
282         keep_backup_chk = gtk_check_button_new_with_label (_("Keep old configuration"));
283         gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(keep_backup_chk), TRUE);
284         gtk_tooltips_set_tip(GTK_TOOLTIPS(tips), keep_backup_chk,
285                              _("Keeping a backup will allow you to go back to an "
286                                "older version, but may take a while if you have "
287                                "cached IMAP or News data, and will take some extra "
288                                "room on your disk."),
289                              NULL);
290
291         g_signal_connect(G_OBJECT(keep_backup_chk), "toggled", 
292                         G_CALLBACK(chk_update_val), &backup);
293
294         if (alertpanel_full(_("Migration of configuration"), message,
295                         GTK_STOCK_NO, "+" GTK_STOCK_YES, NULL, FALSE,
296                         keep_backup_chk, ALERT_QUESTION, G_ALERTDEFAULT) != G_ALERTALTERNATE) {
297                 return FALSE;
298         }
299         
300         /* we can either do a fast migration requiring not any extra disk
301          * space, or a slow one that copies the old configuration and leaves
302          * it in place. */
303         if (backup) {
304 backup_mode:
305                 window = label_window_create(_("Copying configuration... This may take a while..."));
306                 GTK_EVENTS_FLUSH();
307                 
308                 r = copy_dir(old_cfg_dir, new_cfg_dir);
309                 gtk_widget_destroy(window);
310                 
311                 /* if copy failed, we'll remove the partially copied
312                  * new directory */
313                 if (r != 0) {
314                         alertpanel_error(_("Migration failed!"));
315                         remove_dir_recursive(new_cfg_dir);
316                 } else {
317                         if (!backup) {
318                                 /* fast mode failed, but we don't want backup */
319                                 remove_dir_recursive(old_cfg_dir);
320                         }
321                 }
322         } else {
323                 window = label_window_create(_("Migrating configuration..."));
324                 GTK_EVENTS_FLUSH();
325                 
326                 r = g_rename(old_cfg_dir, new_cfg_dir);
327                 gtk_widget_destroy(window);
328                 
329                 /* if g_rename failed, we'll try to copy */
330                 if (r != 0) {
331                         FILE_OP_ERROR(new_cfg_dir, "g_rename failed, trying copy\n");
332                         goto backup_mode;
333                 }
334         }
335         return (r == 0);
336 }
337
338 static void migrate_common_rc(const gchar *old_rc, const gchar *new_rc)
339 {
340         FILE *oldfp, *newfp;
341         gchar *plugin_path, *old_plugin_path, *new_plugin_path;
342         gchar buf[BUFFSIZE];
343         oldfp = g_fopen(old_rc, "r");
344         if (!oldfp)
345                 return;
346         newfp = g_fopen(new_rc, "w");
347         if (!newfp) {
348                 fclose(oldfp);
349                 return;
350         }
351         
352         plugin_path = g_strdup(get_plugin_dir());
353         new_plugin_path = g_strdup(plugin_path);
354         
355         if (strstr(plugin_path, "/claws-mail/")) {
356                 gchar *end = g_strdup(strstr(plugin_path, "/claws-mail/")+strlen("/claws-mail/"));
357                 *(strstr(plugin_path, "/claws-mail/")) = '\0';
358                 old_plugin_path = g_strconcat(plugin_path, "/sylpheed-claws/", end, NULL);
359                 g_free(end);
360         } else {
361                 old_plugin_path = g_strdup(new_plugin_path);
362         }
363         debug_print("replacing %s with %s\n", old_plugin_path, new_plugin_path);
364         while (fgets(buf, sizeof(buf), oldfp)) {
365                 if (strncmp(buf, old_plugin_path, strlen(old_plugin_path))) {
366                         fputs(buf, newfp);
367                 } else {
368                         debug_print("->replacing %s", buf);
369                         debug_print("  with %s%s", new_plugin_path, buf+strlen(old_plugin_path));
370                         fputs(new_plugin_path, newfp);
371                         fputs(buf+strlen(old_plugin_path), newfp);
372                 }
373         }
374         g_free(plugin_path);
375         g_free(new_plugin_path);
376         g_free(old_plugin_path);
377         fclose(oldfp);
378         fclose(newfp);
379 }
380
381 #ifdef HAVE_LIBSM
382 static void
383 sc_client_set_value (MainWindow *mainwin,
384                   gchar       *name,
385                   char        *type,
386                   int          num_vals,
387                   SmPropValue *vals)
388 {
389         SmProp *proplist[1];
390         SmProp prop;
391
392         prop.name = name;
393         prop.type = type;
394         prop.num_vals = num_vals;
395         prop.vals = vals;
396
397         proplist[0]= &prop;
398         if (mainwin->smc_conn)
399                 SmcSetProperties ((SmcConn) mainwin->smc_conn, 1, proplist);
400 }
401
402 static void sc_die_callback (SmcConn smc_conn, SmPointer client_data)
403 {
404         clean_quit(NULL);
405 }
406
407 static void sc_save_complete_callback(SmcConn smc_conn, SmPointer client_data)
408 {
409 }
410
411 static void sc_shutdown_cancelled_callback (SmcConn smc_conn, SmPointer client_data)
412 {
413         MainWindow *mainwin = (MainWindow *)client_data;
414         if (mainwin->smc_conn)
415                 SmcSaveYourselfDone ((SmcConn) mainwin->smc_conn, TRUE);
416 }
417
418 static void sc_save_yourself_callback (SmcConn   smc_conn,
419                                SmPointer client_data,
420                                int       save_style,
421                                gboolean  shutdown,
422                                int       interact_style,
423                                gboolean  fast) {
424
425         MainWindow *mainwin = (MainWindow *)client_data;
426         if (mainwin->smc_conn)
427                 SmcSaveYourselfDone ((SmcConn) mainwin->smc_conn, TRUE);
428 }
429
430 static IceIOErrorHandler sc_ice_installed_handler;
431
432 static void sc_ice_io_error_handler (IceConn connection)
433 {
434         if (sc_ice_installed_handler)
435                 (*sc_ice_installed_handler) (connection);
436 }
437 static gboolean sc_process_ice_messages (GIOChannel   *source,
438                       GIOCondition  condition,
439                       gpointer      data)
440 {
441         IceConn connection = (IceConn) data;
442         IceProcessMessagesStatus status;
443
444         status = IceProcessMessages (connection, NULL, NULL);
445
446         if (status == IceProcessMessagesIOError) {
447                 IcePointer context = IceGetConnectionContext (connection);
448
449                 if (context && GTK_IS_OBJECT (context)) {
450                 guint disconnect_id = g_signal_lookup ("disconnect", G_OBJECT_TYPE (context));
451
452                 if (disconnect_id > 0)
453                         g_signal_emit (context, disconnect_id, 0);
454                 } else {
455                         IceSetShutdownNegotiation (connection, False);
456                         IceCloseConnection (connection);
457                 }
458         }
459
460         return TRUE;
461 }
462
463 static void new_ice_connection (IceConn connection, IcePointer client_data, Bool opening,
464                     IcePointer *watch_data)
465 {
466         guint input_id;
467
468         if (opening) {
469                 GIOChannel *channel;
470                 /* Make sure we don't pass on these file descriptors to any
471                 exec'ed children */
472                 fcntl(IceConnectionNumber(connection),F_SETFD,
473                 fcntl(IceConnectionNumber(connection),F_GETFD,0) | FD_CLOEXEC);
474
475                 channel = g_io_channel_unix_new (IceConnectionNumber (connection));
476                 input_id = g_io_add_watch (channel,
477                 G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_PRI,
478                 sc_process_ice_messages,
479                 connection);
480                 g_io_channel_unref (channel);
481
482                 *watch_data = (IcePointer) GUINT_TO_POINTER (input_id);
483         } else {
484                 input_id = GPOINTER_TO_UINT ((gpointer) *watch_data);
485                 g_source_remove (input_id);
486         }
487 }
488
489 static void sc_session_manager_connect(MainWindow *mainwin)
490 {
491         static gboolean connected = FALSE;
492         SmcCallbacks      callbacks;
493         gchar            *client_id;
494         IceIOErrorHandler default_handler;
495
496         if (connected)
497                 return;
498         connected = TRUE;
499
500
501         sc_ice_installed_handler = IceSetIOErrorHandler (NULL);
502         default_handler = IceSetIOErrorHandler (sc_ice_io_error_handler);
503
504         if (sc_ice_installed_handler == default_handler)
505                 sc_ice_installed_handler = NULL;
506
507         IceAddConnectionWatch (new_ice_connection, NULL);
508       
509       
510         callbacks.save_yourself.callback      = sc_save_yourself_callback;
511         callbacks.die.callback                = sc_die_callback;
512         callbacks.save_complete.callback      = sc_save_complete_callback;
513         callbacks.shutdown_cancelled.callback = sc_shutdown_cancelled_callback;
514
515         callbacks.save_yourself.client_data =
516                 callbacks.die.client_data =
517                 callbacks.save_complete.client_data =
518                 callbacks.shutdown_cancelled.client_data = (SmPointer) mainwin;
519         if (g_getenv ("SESSION_MANAGER")) {
520                 gchar error_string_ret[256] = "";
521
522                 mainwin->smc_conn = (gpointer)
523                         SmcOpenConnection (NULL, mainwin,
524                                 SmProtoMajor, SmProtoMinor,
525                                 SmcSaveYourselfProcMask | SmcDieProcMask |
526                                 SmcSaveCompleteProcMask |
527                                 SmcShutdownCancelledProcMask,
528                                 &callbacks,
529                                 NULL, &client_id,
530                                 256, error_string_ret);
531
532                 if (error_string_ret[0] || mainwin->smc_conn == NULL)
533                         g_warning ("While connecting to session manager:\n%s.",
534                                 error_string_ret);
535                 else {
536                         SmPropValue *vals;
537                         vals = g_new (SmPropValue, 1);
538                         vals[0].length = strlen(argv0);
539                         vals[0].value = argv0;
540                         sc_client_set_value (mainwin, SmCloneCommand, SmLISTofARRAY8, 1, vals);
541                         sc_client_set_value (mainwin, SmRestartCommand, SmLISTofARRAY8, 1, vals);
542                         sc_client_set_value (mainwin, SmProgram, SmARRAY8, 1, vals);
543
544                         vals[0].length = strlen(g_get_user_name()?g_get_user_name():"");
545                         vals[0].value = g_strdup(g_get_user_name()?g_get_user_name():"");
546                         sc_client_set_value (mainwin, SmUserID, SmARRAY8, 1, vals);
547                 }
548         }
549 }
550 #endif
551
552 static gboolean sc_exiting = FALSE;
553 static gboolean sc_starting = FALSE;
554 static gboolean show_at_startup = TRUE;
555
556 void main_set_show_at_startup(gboolean show)
557 {
558         show_at_startup = show;
559 }
560
561 int main(int argc, char *argv[])
562 {
563         gchar *userrc;
564         MainWindow *mainwin;
565         FolderView *folderview;
566         GdkPixbuf *icon;
567         gboolean crash_file_present = FALSE;
568         gint num_folder_class = 0;
569         gboolean asked_for_migration = FALSE;
570
571         START_TIMING("startup");
572         
573         sc_starting = TRUE;
574
575         if (!claws_init(&argc, &argv)) {
576                 return 0;
577         }
578
579         prefs_prepare_cache();
580         prog_version = PROG_VERSION;
581         argv0 = g_strdup(argv[0]);
582
583         parse_cmd_opt(argc, argv);
584
585 #ifdef CRASH_DIALOG
586         if (cmd.crash) {
587                 gtk_set_locale();
588                 gtk_init(&argc, &argv);
589                 crash_main(cmd.crash_params);
590                 return 0;
591         }
592         crash_install_handlers();
593 #endif
594         install_basic_sighandlers();
595         sock_init();
596
597         /* check and create unix domain socket for remote operation */
598 #ifdef G_OS_UNIX
599         lock_socket = prohibit_duplicate_launch();
600         if (lock_socket < 0) {
601 #ifdef HAVE_STARTUP_NOTIFICATION
602                 if(gtk_init_check(&argc, &argv))
603                         startup_notification_complete(TRUE);
604 #endif
605                 return 0;
606         }
607
608         if (cmd.status || cmd.status_full) {
609                 puts("0 Claws Mail not running.");
610                 lock_socket_remove();
611                 return 0;
612         }
613         
614         if (cmd.exit)
615                 return 0;
616 #endif
617         if (!g_thread_supported())
618                 g_thread_init(NULL);
619
620         gtk_set_locale();
621         gtk_init(&argc, &argv);
622
623         gdk_rgb_init();
624         gtk_widget_set_default_colormap(gdk_rgb_get_colormap());
625         gtk_widget_set_default_visual(gdk_rgb_get_visual());
626
627         if (!g_thread_supported()) {
628                 g_error(_("g_thread is not supported by glib.\n"));
629         }
630
631         /* check that we're not on a too recent/old gtk+ */
632 #if GTK_CHECK_VERSION(2, 9, 0)
633         if (gtk_check_version(2, 9, 0) != NULL) {
634                 alertpanel_error(_("Claws Mail has been compiled with "
635                                    "a more recent GTK+ library than is "
636                                    "currently available. This will cause "
637                                    "crashes. You need to upgrade GTK+ or "
638                                    "recompile Claws Mail."));
639                 exit(1);
640         }
641 #else
642         if (gtk_check_version(2, 9, 0) == NULL) {
643                 alertpanel_error(_("Claws Mail has been compiled with "
644                                    "an older GTK+ library than is "
645                                    "currently available. This will cause "
646                                    "crashes. You need to recompile "
647                                    "Claws Mail."));
648                 exit(1);
649         }
650 #endif  
651         /* parse gtkrc files */
652         userrc = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".gtkrc-2.0",
653                              NULL);
654         gtk_rc_parse(userrc);
655         g_free(userrc);
656         userrc = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".gtk",
657                              G_DIR_SEPARATOR_S, "gtkrc-2.0", NULL);
658         gtk_rc_parse(userrc);
659         g_free(userrc);
660
661         CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
662         
663         /* no config dir exists. See if we can migrate an old config. */
664         if (!is_dir_exist(RC_DIR)) {
665                 prefs_destroy_cache();
666                 gboolean r = FALSE;
667                 
668                 /* if one of the old dirs exist, we'll ask if the user 
669                  * want to migrates, and r will be TRUE if he said yes
670                  * and migration succeeded, and FALSE otherwise.
671                  */
672                 if (is_dir_exist(OLD_GTK2_RC_DIR)) {
673                         r = migrate_old_config(OLD_GTK2_RC_DIR, RC_DIR, "Sylpheed-Claws 2.6.0");
674                         asked_for_migration = TRUE;
675                 } else if (is_dir_exist(OLDER_GTK2_RC_DIR)) {
676                         r = migrate_old_config(OLDER_GTK2_RC_DIR, RC_DIR, "Sylpheed-Claws 1.9.15");
677                         asked_for_migration = TRUE;
678                 } else if (is_dir_exist(OLD_GTK1_RC_DIR)) {
679                         r = migrate_old_config(OLD_GTK1_RC_DIR, RC_DIR, "Sylpheed-Claws 1.0.5");
680                         asked_for_migration = TRUE;
681                 }
682                 
683                 /* If migration failed or the user didn't want to do it,
684                  * we create a new one (and we'll hit wizard later). 
685                  */
686                 if (r == FALSE && !is_dir_exist(RC_DIR) && make_dir(RC_DIR) < 0)
687                         exit(1);
688         }
689         
690
691         if (!is_file_exist(RC_DIR G_DIR_SEPARATOR_S COMMON_RC) &&
692             is_file_exist(RC_DIR G_DIR_SEPARATOR_S OLD_COMMON_RC)) {
693                 /* post 2.6 name change */
694                 migrate_common_rc(RC_DIR G_DIR_SEPARATOR_S OLD_COMMON_RC,
695                           RC_DIR G_DIR_SEPARATOR_S COMMON_RC);
696         }
697
698         if (!cmd.exit)
699                 plugin_load_all("Common");
700
701         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, "gtkrc-2.0", NULL);
702         gtk_rc_parse(userrc);
703         g_free(userrc);
704
705         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
706         gtk_accel_map_load (userrc);
707         g_free(userrc);
708
709         CHDIR_RETURN_VAL_IF_FAIL(get_rc_dir(), 1);
710
711         MAKE_DIR_IF_NOT_EXIST(get_mail_base_dir());
712         MAKE_DIR_IF_NOT_EXIST(get_imap_cache_dir());
713         MAKE_DIR_IF_NOT_EXIST(get_news_cache_dir());
714         MAKE_DIR_IF_NOT_EXIST(get_mime_tmp_dir());
715         MAKE_DIR_IF_NOT_EXIST(get_tmp_dir());
716         MAKE_DIR_IF_NOT_EXIST(UIDL_DIR);
717
718         crash_file_present = is_file_exist(get_crashfile_name());
719         /* remove temporary files */
720         remove_all_files(get_tmp_dir());
721         remove_all_files(get_mime_tmp_dir());
722
723         if (is_file_exist("claws.log")) {
724                 if (rename_force("claws.log", "claws.log.bak") < 0)
725                         FILE_OP_ERROR("claws.log", "rename");
726         }
727         set_log_file(LOG_PROTOCOL, "claws.log");
728
729         if (is_file_exist("filtering.log")) {
730                 if (rename_force("filtering.log", "filtering.log.bak") < 0)
731                         FILE_OP_ERROR("filtering.log", "rename");
732         }
733         set_log_file(LOG_DEBUG_FILTERING, "filtering.log");
734
735         CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
736
737         folder_system_init();
738         prefs_common_read_config();
739
740         prefs_themes_init();
741         prefs_fonts_init();
742         prefs_ext_prog_init();
743         prefs_wrapping_init();
744         prefs_compose_writing_init();
745         prefs_msg_colors_init();
746         image_viewer_init();
747         prefs_image_viewer_init();
748         prefs_quote_init();
749         prefs_summaries_init();
750         prefs_message_init();
751         prefs_other_init();
752         prefs_logging_init();
753         prefs_receive_init();
754         prefs_send_init();
755 #ifdef USE_ASPELL
756         gtkaspell_checkers_init();
757         prefs_spelling_init();
758 #endif
759
760         sock_set_io_timeout(prefs_common.io_timeout_secs);
761 #ifdef HAVE_LIBETPAN
762         imap_main_set_timeout(prefs_common.io_timeout_secs);
763 #endif
764         prefs_actions_read_config();
765         prefs_display_header_read_config();
766         /* prefs_filtering_read_config(); */
767         addressbook_read_file();
768         renderer_read_config();
769
770         gtkut_widget_init();
771         stock_pixbuf_gdk(NULL, STOCK_PIXMAP_CLAWS_MAIL_ICON, &icon);
772         gtk_window_set_default_icon(icon);
773
774         folderview_initialize();
775
776         mh_gtk_init();
777         imap_gtk_init();
778         news_gtk_init();
779
780         mainwin = main_window_create();
781
782         manage_window_focus_in(mainwin->window, NULL, NULL);
783         folderview = mainwin->folderview;
784
785         gtk_clist_freeze(GTK_CLIST(mainwin->folderview->ctree));
786         folder_item_update_freeze();
787
788         /* register the callback of unix domain socket input */
789 #ifdef G_OS_UNIX
790         lock_socket_tag = gdk_input_add(lock_socket,
791                                         GDK_INPUT_READ | GDK_INPUT_EXCEPTION,
792                                         lock_socket_input_cb,
793                                         mainwin);
794 #endif
795
796         prefs_account_init();
797         account_read_config_all();
798
799         /* If we can't read a folder list or don't have accounts,
800          * it means the configuration's not done. Either this is
801          * a brand new install, either a failed/refused migration.
802          * So we'll start the wizard.
803          */
804         if (folder_read_list() < 0) {
805                 prefs_destroy_cache();
806                 
807                 /* if run_wizard returns FALSE it's because it's
808                  * been cancelled. We can't do much but exit.
809                  * however, if the user was asked for a migration,
810                  * we remove the newly created directory so that
811                  * he's asked again for migration on next launch.*/
812                 if (!run_wizard(mainwin, TRUE)) {
813                         if (asked_for_migration)
814                                 remove_dir_recursive(RC_DIR);
815                         exit(1);
816                 }
817                 main_window_reflect_prefs_all_now();
818                 folder_write_list();
819         }
820
821         if (!account_get_list()) {
822                 prefs_destroy_cache();
823                 if (!run_wizard(mainwin, FALSE)) {
824                         if (asked_for_migration)
825                                 remove_dir_recursive(RC_DIR);
826                         exit(1);
827                 }
828                 account_read_config_all();
829                 if(!account_get_list()) {
830                         exit_claws(mainwin);
831                         exit(1);
832                 }
833         }
834
835         
836         toolbar_main_set_sensitive(mainwin);
837         main_window_set_menu_sensitive(mainwin);
838
839         /* if crashed, show window early so that the user
840          * sees what's happening */
841         if (!cmd.crash && crash_file_present)
842                 main_window_popup(mainwin);
843
844 #ifdef HAVE_LIBETPAN
845         imap_main_init(prefs_common.skip_ssl_cert_check);
846 #endif  
847         account_set_missing_folder();
848         folder_set_missing_folders();
849         folderview_set(folderview);
850
851         prefs_matcher_read_config();
852
853         /* make one all-folder processing before using claws */
854         main_window_cursor_wait(mainwin);
855         folder_func_to_all_folders(initial_processing, (gpointer *)mainwin);
856
857         /* if claws crashed, rebuild caches */
858         if (!cmd.crash && crash_file_present) {
859                 GTK_EVENTS_FLUSH();
860                 debug_print("Claws Mail crashed, checking for new messages in local folders\n");
861                 folder_item_update_thaw();
862                 folderview_check_new(NULL);
863                 folder_clean_cache_memory_force();
864                 folder_item_update_freeze();
865         }
866         /* make the crash-indicator file */
867         str_write_to_file("foo", get_crashfile_name());
868
869         inc_autocheck_timer_init(mainwin);
870
871         /* ignore SIGPIPE signal for preventing sudden death of program */
872 #ifdef G_OS_UNIX
873         signal(SIGPIPE, SIG_IGN);
874 #endif
875         if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
876                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
877         }
878         if (cmd.online_mode == ONLINE_MODE_ONLINE) {
879                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
880         }
881
882         if (cmd.status_folders) {
883                 g_ptr_array_free(cmd.status_folders, TRUE);
884                 cmd.status_folders = NULL;
885         }
886         if (cmd.status_full_folders) {
887                 g_ptr_array_free(cmd.status_full_folders, TRUE);
888                 cmd.status_full_folders = NULL;
889         }
890
891         claws_register_idle_function(claws_gtk_idle);
892
893         prefs_toolbar_init();
894
895         num_folder_class = g_list_length(folder_get_list());
896
897         plugin_load_all("GTK2");
898
899         if (g_list_length(folder_get_list()) != num_folder_class) {
900                 debug_print("new folders loaded, reloading processing rules\n");
901                 prefs_matcher_read_config();
902         }
903         
904         if (plugin_get_unloaded_list() != NULL) {
905                 main_window_cursor_normal(mainwin);
906                 alertpanel_warning(_("Some plugin(s) failed to load. "
907                                      "Check the Plugins configuration "
908                                      "for more information."));
909                 main_window_cursor_wait(mainwin);
910         }
911
912         plugin_load_standard_plugins ();
913        
914         /* if not crashed, show window now */
915         if (!(!cmd.crash && crash_file_present)) {
916                 /* apart if something told not to show */
917                 if (show_at_startup)
918                         main_window_popup(mainwin);
919         }
920
921         if (!folder_have_mailbox()) {
922                 prefs_destroy_cache();
923                 main_window_cursor_normal(mainwin);
924                 if (folder_get_list() != NULL) {
925                         alertpanel_error(_("Claws Mail has detected a configured "
926                                    "mailbox, but it is incomplete. It is "
927                                    "possibly due to a failing IMAP account. Use "
928                                    "\"Rebuild folder tree\" on the mailbox parent "
929                                    "folder's context menu to try to fix it."));
930                 } else {
931                         alertpanel_error(_("Claws Mail has detected a configured "
932                                    "mailbox, but could not load it. It is "
933                                    "probably provided by an out-of-date "
934                                    "external plugin. Please reinstall the "
935                                    "plugin and try again."));
936                         exit_claws(mainwin);
937                         exit(1);
938                 }
939         }
940         
941         static_mainwindow = mainwin;
942
943 #ifdef HAVE_STARTUP_NOTIFICATION
944         startup_notification_complete(FALSE);
945 #endif
946 #ifdef HAVE_LIBSM
947         sc_session_manager_connect(mainwin);
948 #endif
949         folder_item_update_thaw();
950         gtk_clist_thaw(GTK_CLIST(mainwin->folderview->ctree));
951         main_window_cursor_normal(mainwin);
952
953         if (cmd.receive_all) {
954                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(FALSE));
955         } else if (prefs_common.chk_on_startup) {
956                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(TRUE));
957         } else if (cmd.receive) {
958                 g_timeout_add(1000, defer_check, NULL);
959         } else {
960                 gtk_widget_grab_focus(folderview->ctree);
961         }
962
963         if (cmd.compose) {
964                 open_compose_new(cmd.compose_mailto, cmd.attach_files);
965         }
966         if (cmd.attach_files) {
967                 ptr_array_free_strings(cmd.attach_files);
968                 g_ptr_array_free(cmd.attach_files, TRUE);
969                 cmd.attach_files = NULL;
970         }
971         if (cmd.subscribe) {
972                 folder_subscribe(cmd.subscribe_uri);
973         }
974
975         if (cmd.send) {
976                 send_queue();
977         }
978         
979         if (cmd.target) {
980                 g_timeout_add(500, defer_jump, (gpointer)cmd.target);
981         }
982
983         prefs_destroy_cache();
984         
985         compose_reopen_exit_drafts();
986
987         sc_starting = FALSE;
988         END_TIMING();
989
990         gtk_main();
991
992         exit_claws(mainwin);
993
994         return 0;
995 }
996
997 static void save_all_caches(FolderItem *item, gpointer data)
998 {
999         if (!item->cache) {
1000                 return;
1001         }
1002
1003         if (item->opened)
1004                 folder_item_close(item);
1005         
1006         folder_item_free_cache(item, TRUE);
1007 }
1008
1009 static void exit_claws(MainWindow *mainwin)
1010 {
1011         gchar *filename;
1012
1013         sc_exiting = TRUE;
1014
1015         debug_print("shutting down\n");
1016         inc_autocheck_timer_remove();
1017
1018         if (prefs_common.clean_on_exit && !emergency_exit) {
1019                 main_window_empty_trash(mainwin, prefs_common.ask_on_clean);
1020         }
1021
1022         /* save prefs for opened folder */
1023         if(mainwin->folderview->opened) {
1024                 FolderItem *item;
1025
1026                 item = gtk_ctree_node_get_row_data(GTK_CTREE(mainwin->folderview->ctree), mainwin->folderview->opened);
1027                 summary_save_prefs_to_folderitem(mainwin->folderview->summaryview, item);
1028         }
1029
1030         /* save all state before exiting */
1031         folder_func_to_all_folders(save_all_caches, NULL);
1032         folder_write_list();
1033
1034         main_window_get_size(mainwin);
1035         main_window_get_position(mainwin);
1036
1037         prefs_common_write_config();
1038         account_write_config_all();
1039         addressbook_export_to_file();
1040
1041         filename = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
1042         gtk_accel_map_save(filename);
1043         g_free(filename);
1044
1045         /* delete temporary files */
1046         remove_all_files(get_tmp_dir());
1047         remove_all_files(get_mime_tmp_dir());
1048
1049         close_log_file(LOG_PROTOCOL);
1050         close_log_file(LOG_DEBUG_FILTERING);
1051
1052 #ifdef HAVE_LIBETPAN
1053         imap_main_done();
1054 #endif
1055         /* delete crashfile */
1056         if (!cmd.crash)
1057                 g_unlink(get_crashfile_name());
1058
1059         lock_socket_remove();
1060
1061 #ifdef HAVE_LIBSM
1062         if (mainwin->smc_conn)
1063                 SmcCloseConnection ((SmcConn)mainwin->smc_conn, 0, NULL);
1064         mainwin->smc_conn = NULL;
1065 #endif
1066
1067         main_window_destroy_all();
1068         
1069         plugin_unload_all("GTK2");
1070
1071         prefs_toolbar_done();
1072
1073         addressbook_destroy();
1074
1075         prefs_themes_done();
1076         prefs_fonts_done();
1077         prefs_ext_prog_done();
1078         prefs_wrapping_done();
1079         prefs_compose_writing_done();
1080         prefs_msg_colors_done();
1081         prefs_image_viewer_done();
1082         image_viewer_done();
1083         prefs_quote_done();
1084         prefs_summaries_done();
1085         prefs_message_done();
1086         prefs_other_done();
1087         prefs_receive_done();
1088         prefs_send_done();
1089 #ifdef USE_ASPELL       
1090         prefs_spelling_done();
1091         gtkaspell_checkers_quit();
1092 #endif
1093         plugin_unload_all("Common");
1094         claws_done();
1095 }
1096
1097 static void parse_cmd_opt(int argc, char *argv[])
1098 {
1099         gint i;
1100
1101         for (i = 1; i < argc; i++) {
1102                 if (!strncmp(argv[i], "--receive-all", 13)) {
1103                         cmd.receive_all = TRUE;
1104                 } else if (!strncmp(argv[i], "--receive", 9)) {
1105                         cmd.receive = TRUE;
1106                 } else if (!strncmp(argv[i], "--compose", 9)) {
1107                         const gchar *p = argv[i + 1];
1108
1109                         cmd.compose = TRUE;
1110                         cmd.compose_mailto = NULL;
1111                         if (p && *p != '\0' && *p != '-') {
1112                                 if (!strncmp(p, "mailto:", 7)) {
1113                                         cmd.compose_mailto = p + 7;
1114                                 } else {
1115                                         cmd.compose_mailto = p;
1116                                 }
1117                                 i++;
1118                         }
1119                 } else if (!strncmp(argv[i], "--subscribe", 11)) {
1120                         const gchar *p = argv[i + 1];
1121                         if (p && *p != '\0' && *p != '-') {
1122                                 cmd.subscribe = TRUE;
1123                                 cmd.subscribe_uri = p;
1124                         }
1125                 } else if (!strncmp(argv[i], "--attach", 8)) {
1126                         const gchar *p = argv[i + 1];
1127                         gchar *file = NULL;
1128
1129                         while (p && *p != '\0' && *p != '-') {
1130                                 if (!cmd.attach_files) {
1131                                         cmd.attach_files = g_ptr_array_new();
1132                                 }
1133                                 if ((file = g_filename_from_uri(p, NULL, NULL)) != NULL) {
1134                                         if (!is_file_exist(file)) {
1135                                                 g_free(file);
1136                                                 file = NULL;
1137                                         }
1138                                 }
1139                                 if (file == NULL && *p != G_DIR_SEPARATOR) {
1140                                         file = g_strconcat(claws_get_startup_dir(),
1141                                                            G_DIR_SEPARATOR_S,
1142                                                            p, NULL);
1143                                 } else if (file == NULL) {
1144                                         file = g_strdup(p);
1145                                 }
1146                                 g_ptr_array_add(cmd.attach_files, file);
1147                                 i++;
1148                                 p = argv[i + 1];
1149                         }
1150                 } else if (!strncmp(argv[i], "--send", 6)) {
1151                         cmd.send = TRUE;
1152                 } else if (!strncmp(argv[i], "--version", 9) ||
1153                            !strncmp(argv[i], "-v", 2)) {
1154                         puts("Claws Mail version " VERSION);
1155                         exit(0);
1156                 } else if (!strncmp(argv[i], "--status-full", 13)) {
1157                         const gchar *p = argv[i + 1];
1158  
1159                         cmd.status_full = TRUE;
1160                         while (p && *p != '\0' && *p != '-') {
1161                                 if (!cmd.status_full_folders) {
1162                                         cmd.status_full_folders =
1163                                                 g_ptr_array_new();
1164                                 }
1165                                 g_ptr_array_add(cmd.status_full_folders,
1166                                                 g_strdup(p));
1167                                 i++;
1168                                 p = argv[i + 1];
1169                         }
1170                 } else if (!strncmp(argv[i], "--status", 8)) {
1171                         const gchar *p = argv[i + 1];
1172  
1173                         cmd.status = TRUE;
1174                         while (p && *p != '\0' && *p != '-') {
1175                                 if (!cmd.status_folders)
1176                                         cmd.status_folders = g_ptr_array_new();
1177                                 g_ptr_array_add(cmd.status_folders,
1178                                                 g_strdup(p));
1179                                 i++;
1180                                 p = argv[i + 1];
1181                         }
1182                 } else if (!strncmp(argv[i], "--online", 8)) {
1183                         cmd.online_mode = ONLINE_MODE_ONLINE;
1184                 } else if (!strncmp(argv[i], "--offline", 9)) {
1185                         cmd.online_mode = ONLINE_MODE_OFFLINE;
1186                 } else if (!strncmp(argv[i], "--help", 6) ||
1187                            !strncmp(argv[i], "-h", 2)) {
1188                         gchar *base = g_path_get_basename(argv[0]);
1189                         g_print(_("Usage: %s [OPTION]...\n"), base);
1190
1191                         g_print("%s\n", _("  --compose [address]    open composition window"));
1192                         g_print("%s\n", _("  --subscribe [uri]      subscribe to the given URI if possible"));
1193                         g_print("%s\n", _("  --attach file1 [file2]...\n"
1194                                   "                         open composition window with specified files\n"
1195                                   "                         attached"));
1196                         g_print("%s\n", _("  --receive              receive new messages"));
1197                         g_print("%s\n", _("  --receive-all          receive new messages of all accounts"));
1198                         g_print("%s\n", _("  --send                 send all queued messages"));
1199                         g_print("%s\n", _("  --status [folder]...   show the total number of messages"));
1200                         g_print("%s\n", _("  --status-full [folder]...\n"
1201                                "                         show the status of each folder"));
1202                         g_print("%s\n", _("  --select folder[/msg]  jumps to the specified folder/message\n" 
1203                                           "                         folder is a folder id like 'folder/sub_folder'"));
1204                         g_print("%s\n", _("  --online               switch to online mode"));
1205                         g_print("%s\n", _("  --offline              switch to offline mode"));
1206                         g_print("%s\n", _("  --exit --quit -q       exit Claws Mail"));
1207                         g_print("%s\n", _("  --debug                debug mode"));
1208                         g_print("%s\n", _("  --help -h              display this help and exit"));
1209                         g_print("%s\n", _("  --version -v           output version information and exit"));
1210                         g_print("%s\n", _("  --config-dir           output configuration directory"));
1211
1212                         g_free(base);
1213                         exit(1);
1214                 } else if (!strncmp(argv[i], "--crash", 7)) {
1215                         cmd.crash = TRUE;
1216                         cmd.crash_params = g_strdup(argv[i + 1]);
1217                         i++;
1218                 } else if (!strncmp(argv[i], "--config-dir", sizeof "--config-dir" - 1)) {
1219                         puts(RC_DIR);
1220                         exit(0);
1221                 } else if (!strncmp(argv[i], "--exit", 6) ||
1222                            !strncmp(argv[i], "--quit", 6) ||
1223                            !strncmp(argv[i], "-q", 2)) {
1224                         cmd.exit = TRUE;
1225                 } else if (!strncmp(argv[i], "--select", 8) && i+1 < argc) {
1226                         cmd.target = argv[i+1];
1227                 } else if (i == 1 && argc == 2) {
1228                         /* only one parameter. Do something intelligent about it */
1229                         if (strstr(argv[i], "@") && !strstr(argv[i], "://")) {
1230                                 const gchar *p = argv[i];
1231
1232                                 cmd.compose = TRUE;
1233                                 cmd.compose_mailto = NULL;
1234                                 if (p && *p != '\0' && *p != '-') {
1235                                         if (!strncmp(p, "mailto:", 7)) {
1236                                                 cmd.compose_mailto = p + 7;
1237                                         } else {
1238                                                 cmd.compose_mailto = p;
1239                                         }
1240                                 }
1241                         } else if (strstr(argv[i], "://")) {
1242                                 const gchar *p = argv[i];
1243                                 if (p && *p != '\0' && *p != '-') {
1244                                         cmd.subscribe = TRUE;
1245                                         cmd.subscribe_uri = p;
1246                                 }
1247                         } else if (!strcmp(argv[i], "--sync")) {
1248                                 /* gtk debug */
1249                         } else {
1250                                 g_print(_("Unknown option\n"));
1251                                 exit(1);
1252                         }
1253                 }
1254         }
1255
1256         if (cmd.attach_files && cmd.compose == FALSE) {
1257                 cmd.compose = TRUE;
1258                 cmd.compose_mailto = NULL;
1259         }
1260 }
1261
1262 static void initial_processing(FolderItem *item, gpointer data)
1263 {
1264         MainWindow *mainwin = (MainWindow *)data;
1265         gchar *buf;
1266
1267         g_return_if_fail(item);
1268         buf = g_strdup_printf(_("Processing (%s)..."), 
1269                               item->path 
1270                               ? item->path 
1271                               : _("top level folder"));
1272         g_free(buf);
1273
1274         
1275         if (item->prefs->enable_processing) {
1276                 folder_item_apply_processing(item);
1277         }
1278
1279         STATUSBAR_POP(mainwin);
1280 }
1281
1282 static void draft_all_messages(void)
1283 {
1284         GList *compose_list = NULL;
1285         
1286         compose_clear_exit_drafts();
1287         while ((compose_list = compose_get_compose_list()) != NULL) {
1288                 Compose *c = (Compose*)compose_list->data;
1289                 compose_draft(c, COMPOSE_DRAFT_FOR_EXIT);
1290         }       
1291 }
1292 gboolean clean_quit(gpointer data)
1293 {
1294         static gboolean firstrun = TRUE;
1295
1296         if (!firstrun) {
1297                 return FALSE;
1298         }
1299         firstrun = FALSE;
1300
1301         /*!< Good idea to have the main window stored in a 
1302          *   static variable so we can check that variable
1303          *   to see if we're really allowed to do things
1304          *   that actually the spawner is supposed to 
1305          *   do (like: sending mail, composing messages).
1306          *   Because, really, if we're the spawnee, and
1307          *   we touch GTK stuff, we're hosed. See the 
1308          *   next fixme. */
1309
1310         /* FIXME: Use something else to signal that we're
1311          * in the original spawner, and not in a spawned
1312          * child. */
1313         if (!static_mainwindow) {
1314                 return FALSE;
1315         }
1316                 
1317         draft_all_messages();
1318         emergency_exit = TRUE;
1319         exit_claws(static_mainwindow);
1320         exit(0);
1321
1322         return FALSE;
1323 }
1324
1325 void app_will_exit(GtkWidget *widget, gpointer data)
1326 {
1327         MainWindow *mainwin = data;
1328         
1329         if (sc_exiting == TRUE) {
1330                 debug_print("exit pending\n");
1331                 return;
1332         }
1333         sc_exiting = TRUE;
1334         debug_print("exiting\n");
1335         if (compose_get_compose_list()) {
1336                 draft_all_messages();
1337         }
1338
1339         if (prefs_common.warn_queued_on_exit && procmsg_have_queued_mails_fast()) {
1340                 if (alertpanel(_("Queued messages"),
1341                                _("Some unsent messages are queued. Exit now?"),
1342                                GTK_STOCK_CANCEL, GTK_STOCK_OK, NULL)
1343                     != G_ALERTALTERNATE) {
1344                         main_window_popup(mainwin);
1345                         sc_exiting = FALSE;
1346                         return;
1347                 }
1348                 manage_window_focus_in(mainwin->window, NULL, NULL);
1349         }
1350
1351         sock_cleanup();
1352 #ifdef HAVE_VALGRIND
1353         if (RUNNING_ON_VALGRIND) {
1354                 summary_clear_list(mainwin->summaryview);
1355         }
1356 #endif
1357         if (folderview_get_selected_item(mainwin->folderview))
1358                 folder_item_close(folderview_get_selected_item(mainwin->folderview));
1359         gtk_main_quit();
1360 }
1361
1362 gboolean claws_is_exiting(void)
1363 {
1364         return sc_exiting;
1365 }
1366
1367 gboolean claws_is_starting(void)
1368 {
1369         return sc_starting;
1370 }
1371
1372 /*
1373  * CLAWS: want this public so crash dialog can delete the
1374  * lock file too
1375  */
1376 gchar *claws_get_socket_name(void)
1377 {
1378         static gchar *filename = NULL;
1379
1380         if (filename == NULL) {
1381                 filename = g_strdup_printf("%s%cclaws-mail-%d",
1382                                            g_get_tmp_dir(), G_DIR_SEPARATOR,
1383 #if HAVE_GETUID
1384                                            getuid());
1385 #else
1386                                            0);                                          
1387 #endif
1388         }
1389
1390         return filename;
1391 }
1392
1393 static gchar *get_crashfile_name(void)
1394 {
1395         static gchar *filename = NULL;
1396
1397         if (filename == NULL) {
1398                 filename = g_strdup_printf("%s%cclaws-crashed",
1399                                            get_tmp_dir(), G_DIR_SEPARATOR);
1400         }
1401
1402         return filename;
1403 }
1404
1405 static gint prohibit_duplicate_launch(void)
1406 {
1407         gint uxsock;
1408         gchar *path;
1409
1410         path = claws_get_socket_name();
1411         uxsock = fd_connect_unix(path);
1412         
1413         if (x_display == NULL)
1414                 x_display = g_strdup(g_getenv("DISPLAY"));
1415
1416         if (uxsock < 0) {
1417                 g_unlink(path);
1418                 return fd_open_unix(path);
1419         }
1420
1421         /* remote command mode */
1422
1423         debug_print("another Claws Mail instance is already running.\n");
1424
1425         if (cmd.receive_all) {
1426                 fd_write_all(uxsock, "receive_all\n", 12);
1427         } else if (cmd.receive) {
1428                 fd_write_all(uxsock, "receive\n", 8);
1429         } else if (cmd.compose && cmd.attach_files) {
1430                 gchar *str, *compose_str;
1431                 gint i;
1432
1433                 if (cmd.compose_mailto) {
1434                         compose_str = g_strdup_printf("compose_attach %s\n",
1435                                                       cmd.compose_mailto);
1436                 } else {
1437                         compose_str = g_strdup("compose_attach\n");
1438                 }
1439
1440                 fd_write_all(uxsock, compose_str, strlen(compose_str));
1441                 g_free(compose_str);
1442
1443                 for (i = 0; i < cmd.attach_files->len; i++) {
1444                         str = g_ptr_array_index(cmd.attach_files, i);
1445                         fd_write_all(uxsock, str, strlen(str));
1446                         fd_write_all(uxsock, "\n", 1);
1447                 }
1448
1449                 fd_write_all(uxsock, ".\n", 2);
1450         } else if (cmd.compose) {
1451                 gchar *compose_str;
1452
1453                 if (cmd.compose_mailto) {
1454                         compose_str = g_strdup_printf
1455                                 ("compose %s\n", cmd.compose_mailto);
1456                 } else {
1457                         compose_str = g_strdup("compose\n");
1458                 }
1459
1460                 fd_write_all(uxsock, compose_str, strlen(compose_str));
1461                 g_free(compose_str);
1462         } else if (cmd.subscribe) {
1463                 gchar *str = g_strdup_printf("subscribe %s\n", cmd.subscribe_uri);
1464                 fd_write_all(uxsock, str, strlen(str));
1465                 g_free(str);
1466         } else if (cmd.send) {
1467                 fd_write_all(uxsock, "send\n", 5);
1468         } else if (cmd.online_mode == ONLINE_MODE_ONLINE) {
1469                 fd_write(uxsock, "online\n", 6);
1470         } else if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
1471                 fd_write(uxsock, "offline\n", 7);
1472         } else if (cmd.status || cmd.status_full) {
1473                 gchar buf[BUFFSIZE];
1474                 gint i;
1475                 const gchar *command;
1476                 GPtrArray *folders;
1477                 gchar *folder;
1478  
1479                 command = cmd.status_full ? "status-full\n" : "status\n";
1480                 folders = cmd.status_full ? cmd.status_full_folders :
1481                         cmd.status_folders;
1482  
1483                 fd_write_all(uxsock, command, strlen(command));
1484                 for (i = 0; folders && i < folders->len; ++i) {
1485                         folder = g_ptr_array_index(folders, i);
1486                         fd_write_all(uxsock, folder, strlen(folder));
1487                         fd_write_all(uxsock, "\n", 1);
1488                 }
1489                 fd_write_all(uxsock, ".\n", 2);
1490                 for (;;) {
1491                         fd_gets(uxsock, buf, sizeof(buf));
1492                         if (!strncmp(buf, ".\n", 2)) break;
1493                         fputs(buf, stdout);
1494                 }
1495         } else if (cmd.exit) {
1496                 fd_write_all(uxsock, "exit\n", 5);
1497         } else if (cmd.target) {
1498                 gchar *str = g_strdup_printf("select %s\n", cmd.target);
1499                 fd_write_all(uxsock, str, strlen(str));
1500                 g_free(str);
1501         } else {
1502                 gchar buf[BUFSIZ];
1503                 fd_write_all(uxsock, "get_display\n", 12);
1504                 memset(buf, 0, sizeof(buf));
1505                 fd_gets(uxsock, buf, sizeof(buf));
1506                 if (strcmp2(buf, x_display)) {
1507                         printf("Claws Mail is already running on display %s.\n",
1508                                 buf);
1509                 } else {
1510                         fd_close(uxsock);
1511                         uxsock = fd_connect_unix(path);
1512                         fd_write_all(uxsock, "popup\n", 6);
1513                 }
1514         }
1515
1516         fd_close(uxsock);
1517         return -1;
1518 }
1519
1520 static gint lock_socket_remove(void)
1521 {
1522 #ifdef G_OS_UNIX
1523         gchar *filename;
1524
1525         if (lock_socket < 0) {
1526                 return -1;
1527         }
1528
1529         if (lock_socket_tag > 0) {
1530                 gdk_input_remove(lock_socket_tag);
1531         }
1532         fd_close(lock_socket);
1533         filename = claws_get_socket_name();
1534         g_unlink(filename);
1535 #endif
1536
1537         return 0;
1538 }
1539
1540 static GPtrArray *get_folder_item_list(gint sock)
1541 {
1542         gchar buf[BUFFSIZE];
1543         FolderItem *item;
1544         GPtrArray *folders = NULL;
1545
1546         for (;;) {
1547                 fd_gets(sock, buf, sizeof(buf));
1548                 if (!strncmp(buf, ".\n", 2)) {
1549                         break;
1550                 }
1551                 strretchomp(buf);
1552                 if (!folders) {
1553                         folders = g_ptr_array_new();
1554                 }
1555                 item = folder_find_item_from_identifier(buf);
1556                 if (item) {
1557                         g_ptr_array_add(folders, item);
1558                 } else {
1559                         g_warning("no such folder: %s\n", buf);
1560                 }
1561         }
1562
1563         return folders;
1564 }
1565
1566 static void lock_socket_input_cb(gpointer data,
1567                                  gint source,
1568                                  GdkInputCondition condition)
1569 {
1570         MainWindow *mainwin = (MainWindow *)data;
1571         gint sock;
1572         gchar buf[BUFFSIZE];
1573
1574         sock = fd_accept(source);
1575         fd_gets(sock, buf, sizeof(buf));
1576
1577         if (!strncmp(buf, "popup", 5)) {
1578                 main_window_popup(mainwin);
1579         } else if (!strncmp(buf, "get_display", 11)) {
1580                 fd_write_all(sock, x_display, strlen(x_display));
1581         } else if (!strncmp(buf, "receive_all", 11)) {
1582                 inc_all_account_mail(mainwin, FALSE,
1583                                      prefs_common.newmail_notify_manu);
1584         } else if (!strncmp(buf, "receive", 7)) {
1585                 inc_mail(mainwin, prefs_common.newmail_notify_manu);
1586         } else if (!strncmp(buf, "compose_attach", 14)) {
1587                 GPtrArray *files;
1588                 gchar *mailto;
1589
1590                 mailto = g_strdup(buf + strlen("compose_attach") + 1);
1591                 files = g_ptr_array_new();
1592                 while (fd_gets(sock, buf, sizeof(buf)) > 0) {
1593                         if (buf[0] == '.' && buf[1] == '\n') {
1594                                 break;
1595                         }
1596                         strretchomp(buf);
1597                         g_ptr_array_add(files, g_strdup(buf));
1598                 }
1599                 open_compose_new(mailto, files);
1600                 ptr_array_free_strings(files);
1601                 g_ptr_array_free(files, TRUE);
1602                 g_free(mailto);
1603         } else if (!strncmp(buf, "compose", 7)) {
1604                 open_compose_new(buf + strlen("compose") + 1, NULL);
1605         } else if (!strncmp(buf, "subscribe", 9)) {
1606                 main_window_popup(mainwin);
1607                 folder_subscribe(buf + strlen("subscribe") + 1);
1608         } else if (!strncmp(buf, "send", 4)) {
1609                 send_queue();
1610         } else if (!strncmp(buf, "online", 6)) {
1611                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
1612         } else if (!strncmp(buf, "offline", 7)) {
1613                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
1614         } else if (!strncmp(buf, "status-full", 11) ||
1615                    !strncmp(buf, "status", 6)) {
1616                 gchar *status;
1617                 GPtrArray *folders;
1618  
1619                 folders = get_folder_item_list(sock);
1620                 status = folder_get_status
1621                         (folders, !strncmp(buf, "status-full", 11));
1622                 fd_write_all(sock, status, strlen(status));
1623                 fd_write_all(sock, ".\n", 2);
1624                 g_free(status);
1625                 if (folders) g_ptr_array_free(folders, TRUE);
1626         } else if (!strncmp(buf, "select ", 7)) {
1627                 const gchar *target = buf+7;
1628                 mainwindow_jump_to(target);
1629         } else if (!strncmp(buf, "exit", 4)) {
1630                 app_will_exit(NULL, mainwin);
1631         }
1632
1633         fd_close(sock);
1634 }
1635
1636 static void open_compose_new(const gchar *address, GPtrArray *attach_files)
1637 {
1638         gchar *addr = NULL;
1639
1640         if (address) {
1641                 Xstrdup_a(addr, address, return);
1642                 g_strstrip(addr);
1643         }
1644
1645         compose_new(NULL, addr, attach_files);
1646 }
1647
1648 static void send_queue(void)
1649 {
1650         GList *list;
1651         gchar *errstr = NULL;
1652         for (list = folder_get_list(); list != NULL; list = list->next) {
1653                 Folder *folder = list->data;
1654
1655                 if (folder->queue) {
1656                         gint res = procmsg_send_queue
1657                                 (folder->queue, prefs_common.savemsg,
1658                                 &errstr);
1659
1660                         if (res) {
1661                                 folder_item_scan(folder->queue);
1662                         }
1663                 }
1664         }
1665         if (errstr) {
1666                 gchar *tmp = g_strdup_printf(_("Some errors occurred "
1667                                 "while sending queued messages:\n%s"), errstr);
1668                 g_free(errstr);
1669                 alertpanel_error_log(tmp);
1670                 g_free(tmp);
1671         } else {
1672                 alertpanel_error_log("Some errors occurred "
1673                                 "while sending queued messages.");
1674         }
1675 }
1676
1677 static void quit_signal_handler(int sig)
1678 {
1679         debug_print("Quitting on signal %d\n", sig);
1680
1681         g_timeout_add(0, clean_quit, NULL);
1682 }
1683
1684 static void install_basic_sighandlers()
1685 {
1686 #ifndef G_OS_WIN32
1687         sigset_t    mask;
1688         struct sigaction act;
1689
1690         sigemptyset(&mask);
1691
1692 #ifdef SIGTERM
1693         sigaddset(&mask, SIGTERM);
1694 #endif
1695 #ifdef SIGINT
1696         sigaddset(&mask, SIGINT);
1697 #endif
1698 #ifdef SIGHUP
1699         sigaddset(&mask, SIGHUP);
1700 #endif
1701
1702         act.sa_handler = quit_signal_handler;
1703         act.sa_mask    = mask;
1704         act.sa_flags   = 0;
1705
1706 #ifdef SIGTERM
1707         sigaction(SIGTERM, &act, 0);
1708 #endif
1709 #ifdef SIGINT
1710         sigaction(SIGINT, &act, 0);
1711 #endif  
1712 #ifdef SIGHUP
1713         sigaction(SIGHUP, &act, 0);
1714 #endif  
1715
1716         sigprocmask(SIG_UNBLOCK, &mask, 0);
1717 #endif /* !G_OS_WIN32 */
1718 }