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