2007-01-18 [colin] 2.7.1cvs31
[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 gchar *get_socket_name          (void);
162
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 void claws_gtk_idle(void) 
236 {
237         while(gtk_events_pending()) {
238                 gtk_main_iteration();
239         }
240         g_usleep(50000);
241 }
242
243 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 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
555 int main(int argc, char *argv[])
556 {
557         gchar *userrc;
558         MainWindow *mainwin;
559         FolderView *folderview;
560         GdkPixbuf *icon;
561         gboolean crash_file_present = FALSE;
562         gint num_folder_class = 0;
563         gboolean asked_for_migration = FALSE;
564
565         START_TIMING("startup");
566         
567         sc_starting = TRUE;
568
569         if (!claws_init(&argc, &argv)) {
570                 return 0;
571         }
572
573         prefs_prepare_cache();
574         prog_version = PROG_VERSION;
575         argv0 = g_strdup(argv[0]);
576
577         parse_cmd_opt(argc, argv);
578
579 #ifdef CRASH_DIALOG
580         if (cmd.crash) {
581                 gtk_set_locale();
582                 gtk_init(&argc, &argv);
583                 crash_main(cmd.crash_params);
584                 return 0;
585         }
586         crash_install_handlers();
587 #endif
588         install_basic_sighandlers();
589         sock_init();
590
591         /* check and create unix domain socket for remote operation */
592 #ifdef G_OS_UNIX
593         lock_socket = prohibit_duplicate_launch();
594         if (lock_socket < 0) {
595 #ifdef HAVE_STARTUP_NOTIFICATION
596                 if(gtk_init_check(&argc, &argv))
597                         startup_notification_complete(TRUE);
598 #endif
599                 return 0;
600         }
601
602         if (cmd.status || cmd.status_full) {
603                 puts("0 Claws Mail not running.");
604                 lock_socket_remove();
605                 return 0;
606         }
607         
608         if (cmd.exit)
609                 return 0;
610 #endif
611         if (!g_thread_supported())
612                 g_thread_init(NULL);
613
614         gtk_set_locale();
615         gtk_init(&argc, &argv);
616
617         gdk_rgb_init();
618         gtk_widget_set_default_colormap(gdk_rgb_get_colormap());
619         gtk_widget_set_default_visual(gdk_rgb_get_visual());
620
621         if (!g_thread_supported()) {
622                 g_error(_("g_thread is not supported by glib.\n"));
623         }
624
625         /* check that we're not on a too recent/old gtk+ */
626 #if GTK_CHECK_VERSION(2, 9, 0)
627         if (gtk_check_version(2, 9, 0) != NULL) {
628                 alertpanel_error(_("Claws Mail has been compiled with "
629                                    "a more recent GTK+ library than is "
630                                    "currently available. This will cause "
631                                    "crashes. You need to upgrade GTK+ or "
632                                    "recompile Claws Mail."));
633                 exit(1);
634         }
635 #else
636         if (gtk_check_version(2, 9, 0) == NULL) {
637                 alertpanel_error(_("Claws Mail has been compiled with "
638                                    "an older GTK+ library than is "
639                                    "currently available. This will cause "
640                                    "crashes. You need to recompile "
641                                    "Claws Mail."));
642                 exit(1);
643         }
644 #endif  
645         /* parse gtkrc files */
646         userrc = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".gtkrc-2.0",
647                              NULL);
648         gtk_rc_parse(userrc);
649         g_free(userrc);
650         userrc = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".gtk",
651                              G_DIR_SEPARATOR_S, "gtkrc-2.0", NULL);
652         gtk_rc_parse(userrc);
653         g_free(userrc);
654
655         CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
656         
657         /* no config dir exists. See if we can migrate an old config. */
658         if (!is_dir_exist(RC_DIR)) {
659                 prefs_destroy_cache();
660                 gboolean r = FALSE;
661                 
662                 /* if one of the old dirs exist, we'll ask if the user 
663                  * want to migrates, and r will be TRUE if he said yes
664                  * and migration succeeded, and FALSE otherwise.
665                  */
666                 if (is_dir_exist(OLD_GTK2_RC_DIR)) {
667                         r = migrate_old_config(OLD_GTK2_RC_DIR, RC_DIR, "Sylpheed-Claws 2.6.0");
668                         asked_for_migration = TRUE;
669                 } else if (is_dir_exist(OLDER_GTK2_RC_DIR)) {
670                         r = migrate_old_config(OLDER_GTK2_RC_DIR, RC_DIR, "Sylpheed-Claws 1.9.15");
671                         asked_for_migration = TRUE;
672                 } else if (is_dir_exist(OLD_GTK1_RC_DIR)) {
673                         r = migrate_old_config(OLD_GTK1_RC_DIR, RC_DIR, "Sylpheed-Claws 1.0.5");
674                         asked_for_migration = TRUE;
675                 }
676                 
677                 /* If migration failed or the user didn't want to do it,
678                  * we create a new one (and we'll hit wizard later). 
679                  */
680                 if (r == FALSE && !is_dir_exist(RC_DIR) && make_dir(RC_DIR) < 0)
681                         exit(1);
682         }
683         
684
685         if (!is_file_exist(RC_DIR G_DIR_SEPARATOR_S COMMON_RC) &&
686             is_file_exist(RC_DIR G_DIR_SEPARATOR_S OLD_COMMON_RC)) {
687                 /* post 2.6 name change */
688                 migrate_common_rc(RC_DIR G_DIR_SEPARATOR_S OLD_COMMON_RC,
689                           RC_DIR G_DIR_SEPARATOR_S COMMON_RC);
690         }
691
692         if (!cmd.exit)
693                 plugin_load_all("Common");
694
695         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, "gtkrc-2.0", NULL);
696         gtk_rc_parse(userrc);
697         g_free(userrc);
698
699         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
700         gtk_accel_map_load (userrc);
701         g_free(userrc);
702
703         CHDIR_RETURN_VAL_IF_FAIL(get_rc_dir(), 1);
704
705         MAKE_DIR_IF_NOT_EXIST(get_mail_base_dir());
706         MAKE_DIR_IF_NOT_EXIST(get_imap_cache_dir());
707         MAKE_DIR_IF_NOT_EXIST(get_news_cache_dir());
708         MAKE_DIR_IF_NOT_EXIST(get_mime_tmp_dir());
709         MAKE_DIR_IF_NOT_EXIST(get_tmp_dir());
710         MAKE_DIR_IF_NOT_EXIST(UIDL_DIR);
711
712         crash_file_present = is_file_exist(get_crashfile_name());
713         /* remove temporary files */
714         remove_all_files(get_tmp_dir());
715         remove_all_files(get_mime_tmp_dir());
716
717         if (is_file_exist("claws.log")) {
718                 if (rename_force("claws.log", "claws.log.bak") < 0)
719                         FILE_OP_ERROR("claws.log", "rename");
720         }
721         set_log_file("claws.log");
722
723         CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
724
725         folder_system_init();
726         prefs_common_read_config();
727
728         prefs_themes_init();
729         prefs_fonts_init();
730         prefs_ext_prog_init();
731         prefs_wrapping_init();
732         prefs_compose_writing_init();
733         prefs_msg_colors_init();
734         image_viewer_init();
735         prefs_image_viewer_init();
736         prefs_quote_init();
737         prefs_summaries_init();
738         prefs_message_init();
739         prefs_other_init();
740         prefs_receive_init();
741         prefs_send_init();
742 #ifdef USE_ASPELL
743         gtkaspell_checkers_init();
744         prefs_spelling_init();
745 #endif
746
747         sock_set_io_timeout(prefs_common.io_timeout_secs);
748 #ifdef HAVE_LIBETPAN
749         imap_main_set_timeout(prefs_common.io_timeout_secs);
750 #endif
751         prefs_actions_read_config();
752         prefs_display_header_read_config();
753         /* prefs_filtering_read_config(); */
754         addressbook_read_file();
755         renderer_read_config();
756
757         gtkut_widget_init();
758         stock_pixbuf_gdk(NULL, STOCK_PIXMAP_CLAWS_MAIL_ICON, &icon);
759         gtk_window_set_default_icon(icon);
760
761         folderview_initialize();
762
763         mh_gtk_init();
764         imap_gtk_init();
765         news_gtk_init();
766
767         mainwin = main_window_create
768                 (prefs_common.sep_folder | prefs_common.sep_msg << 1);
769
770         manage_window_focus_in(mainwin->window, NULL, NULL);
771         folderview = mainwin->folderview;
772
773         gtk_clist_freeze(GTK_CLIST(mainwin->folderview->ctree));
774         folder_item_update_freeze();
775
776         /* register the callback of unix domain socket input */
777 #ifdef G_OS_UNIX
778         lock_socket_tag = gdk_input_add(lock_socket,
779                                         GDK_INPUT_READ | GDK_INPUT_EXCEPTION,
780                                         lock_socket_input_cb,
781                                         mainwin);
782 #endif
783
784         prefs_account_init();
785         account_read_config_all();
786
787         /* If we can't read a folder list or don't have accounts,
788          * it means the configuration's not done. Either this is
789          * a brand new install, either a failed/refused migration.
790          * So we'll start the wizard.
791          */
792         if (folder_read_list() < 0) {
793                 prefs_destroy_cache();
794                 
795                 /* if run_wizard returns FALSE it's because it's
796                  * been cancelled. We can't do much but exit.
797                  * however, if the user was asked for a migration,
798                  * we remove the newly created directory so that
799                  * he's asked again for migration on next launch.*/
800                 if (!run_wizard(mainwin, TRUE)) {
801                         if (asked_for_migration)
802                                 remove_dir_recursive(RC_DIR);
803                         exit(1);
804                 }
805                 main_window_reflect_prefs_all_now();
806                 folder_write_list();
807         }
808
809         if (!account_get_list()) {
810                 prefs_destroy_cache();
811                 if (!run_wizard(mainwin, FALSE)) {
812                         if (asked_for_migration)
813                                 remove_dir_recursive(RC_DIR);
814                         exit(1);
815                 }
816                 account_read_config_all();
817                 if(!account_get_list()) {
818                         exit_claws(mainwin);
819                         exit(1);
820                 }
821         }
822
823         
824         toolbar_main_set_sensitive(mainwin);
825         main_window_set_menu_sensitive(mainwin);
826
827         main_window_popup(mainwin);
828
829 #ifdef HAVE_LIBETPAN
830         imap_main_init(prefs_common.skip_ssl_cert_check);
831 #endif  
832         account_set_missing_folder();
833         folder_set_missing_folders();
834         folderview_set(folderview);
835
836         prefs_matcher_read_config();
837
838         /* make one all-folder processing before using claws */
839         main_window_cursor_wait(mainwin);
840         folder_func_to_all_folders(initial_processing, (gpointer *)mainwin);
841
842         /* if claws crashed, rebuild caches */
843         if (!cmd.crash && crash_file_present) {
844                 GTK_EVENTS_FLUSH();
845                 debug_print("Claws Mail crashed, checking for new messages in local folders\n");
846                 folder_item_update_thaw();
847                 folderview_check_new(NULL);
848                 folder_clean_cache_memory_force();
849                 folder_item_update_freeze();
850         }
851         /* make the crash-indicator file */
852         str_write_to_file("foo", get_crashfile_name());
853
854         inc_autocheck_timer_init(mainwin);
855
856         /* ignore SIGPIPE signal for preventing sudden death of program */
857 #ifdef G_OS_UNIX
858         signal(SIGPIPE, SIG_IGN);
859 #endif
860         if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
861                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
862         }
863         if (cmd.online_mode == ONLINE_MODE_ONLINE) {
864                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
865         }
866
867         if (cmd.status_folders) {
868                 g_ptr_array_free(cmd.status_folders, TRUE);
869                 cmd.status_folders = NULL;
870         }
871         if (cmd.status_full_folders) {
872                 g_ptr_array_free(cmd.status_full_folders, TRUE);
873                 cmd.status_full_folders = NULL;
874         }
875
876         claws_register_idle_function(claws_gtk_idle);
877
878         prefs_toolbar_init();
879
880         num_folder_class = g_list_length(folder_get_list());
881
882         plugin_load_all("GTK2");
883
884         if (g_list_length(folder_get_list()) != num_folder_class) {
885                 debug_print("new folders loaded, reloading processing rules\n");
886                 prefs_matcher_read_config();
887         }
888         
889         if (plugin_get_unloaded_list() != NULL) {
890                 main_window_cursor_normal(mainwin);
891                 alertpanel_warning(_("Some plugin(s) failed to load. "
892                                      "Check the Plugins configuration "
893                                      "for more information."));
894                 main_window_cursor_wait(mainwin);
895         }
896
897         plugin_load_standard_plugins ();
898        
899         if (!folder_have_mailbox()) {
900                 prefs_destroy_cache();
901                 main_window_cursor_normal(mainwin);
902                 if (folder_get_list() != NULL) {
903                         alertpanel_error(_("Claws Mail has detected a configured "
904                                    "mailbox, but is it incomplete. It is "
905                                    "possibly due to a failing IMAP account. Use "
906                                    "\"Rebuild folder tree\" on the mailbox's folder "
907                                    "to try to fix it."));
908                 } else {
909                         alertpanel_error(_("Claws Mail has detected a configured "
910                                    "mailbox, but could not load it. It is "
911                                    "probably provided by an out-of-date "
912                                    "external plugin. Please reinstall the "
913                                    "plugin and try again."));
914                         exit_claws(mainwin);
915                         exit(1);
916                 }
917         }
918         
919         static_mainwindow = mainwin;
920
921 #ifdef HAVE_STARTUP_NOTIFICATION
922         startup_notification_complete(FALSE);
923 #endif
924 #ifdef HAVE_LIBSM
925         sc_session_manager_connect(mainwin);
926 #endif
927         folder_item_update_thaw();
928         gtk_clist_thaw(GTK_CLIST(mainwin->folderview->ctree));
929         main_window_cursor_normal(mainwin);
930
931         if (cmd.receive_all) {
932                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(FALSE));
933         } else if (prefs_common.chk_on_startup) {
934                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(TRUE));
935         } else if (cmd.receive) {
936                 g_timeout_add(1000, defer_check, NULL);
937         } else {
938                 gtk_widget_grab_focus(folderview->ctree);
939         }
940
941         if (cmd.compose) {
942                 open_compose_new(cmd.compose_mailto, cmd.attach_files);
943         }
944         if (cmd.attach_files) {
945                 ptr_array_free_strings(cmd.attach_files);
946                 g_ptr_array_free(cmd.attach_files, TRUE);
947                 cmd.attach_files = NULL;
948         }
949         if (cmd.subscribe) {
950                 folder_subscribe(cmd.subscribe_uri);
951         }
952
953         if (cmd.send) {
954                 send_queue();
955         }
956         
957         if (cmd.target) {
958                 g_timeout_add(500, defer_jump, (gpointer)cmd.target);
959         }
960
961         prefs_destroy_cache();
962         
963         sc_starting = FALSE;
964         END_TIMING();
965         
966         gtk_main();
967
968         exit_claws(mainwin);
969
970         return 0;
971 }
972
973 static void save_all_caches(FolderItem *item, gpointer data)
974 {
975         if (!item->cache) {
976                 return;
977         }
978
979         if (item->opened)
980                 folder_item_close(item);
981         
982         folder_item_free_cache(item, TRUE);
983 }
984
985 static void exit_claws(MainWindow *mainwin)
986 {
987         gchar *filename;
988
989         sc_exiting = TRUE;
990
991         debug_print("shutting down\n");
992         inc_autocheck_timer_remove();
993
994         if (prefs_common.clean_on_exit && !emergency_exit) {
995                 main_window_empty_trash(mainwin, prefs_common.ask_on_clean);
996         }
997
998         /* save prefs for opened folder */
999         if(mainwin->folderview->opened) {
1000                 FolderItem *item;
1001
1002                 item = gtk_ctree_node_get_row_data(GTK_CTREE(mainwin->folderview->ctree), mainwin->folderview->opened);
1003                 summary_save_prefs_to_folderitem(mainwin->folderview->summaryview, item);
1004         }
1005
1006         /* save all state before exiting */
1007         folder_func_to_all_folders(save_all_caches, NULL);
1008         folder_write_list();
1009
1010         main_window_get_size(mainwin);
1011         main_window_get_position(mainwin);
1012         prefs_common_write_config();
1013         account_write_config_all();
1014         addressbook_export_to_file();
1015
1016         filename = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
1017         gtk_accel_map_save(filename);
1018         g_free(filename);
1019
1020         /* delete temporary files */
1021         remove_all_files(get_tmp_dir());
1022         remove_all_files(get_mime_tmp_dir());
1023
1024         close_log_file();
1025
1026 #ifdef HAVE_LIBETPAN
1027         imap_main_done();
1028 #endif
1029         /* delete crashfile */
1030         if (!cmd.crash)
1031                 g_unlink(get_crashfile_name());
1032
1033         lock_socket_remove();
1034
1035 #ifdef HAVE_LIBSM
1036         if (mainwin->smc_conn)
1037                 SmcCloseConnection ((SmcConn)mainwin->smc_conn, 0, NULL);
1038         mainwin->smc_conn = NULL;
1039 #endif
1040
1041         main_window_destroy_all();
1042         
1043         plugin_unload_all("GTK2");
1044
1045         prefs_toolbar_done();
1046
1047         addressbook_destroy();
1048
1049         prefs_themes_done();
1050         prefs_fonts_done();
1051         prefs_ext_prog_done();
1052         prefs_wrapping_done();
1053         prefs_compose_writing_done();
1054         prefs_msg_colors_done();
1055         prefs_image_viewer_done();
1056         image_viewer_done();
1057         prefs_quote_done();
1058         prefs_summaries_done();
1059         prefs_message_done();
1060         prefs_other_done();
1061         prefs_receive_done();
1062         prefs_send_done();
1063 #ifdef USE_ASPELL       
1064         prefs_spelling_done();
1065         gtkaspell_checkers_quit();
1066 #endif
1067         plugin_unload_all("Common");
1068         claws_done();
1069 }
1070
1071 static void parse_cmd_opt(int argc, char *argv[])
1072 {
1073         gint i;
1074
1075         for (i = 1; i < argc; i++) {
1076                 if (!strncmp(argv[i], "--receive-all", 13)) {
1077                         cmd.receive_all = TRUE;
1078                 } else if (!strncmp(argv[i], "--receive", 9)) {
1079                         cmd.receive = TRUE;
1080                 } else if (!strncmp(argv[i], "--compose", 9)) {
1081                         const gchar *p = argv[i + 1];
1082
1083                         cmd.compose = TRUE;
1084                         cmd.compose_mailto = NULL;
1085                         if (p && *p != '\0' && *p != '-') {
1086                                 if (!strncmp(p, "mailto:", 7)) {
1087                                         cmd.compose_mailto = p + 7;
1088                                 } else {
1089                                         cmd.compose_mailto = p;
1090                                 }
1091                                 i++;
1092                         }
1093                 } else if (!strncmp(argv[i], "--subscribe", 11)) {
1094                         const gchar *p = argv[i + 1];
1095                         if (p && *p != '\0' && *p != '-') {
1096                                 cmd.subscribe = TRUE;
1097                                 cmd.subscribe_uri = p;
1098                         }
1099                 } else if (!strncmp(argv[i], "--attach", 8)) {
1100                         const gchar *p = argv[i + 1];
1101                         gchar *file;
1102
1103                         while (p && *p != '\0' && *p != '-') {
1104                                 if (!cmd.attach_files) {
1105                                         cmd.attach_files = g_ptr_array_new();
1106                                 }
1107                                 if (*p != G_DIR_SEPARATOR) {
1108                                         file = g_strconcat(claws_get_startup_dir(),
1109                                                            G_DIR_SEPARATOR_S,
1110                                                            p, NULL);
1111                                 } else {
1112                                         file = g_strdup(p);
1113                                 }
1114                                 g_ptr_array_add(cmd.attach_files, file);
1115                                 i++;
1116                                 p = argv[i + 1];
1117                         }
1118                 } else if (!strncmp(argv[i], "--send", 6)) {
1119                         cmd.send = TRUE;
1120                 } else if (!strncmp(argv[i], "--version", 9) ||
1121                            !strncmp(argv[i], "-v", 2)) {
1122                         puts("Claws Mail version " VERSION);
1123                         exit(0);
1124                 } else if (!strncmp(argv[i], "--status-full", 13)) {
1125                         const gchar *p = argv[i + 1];
1126  
1127                         cmd.status_full = TRUE;
1128                         while (p && *p != '\0' && *p != '-') {
1129                                 if (!cmd.status_full_folders) {
1130                                         cmd.status_full_folders =
1131                                                 g_ptr_array_new();
1132                                 }
1133                                 g_ptr_array_add(cmd.status_full_folders,
1134                                                 g_strdup(p));
1135                                 i++;
1136                                 p = argv[i + 1];
1137                         }
1138                 } else if (!strncmp(argv[i], "--status", 8)) {
1139                         const gchar *p = argv[i + 1];
1140  
1141                         cmd.status = TRUE;
1142                         while (p && *p != '\0' && *p != '-') {
1143                                 if (!cmd.status_folders)
1144                                         cmd.status_folders = g_ptr_array_new();
1145                                 g_ptr_array_add(cmd.status_folders,
1146                                                 g_strdup(p));
1147                                 i++;
1148                                 p = argv[i + 1];
1149                         }
1150                 } else if (!strncmp(argv[i], "--online", 8)) {
1151                         cmd.online_mode = ONLINE_MODE_ONLINE;
1152                 } else if (!strncmp(argv[i], "--offline", 9)) {
1153                         cmd.online_mode = ONLINE_MODE_OFFLINE;
1154                 } else if (!strncmp(argv[i], "--help", 6) ||
1155                            !strncmp(argv[i], "-h", 2)) {
1156                         gchar *base = g_path_get_basename(argv[0]);
1157                         g_print(_("Usage: %s [OPTION]...\n"), base);
1158
1159                         g_print("%s\n", _("  --compose [address]    open composition window"));
1160                         g_print("%s\n", _("  --subscribe [uri]      subscribe to the given URI if possible"));
1161                         g_print("%s\n", _("  --attach file1 [file2]...\n"
1162                                   "                         open composition window with specified files\n"
1163                                   "                         attached"));
1164                         g_print("%s\n", _("  --receive              receive new messages"));
1165                         g_print("%s\n", _("  --receive-all          receive new messages of all accounts"));
1166                         g_print("%s\n", _("  --send                 send all queued messages"));
1167                         g_print("%s\n", _("  --status [folder]...   show the total number of messages"));
1168                         g_print("%s\n", _("  --status-full [folder]...\n"
1169                                "                         show the status of each folder"));
1170                         g_print("%s\n", _("  --select folder[/msg]  jumps to the specified folder/message\n" 
1171                                           "                         folder is a folder id like 'folder/sub_folder'"));
1172                         g_print("%s\n", _("  --online               switch to online mode"));
1173                         g_print("%s\n", _("  --offline              switch to offline mode"));
1174                         g_print("%s\n", _("  --exit --quit -q       exit Claws Mail"));
1175                         g_print("%s\n", _("  --debug                debug mode"));
1176                         g_print("%s\n", _("  --help -h              display this help and exit"));
1177                         g_print("%s\n", _("  --version -v           output version information and exit"));
1178                         g_print("%s\n", _("  --config-dir           output configuration directory"));
1179
1180                         g_free(base);
1181                         exit(1);
1182                 } else if (!strncmp(argv[i], "--crash", 7)) {
1183                         cmd.crash = TRUE;
1184                         cmd.crash_params = g_strdup(argv[i + 1]);
1185                         i++;
1186                 } else if (!strncmp(argv[i], "--config-dir", sizeof "--config-dir" - 1)) {
1187                         puts(RC_DIR);
1188                         exit(0);
1189                 } else if (!strncmp(argv[i], "--exit", 6) ||
1190                            !strncmp(argv[i], "--quit", 6) ||
1191                            !strncmp(argv[i], "-q", 2)) {
1192                         cmd.exit = TRUE;
1193                 } else if (!strncmp(argv[i], "--select", 8) && i+1 < argc) {
1194                         cmd.target = argv[i+1];
1195                 } else if (i == 1 && argc == 2) {
1196                         /* only one parameter. Do something intelligent about it */
1197                         if (strstr(argv[i], "@") && !strstr(argv[i], "://")) {
1198                                 const gchar *p = argv[i];
1199
1200                                 cmd.compose = TRUE;
1201                                 cmd.compose_mailto = NULL;
1202                                 if (p && *p != '\0' && *p != '-') {
1203                                         if (!strncmp(p, "mailto:", 7)) {
1204                                                 cmd.compose_mailto = p + 7;
1205                                         } else {
1206                                                 cmd.compose_mailto = p;
1207                                         }
1208                                 }
1209                         } else if (strstr(argv[i], "://")) {
1210                                 const gchar *p = argv[i];
1211                                 if (p && *p != '\0' && *p != '-') {
1212                                         cmd.subscribe = TRUE;
1213                                         cmd.subscribe_uri = p;
1214                                 }
1215                         } else if (!strcmp(argv[i], "--sync")) {
1216                                 /* gtk debug */
1217                         } else {
1218                                 g_print(_("Unknown option\n"));
1219                                 exit(1);
1220                         }
1221                 }
1222         }
1223
1224         if (cmd.attach_files && cmd.compose == FALSE) {
1225                 cmd.compose = TRUE;
1226                 cmd.compose_mailto = NULL;
1227         }
1228 }
1229
1230 static gint get_queued_message_num(void)
1231 {
1232         FolderItem *queue;
1233
1234         queue = folder_get_default_queue();
1235         if (!queue) {
1236                 return -1;
1237         }
1238
1239         folder_item_scan(queue);
1240         return queue->total_msgs;
1241 }
1242
1243 static void initial_processing(FolderItem *item, gpointer data)
1244 {
1245         MainWindow *mainwin = (MainWindow *)data;
1246         gchar *buf;
1247
1248         g_return_if_fail(item);
1249         buf = g_strdup_printf(_("Processing (%s)..."), 
1250                               item->path 
1251                               ? item->path 
1252                               : _("top level folder"));
1253         g_free(buf);
1254
1255         
1256         if (item->prefs->enable_processing) {
1257                 folder_item_apply_processing(item);
1258         }
1259
1260         STATUSBAR_POP(mainwin);
1261 }
1262
1263 static void draft_all_messages(void)
1264 {
1265         GList *compose_list = NULL;
1266         
1267         while ((compose_list = compose_get_compose_list()) != NULL) {
1268                 Compose *c = (Compose*)compose_list->data;
1269                 compose_draft(c);
1270         }       
1271 }
1272 gboolean clean_quit(gpointer data)
1273 {
1274         static gboolean firstrun = TRUE;
1275
1276         if (!firstrun) {
1277                 return FALSE;
1278         }
1279         firstrun = FALSE;
1280
1281         /*!< Good idea to have the main window stored in a 
1282          *   static variable so we can check that variable
1283          *   to see if we're really allowed to do things
1284          *   that actually the spawner is supposed to 
1285          *   do (like: sending mail, composing messages).
1286          *   Because, really, if we're the spawnee, and
1287          *   we touch GTK stuff, we're hosed. See the 
1288          *   next fixme. */
1289
1290         /* FIXME: Use something else to signal that we're
1291          * in the original spawner, and not in a spawned
1292          * child. */
1293         if (!static_mainwindow) {
1294                 return FALSE;
1295         }
1296                 
1297         draft_all_messages();
1298         emergency_exit = TRUE;
1299         exit_claws(static_mainwindow);
1300         exit(0);
1301
1302         return FALSE;
1303 }
1304
1305 void app_will_exit(GtkWidget *widget, gpointer data)
1306 {
1307         MainWindow *mainwin = data;
1308         
1309         if (sc_exiting == TRUE) {
1310                 debug_print("exit pending\n");
1311                 return;
1312         }
1313         sc_exiting = TRUE;
1314         debug_print("exiting\n");
1315         if (compose_get_compose_list()) {
1316                 gint val = alertpanel(_("Really quit?"),
1317                                _("Composing message exists."),
1318                                _("_Save to Draft"), _("_Discard them"), _("Do_n't quit"));
1319                 switch (val) {
1320                         case G_ALERTOTHER:
1321                                 sc_exiting = FALSE;
1322                                 return;
1323                         case G_ALERTALTERNATE:
1324                                 break;
1325                         default:
1326                                 draft_all_messages();
1327                 }
1328
1329                 manage_window_focus_in(mainwin->window, NULL, NULL);
1330         }
1331
1332         if (prefs_common.warn_queued_on_exit && get_queued_message_num() > 0) {
1333                 if (alertpanel(_("Queued messages"),
1334                                _("Some unsent messages are queued. Exit now?"),
1335                                GTK_STOCK_CANCEL, GTK_STOCK_OK, NULL)
1336                     != G_ALERTALTERNATE) {
1337                         sc_exiting = FALSE;
1338                         return;
1339                 }
1340                 manage_window_focus_in(mainwin->window, NULL, NULL);
1341         }
1342
1343         sock_cleanup();
1344         if (folderview_get_selected_item(mainwin->folderview))
1345                 folder_item_close(folderview_get_selected_item(mainwin->folderview));
1346         gtk_main_quit();
1347 }
1348
1349 gboolean claws_is_exiting(void)
1350 {
1351         return sc_exiting;
1352 }
1353
1354 gboolean claws_is_starting(void)
1355 {
1356         return sc_starting;
1357 }
1358
1359 /*
1360  * CLAWS: want this public so crash dialog can delete the
1361  * lock file too
1362  */
1363 gchar *get_socket_name(void)
1364 {
1365         static gchar *filename = NULL;
1366
1367         if (filename == NULL) {
1368                 filename = g_strdup_printf("%s%cclaws-mail-%d",
1369                                            g_get_tmp_dir(), G_DIR_SEPARATOR,
1370 #if HAVE_GETUID
1371                                            getuid());
1372 #else
1373                                            0);                                          
1374 #endif
1375         }
1376
1377         return filename;
1378 }
1379
1380 static gchar *get_crashfile_name(void)
1381 {
1382         static gchar *filename = NULL;
1383
1384         if (filename == NULL) {
1385                 filename = g_strdup_printf("%s%cclaws-crashed",
1386                                            get_tmp_dir(), G_DIR_SEPARATOR);
1387         }
1388
1389         return filename;
1390 }
1391
1392 static gint prohibit_duplicate_launch(void)
1393 {
1394         gint uxsock;
1395         gchar *path;
1396
1397         path = get_socket_name();
1398         uxsock = fd_connect_unix(path);
1399         if (uxsock < 0) {
1400                 g_unlink(path);
1401                 return fd_open_unix(path);
1402         }
1403
1404         /* remote command mode */
1405
1406         debug_print("another Claws Mail instance is already running.\n");
1407
1408         if (cmd.receive_all) {
1409                 fd_write_all(uxsock, "receive_all\n", 12);
1410         } else if (cmd.receive) {
1411                 fd_write_all(uxsock, "receive\n", 8);
1412         } else if (cmd.compose && cmd.attach_files) {
1413                 gchar *str, *compose_str;
1414                 gint i;
1415
1416                 if (cmd.compose_mailto) {
1417                         compose_str = g_strdup_printf("compose_attach %s\n",
1418                                                       cmd.compose_mailto);
1419                 } else {
1420                         compose_str = g_strdup("compose_attach\n");
1421                 }
1422
1423                 fd_write_all(uxsock, compose_str, strlen(compose_str));
1424                 g_free(compose_str);
1425
1426                 for (i = 0; i < cmd.attach_files->len; i++) {
1427                         str = g_ptr_array_index(cmd.attach_files, i);
1428                         fd_write_all(uxsock, str, strlen(str));
1429                         fd_write_all(uxsock, "\n", 1);
1430                 }
1431
1432                 fd_write_all(uxsock, ".\n", 2);
1433         } else if (cmd.compose) {
1434                 gchar *compose_str;
1435
1436                 if (cmd.compose_mailto) {
1437                         compose_str = g_strdup_printf
1438                                 ("compose %s\n", cmd.compose_mailto);
1439                 } else {
1440                         compose_str = g_strdup("compose\n");
1441                 }
1442
1443                 fd_write_all(uxsock, compose_str, strlen(compose_str));
1444                 g_free(compose_str);
1445         } else if (cmd.subscribe) {
1446                 gchar *str = g_strdup_printf("subscribe %s\n", cmd.subscribe_uri);
1447                 fd_write_all(uxsock, str, strlen(str));
1448                 g_free(str);
1449         } else if (cmd.send) {
1450                 fd_write_all(uxsock, "send\n", 5);
1451         } else if (cmd.online_mode == ONLINE_MODE_ONLINE) {
1452                 fd_write(uxsock, "online\n", 6);
1453         } else if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
1454                 fd_write(uxsock, "offline\n", 7);
1455         } else if (cmd.status || cmd.status_full) {
1456                 gchar buf[BUFFSIZE];
1457                 gint i;
1458                 const gchar *command;
1459                 GPtrArray *folders;
1460                 gchar *folder;
1461  
1462                 command = cmd.status_full ? "status-full\n" : "status\n";
1463                 folders = cmd.status_full ? cmd.status_full_folders :
1464                         cmd.status_folders;
1465  
1466                 fd_write_all(uxsock, command, strlen(command));
1467                 for (i = 0; folders && i < folders->len; ++i) {
1468                         folder = g_ptr_array_index(folders, i);
1469                         fd_write_all(uxsock, folder, strlen(folder));
1470                         fd_write_all(uxsock, "\n", 1);
1471                 }
1472                 fd_write_all(uxsock, ".\n", 2);
1473                 for (;;) {
1474                         fd_gets(uxsock, buf, sizeof(buf));
1475                         if (!strncmp(buf, ".\n", 2)) break;
1476                         fputs(buf, stdout);
1477                 }
1478         } else if (cmd.exit) {
1479                 fd_write_all(uxsock, "exit\n", 5);
1480         } else if (cmd.target) {
1481                 gchar *str = g_strdup_printf("select %s\n", cmd.target);
1482                 fd_write_all(uxsock, str, strlen(str));
1483                 g_free(str);
1484         } else
1485                 fd_write_all(uxsock, "popup\n", 6);
1486
1487         fd_close(uxsock);
1488         return -1;
1489 }
1490
1491 static gint lock_socket_remove(void)
1492 {
1493 #ifdef G_OS_UNIX
1494         gchar *filename;
1495
1496         if (lock_socket < 0) {
1497                 return -1;
1498         }
1499
1500         if (lock_socket_tag > 0) {
1501                 gdk_input_remove(lock_socket_tag);
1502         }
1503         fd_close(lock_socket);
1504         filename = get_socket_name();
1505         g_unlink(filename);
1506 #endif
1507
1508         return 0;
1509 }
1510
1511 static GPtrArray *get_folder_item_list(gint sock)
1512 {
1513         gchar buf[BUFFSIZE];
1514         FolderItem *item;
1515         GPtrArray *folders = NULL;
1516
1517         for (;;) {
1518                 fd_gets(sock, buf, sizeof(buf));
1519                 if (!strncmp(buf, ".\n", 2)) {
1520                         break;
1521                 }
1522                 strretchomp(buf);
1523                 if (!folders) {
1524                         folders = g_ptr_array_new();
1525                 }
1526                 item = folder_find_item_from_identifier(buf);
1527                 if (item) {
1528                         g_ptr_array_add(folders, item);
1529                 } else {
1530                         g_warning("no such folder: %s\n", buf);
1531                 }
1532         }
1533
1534         return folders;
1535 }
1536
1537 static void lock_socket_input_cb(gpointer data,
1538                                  gint source,
1539                                  GdkInputCondition condition)
1540 {
1541         MainWindow *mainwin = (MainWindow *)data;
1542         gint sock;
1543         gchar buf[BUFFSIZE];
1544
1545         sock = fd_accept(source);
1546         fd_gets(sock, buf, sizeof(buf));
1547
1548         if (!strncmp(buf, "popup", 5)) {
1549                 main_window_popup(mainwin);
1550         } else if (!strncmp(buf, "receive_all", 11)) {
1551                 inc_all_account_mail(mainwin, FALSE,
1552                                      prefs_common.newmail_notify_manu);
1553         } else if (!strncmp(buf, "receive", 7)) {
1554                 inc_mail(mainwin, prefs_common.newmail_notify_manu);
1555         } else if (!strncmp(buf, "compose_attach", 14)) {
1556                 GPtrArray *files;
1557                 gchar *mailto;
1558
1559                 mailto = g_strdup(buf + strlen("compose_attach") + 1);
1560                 files = g_ptr_array_new();
1561                 while (fd_gets(sock, buf, sizeof(buf)) > 0) {
1562                         if (buf[0] == '.' && buf[1] == '\n') {
1563                                 break;
1564                         }
1565                         strretchomp(buf);
1566                         g_ptr_array_add(files, g_strdup(buf));
1567                 }
1568                 open_compose_new(mailto, files);
1569                 ptr_array_free_strings(files);
1570                 g_ptr_array_free(files, TRUE);
1571                 g_free(mailto);
1572         } else if (!strncmp(buf, "compose", 7)) {
1573                 open_compose_new(buf + strlen("compose") + 1, NULL);
1574         } else if (!strncmp(buf, "subscribe", 9)) {
1575                 main_window_popup(mainwin);
1576                 folder_subscribe(buf + strlen("subscribe") + 1);
1577         } else if (!strncmp(buf, "send", 4)) {
1578                 send_queue();
1579         } else if (!strncmp(buf, "online", 6)) {
1580                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
1581         } else if (!strncmp(buf, "offline", 7)) {
1582                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
1583         } else if (!strncmp(buf, "status-full", 11) ||
1584                    !strncmp(buf, "status", 6)) {
1585                 gchar *status;
1586                 GPtrArray *folders;
1587  
1588                 folders = get_folder_item_list(sock);
1589                 status = folder_get_status
1590                         (folders, !strncmp(buf, "status-full", 11));
1591                 fd_write_all(sock, status, strlen(status));
1592                 fd_write_all(sock, ".\n", 2);
1593                 g_free(status);
1594                 if (folders) g_ptr_array_free(folders, TRUE);
1595         } else if (!strncmp(buf, "select ", 7)) {
1596                 const gchar *target = buf+7;
1597                 mainwindow_jump_to(target);
1598         } else if (!strncmp(buf, "exit", 4)) {
1599                 app_will_exit(NULL, mainwin);
1600         }
1601
1602         fd_close(sock);
1603 }
1604
1605 static void open_compose_new(const gchar *address, GPtrArray *attach_files)
1606 {
1607         gchar *addr = NULL;
1608
1609         if (address) {
1610                 Xstrdup_a(addr, address, return);
1611                 g_strstrip(addr);
1612         }
1613
1614         compose_new(NULL, addr, attach_files);
1615 }
1616
1617 static void send_queue(void)
1618 {
1619         GList *list;
1620         gchar *errstr = NULL;
1621         for (list = folder_get_list(); list != NULL; list = list->next) {
1622                 Folder *folder = list->data;
1623
1624                 if (folder->queue) {
1625                         gint res = procmsg_send_queue
1626                                 (folder->queue, prefs_common.savemsg,
1627                                 &errstr);
1628
1629                         if (res) {
1630                                 folder_item_scan(folder->queue);
1631                         }
1632                 }
1633         }
1634         if (errstr) {
1635                 gchar *tmp = g_strdup_printf(_("Some errors occurred "
1636                                 "while sending queued messages:\n%s"), errstr);
1637                 g_free(errstr);
1638                 alertpanel_error_log(tmp);
1639                 g_free(tmp);
1640         } else {
1641                 alertpanel_error_log("Some errors occurred "
1642                                 "while sending queued messages.");
1643         }
1644 }
1645
1646 static void quit_signal_handler(int sig)
1647 {
1648         debug_print("Quitting on signal %d\n", sig);
1649
1650         g_timeout_add(0, clean_quit, NULL);
1651 }
1652
1653 static void install_basic_sighandlers()
1654 {
1655 #ifndef G_OS_WIN32
1656         sigset_t    mask;
1657         struct sigaction act;
1658
1659         sigemptyset(&mask);
1660
1661 #ifdef SIGTERM
1662         sigaddset(&mask, SIGTERM);
1663 #endif
1664 #ifdef SIGINT
1665         sigaddset(&mask, SIGINT);
1666 #endif
1667 #ifdef SIGHUP
1668         sigaddset(&mask, SIGHUP);
1669 #endif
1670
1671         act.sa_handler = quit_signal_handler;
1672         act.sa_mask    = mask;
1673         act.sa_flags   = 0;
1674
1675 #ifdef SIGTERM
1676         sigaction(SIGTERM, &act, 0);
1677 #endif
1678 #ifdef SIGINT
1679         sigaction(SIGINT, &act, 0);
1680 #endif  
1681 #ifdef SIGHUP
1682         sigaction(SIGHUP, &act, 0);
1683 #endif  
1684
1685         sigprocmask(SIG_UNBLOCK, &mask, 0);
1686 #endif /* !G_OS_WIN32 */
1687 }