2005-10-26 [colin] 1.9.15cvs111
[claws.git] / src / main.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2005 Hiroyuki Yamamoto
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 #include "wizard.h"
43 #ifdef HAVE_STARTUP_NOTIFICATION
44 # define SN_API_NOT_YET_FROZEN
45 # include <libsn/sn-launchee.h>
46 # include <gdk/gdkx.h>
47 #endif
48
49 #include "sylpheed.h"
50 #include "main.h"
51 #include "mainwindow.h"
52 #include "folderview.h"
53 #include "image_viewer.h"
54 #include "summaryview.h"
55 #include "prefs_common.h"
56 #include "prefs_account.h"
57 #include "prefs_actions.h"
58 #include "prefs_ext_prog.h"
59 #include "prefs_fonts.h"
60 #include "prefs_image_viewer.h"
61 #include "prefs_message.h"
62 #include "prefs_receive.h"
63 #include "prefs_msg_colors.h"
64 #include "prefs_quote.h"
65 #include "prefs_spelling.h"
66 #include "prefs_summaries.h"
67 #include "prefs_themes.h"
68 #include "prefs_other.h"
69 #include "prefs_send.h"
70 #include "prefs_wrapping.h"
71 #include "prefs_compose_writing.h"
72 #include "prefs_display_header.h"
73 #include "account.h"
74 #include "procmsg.h"
75 #include "inc.h"
76 #include "import.h"
77 #include "manage_window.h"
78 #include "alertpanel.h"
79 #include "statusbar.h"
80 #include "addressbook.h"
81 #include "compose.h"
82 #include "folder.h"
83 #include "setup.h"
84 #include "utils.h"
85 #include "gtkutils.h"
86 #include "socket.h"
87 #include "log.h"
88 #include "prefs_toolbar.h"
89 #include "plugin.h"
90 #include "mh_gtk.h"
91 #include "imap_gtk.h"
92 #include "news_gtk.h"
93 #include "matcher.h"
94 #ifdef HAVE_LIBETPAN
95 #include "imap-thread.h"
96 #endif
97 #include "stock_pixmap.h"
98
99 #if USE_OPENSSL
100 #  include "ssl.h"
101 #endif
102
103 #include "version.h"
104
105 #include "crash.h"
106
107 gchar *prog_version;
108 #ifdef CRASH_DIALOG
109 gchar *argv0;
110 #endif
111
112 #ifdef HAVE_STARTUP_NOTIFICATION
113 static SnLauncheeContext *sn_context = NULL;
114 static SnDisplay *sn_display = NULL;
115 #endif
116
117 static gint lock_socket = -1;
118 static gint lock_socket_tag = 0;
119
120 typedef enum 
121 {
122         ONLINE_MODE_DONT_CHANGE,
123         ONLINE_MODE_ONLINE,
124         ONLINE_MODE_OFFLINE
125 } OnlineMode;
126
127 static struct RemoteCmd {
128         gboolean receive;
129         gboolean receive_all;
130         gboolean compose;
131         const gchar *compose_mailto;
132         GPtrArray *attach_files;
133         gboolean status;
134         gboolean status_full;
135         GPtrArray *status_folders;
136         GPtrArray *status_full_folders;
137         gboolean send;
138         gboolean crash;
139         int online_mode;
140         gchar   *crash_params;
141 } cmd;
142
143 static void parse_cmd_opt(int argc, char *argv[]);
144
145 static gint prohibit_duplicate_launch   (void);
146 static gchar * get_crashfile_name       (void);
147 static gint lock_socket_remove          (void);
148 static void lock_socket_input_cb        (gpointer          data,
149                                          gint              source,
150                                          GdkInputCondition condition);
151 #ifndef CLAWS                                    
152 static 
153 #endif
154 gchar *get_socket_name          (void);
155
156
157 static void open_compose_new            (const gchar    *address,
158                                          GPtrArray      *attach_files);
159
160 static void send_queue                  (void);
161 static void initial_processing          (FolderItem *item, gpointer data);
162 static void quit_signal_handler         (int sig);
163 static void install_basic_sighandlers   (void);
164 static void exit_sylpheed               (MainWindow *mainwin);
165
166 #define MAKE_DIR_IF_NOT_EXIST(dir) \
167 { \
168         if (!is_dir_exist(dir)) { \
169                 if (is_file_exist(dir)) { \
170                         alertpanel_warning \
171                                 (_("File '%s' already exists.\n" \
172                                    "Can't create folder."), \
173                                  dir); \
174                         return 1; \
175                 } \
176                 if (make_dir(dir) < 0) \
177                         return 1; \
178         } \
179 }
180
181 static MainWindow *static_mainwindow;
182
183 #ifdef HAVE_STARTUP_NOTIFICATION
184 static void sn_error_trap_push(SnDisplay *display, Display *xdisplay)
185 {
186         gdk_error_trap_push();
187 }
188
189 static void sn_error_trap_pop(SnDisplay *display, Display *xdisplay)
190 {
191         gdk_error_trap_pop();
192 }
193
194 static void startup_notification_complete(gboolean with_window)
195 {
196         Display *xdisplay;
197         GtkWidget *hack = NULL;
198
199         if (with_window) {
200                 /* this is needed to make the startup notification leave,
201                  * if we have been launched from a menu.
202                  * We have to display a window, so let it be very little */
203                 hack = gtk_window_new(GTK_WINDOW_POPUP);
204                 gtk_widget_set_uposition(hack, 0, 0);
205                 gtk_widget_set_size_request(hack, 1, 1);
206                 gtk_widget_show(hack);
207         }
208
209         xdisplay = GDK_DISPLAY();
210         sn_display = sn_display_new(xdisplay,
211                                 sn_error_trap_push,
212                                 sn_error_trap_pop);
213         sn_context = sn_launchee_context_new_from_environment(sn_display,
214                                                  DefaultScreen(xdisplay));
215
216         if (sn_context != NULL)
217         {
218                 sn_launchee_context_complete(sn_context);
219                 sn_launchee_context_unref(sn_context);
220                 sn_display_unref(sn_display);
221         }
222         if (with_window)
223                 gtk_widget_destroy(hack);
224 }
225 #endif /* HAVE_STARTUP_NOTIFICATION */
226
227 void sylpheed_gtk_idle(void) 
228 {
229         while(gtk_events_pending())
230                 gtk_main_iteration();
231         usleep(50000);
232 }
233
234 gboolean defer_check_all(void *data)
235 {
236         gboolean autochk = GPOINTER_TO_INT(data);
237
238         inc_all_account_mail(static_mainwindow, autochk, 
239                         prefs_common.newmail_notify_manu);
240
241         return FALSE;
242 }
243
244 gboolean defer_check(void *data)
245 {
246         inc_mail(static_mainwindow, prefs_common.newmail_notify_manu);
247
248         return FALSE;
249 }
250
251 static gboolean migrate_old_config(const gchar *old_cfg_dir, const gchar *new_cfg_dir)
252 {
253         gchar *message = g_strdup_printf(_("Configuration for Sylpheed-Claws %s found.\n"
254                          "Do you want to migrate this configuration?"),
255                          !strcmp(old_cfg_dir, OLD_GTK1_RC_DIR)?
256                                 _("1.0.5 or previous"):_("1.9.15 or previous"));
257         gint r = 0;
258         GtkWidget *window = NULL;
259         if (alertpanel(_("Migration of configuration"),
260                        message,
261                        GTK_STOCK_YES, GTK_STOCK_NO, NULL) != G_ALERTDEFAULT)
262                 return FALSE;
263         
264         window = label_window_create(_("Copying configuration..."));
265         GTK_EVENTS_FLUSH();
266         r = copy_dir(old_cfg_dir, new_cfg_dir);
267         gtk_widget_destroy(window);
268         if (r != 0) {
269                 alertpanel_error(_("Migration failed!"));
270         }
271         return (r == 0);
272 }
273
274 int main(int argc, char *argv[])
275 {
276         gchar *userrc;
277         MainWindow *mainwin;
278         FolderView *folderview;
279         GdkPixbuf *icon;
280         gboolean crash_file_present = FALSE;
281
282         if (!sylpheed_init(&argc, &argv)) {
283                 return 0;
284         }
285
286         prog_version = PROG_VERSION;
287 #ifdef CRASH_DIALOG
288         argv0 = g_strdup(argv[0]);
289 #endif
290
291         parse_cmd_opt(argc, argv);
292
293 #ifdef CRASH_DIALOG
294         if (cmd.crash) {
295                 gtk_set_locale();
296                 gtk_init(&argc, &argv);
297                 crash_main(cmd.crash_params);
298                 return 0;
299         }
300         crash_install_handlers();
301 #endif
302         install_basic_sighandlers();
303         sock_init();
304
305         /* check and create unix domain socket for remote operation */
306 #ifdef G_OS_UNIX
307         lock_socket = prohibit_duplicate_launch();
308         if (lock_socket < 0) {
309 #ifdef HAVE_STARTUP_NOTIFICATION
310                 if(gtk_init_check(&argc, &argv))
311                         startup_notification_complete(TRUE);
312 #endif
313                 return 0;
314         }
315
316         if (cmd.status || cmd.status_full) {
317                 puts("0 Sylpheed not running.");
318                 lock_socket_remove();
319                 return 0;
320         }
321 #endif
322         g_thread_init(NULL);
323         /* gdk_threads_init(); */
324
325         gtk_set_locale();
326         gtk_init(&argc, &argv);
327
328         gdk_rgb_init();
329         gtk_widget_set_default_colormap(gdk_rgb_get_colormap());
330         gtk_widget_set_default_visual(gdk_rgb_get_visual());
331
332         if (!g_thread_supported())
333                 g_error(_("g_thread is not supported by glib.\n"));
334
335         /* parse gtkrc files */
336         userrc = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".gtkrc-2.0",
337                              NULL);
338         gtk_rc_parse(userrc);
339         g_free(userrc);
340         userrc = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".gtk",
341                              G_DIR_SEPARATOR_S, "gtkrc-2.0", NULL);
342         gtk_rc_parse(userrc);
343         g_free(userrc);
344
345         CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
346         if (!is_dir_exist(RC_DIR)) {
347                 gboolean r = FALSE;
348                 if (is_dir_exist(OLD_GTK2_RC_DIR))
349                         r = migrate_old_config(OLD_GTK2_RC_DIR, RC_DIR);
350                 else if (is_dir_exist(OLD_GTK1_RC_DIR))
351                         r = migrate_old_config(OLD_GTK1_RC_DIR, RC_DIR);
352                 if (r == FALSE && !is_dir_exist(RC_DIR) && make_dir(RC_DIR) < 0)
353                         exit(1);
354         }
355
356         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, "gtkrc-2.0", NULL);
357         gtk_rc_parse(userrc);
358         g_free(userrc);
359
360         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
361         gtk_accel_map_load (userrc);
362         g_free(userrc);
363
364         gtk_settings_set_long_property(gtk_settings_get_default(), 
365                                        "gtk-can-change-accels",
366                                        (glong)TRUE, "XProperty");
367
368         CHDIR_RETURN_VAL_IF_FAIL(get_rc_dir(), 1);
369
370         MAKE_DIR_IF_NOT_EXIST(get_imap_cache_dir());
371         MAKE_DIR_IF_NOT_EXIST(get_news_cache_dir());
372         MAKE_DIR_IF_NOT_EXIST(get_mime_tmp_dir());
373         MAKE_DIR_IF_NOT_EXIST(get_tmp_dir());
374         MAKE_DIR_IF_NOT_EXIST(UIDL_DIR);
375
376         crash_file_present = is_file_exist(get_crashfile_name());
377         /* remove temporary files */
378         remove_all_files(get_tmp_dir());
379         remove_all_files(get_mime_tmp_dir());
380
381         if (is_file_exist("sylpheed.log")) {
382                 if (rename_force("sylpheed.log", "sylpheed.log.bak") < 0)
383                         FILE_OP_ERROR("sylpheed.log", "rename");
384         }
385         set_log_file("sylpheed.log");
386
387         CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
388
389         folder_system_init();
390         prefs_common_read_config();
391
392         prefs_themes_init();
393         prefs_fonts_init();
394         prefs_ext_prog_init();
395         prefs_wrapping_init();
396         prefs_compose_writing_init();
397         prefs_msg_colors_init();
398         image_viewer_init();
399         prefs_image_viewer_init();
400         prefs_quote_init();
401         prefs_summaries_init();
402         prefs_message_init();
403         prefs_other_init();
404         prefs_receive_init();
405         prefs_send_init();
406 #ifdef USE_ASPELL
407         gtkaspell_checkers_init();
408         prefs_spelling_init();
409 #endif
410         
411         sock_set_io_timeout(prefs_common.io_timeout_secs);
412 #ifdef HAVE_LIBETPAN
413         imap_main_set_timeout(prefs_common.io_timeout_secs);
414 #endif
415         prefs_actions_read_config();
416         prefs_display_header_read_config();
417         /* prefs_filtering_read_config(); */
418         addressbook_read_file();
419         renderer_read_config();
420
421         gtkut_widget_init();
422         stock_pixbuf_gdk(NULL, STOCK_PIXMAP_SYLPHEED_ICON, &icon);
423         gtk_window_set_default_icon(icon);
424
425         folderview_initialize();
426
427         mh_gtk_init();
428         imap_gtk_init();
429         news_gtk_init();
430                 
431         mainwin = main_window_create
432                 (prefs_common.sep_folder | prefs_common.sep_msg << 1);
433         folderview = mainwin->folderview;
434
435         gtk_clist_freeze(GTK_CLIST(mainwin->folderview->ctree));
436         folder_item_update_freeze();
437
438         /* register the callback of unix domain socket input */
439 #ifdef G_OS_UNIX
440         lock_socket_tag = gdk_input_add(lock_socket,
441                                         GDK_INPUT_READ | GDK_INPUT_EXCEPTION,
442                                         lock_socket_input_cb,
443                                         mainwin);
444 #endif
445
446         prefs_account_init();
447         account_read_config_all();
448
449         if (folder_read_list() < 0) {
450                 if (!run_wizard(mainwin, TRUE))
451                         exit(1);
452                 folder_write_list();
453         }
454
455         if (!account_get_list()) {
456                 if (!run_wizard(mainwin, FALSE))
457                         exit(1);
458                 account_read_config_all();
459                 if(!account_get_list())
460                         exit_sylpheed(mainwin);
461         }
462
463         gtk_window_deiconify(mainwin->window);
464
465 #ifdef HAVE_LIBETPAN
466         imap_main_init();
467 #endif  
468         account_set_missing_folder();
469         folder_set_missing_folders();
470         folderview_set(folderview);
471
472         prefs_matcher_read_config();
473
474         /* make one all-folder processing before using sylpheed */
475         main_window_cursor_wait(mainwin);
476         folder_func_to_all_folders(initial_processing, (gpointer *)mainwin);
477
478         /* if Sylpheed crashed, rebuild caches */
479         if (!cmd.crash && crash_file_present) {
480                 debug_print("Sylpheed crashed, checking for new messages in local folders\n");
481                 folder_item_update_thaw();
482                 folderview_check_new(NULL);
483                 folder_clean_cache_memory_force();
484                 folder_item_update_freeze();
485         }
486         /* make the crash-indicator file */
487         str_write_to_file("foo", get_crashfile_name());
488
489         addressbook_read_file();
490
491         inc_autocheck_timer_init(mainwin);
492
493         /* ignore SIGPIPE signal for preventing sudden death of program */
494 #ifdef G_OS_UNIX
495         signal(SIGPIPE, SIG_IGN);
496 #endif
497         if (cmd.online_mode == ONLINE_MODE_OFFLINE)
498                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
499         if (cmd.online_mode == ONLINE_MODE_ONLINE)
500                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
501
502         if (cmd.status_folders) {
503                 g_ptr_array_free(cmd.status_folders, TRUE);
504                 cmd.status_folders = NULL;
505         }
506         if (cmd.status_full_folders) {
507                 g_ptr_array_free(cmd.status_full_folders, TRUE);
508                 cmd.status_full_folders = NULL;
509         }
510
511         sylpheed_register_idle_function(sylpheed_gtk_idle);
512
513         prefs_toolbar_init();
514
515         plugin_load_all("GTK2");
516         
517         static_mainwindow = mainwin;
518
519 #ifdef HAVE_STARTUP_NOTIFICATION
520         startup_notification_complete(FALSE);
521 #endif
522         folder_item_update_thaw();
523         gtk_clist_thaw(GTK_CLIST(mainwin->folderview->ctree));
524         main_window_cursor_normal(mainwin);
525
526         if (cmd.receive_all)
527                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(FALSE));
528         else if (prefs_common.chk_on_startup)
529                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(TRUE));
530         else if (cmd.receive)
531                 g_timeout_add(1000, defer_check, NULL);
532         else
533                 gtk_widget_grab_focus(folderview->ctree);
534
535         if (cmd.compose)
536                 open_compose_new(cmd.compose_mailto, cmd.attach_files);
537         if (cmd.attach_files) {
538                 ptr_array_free_strings(cmd.attach_files);
539                 g_ptr_array_free(cmd.attach_files, TRUE);
540                 cmd.attach_files = NULL;
541         }
542         if (cmd.send)
543                 send_queue();
544         
545         gtk_main();
546
547         exit_sylpheed(mainwin);
548
549         return 0;
550 }
551
552 static void save_all_caches(FolderItem *item, gpointer data)
553 {
554         if (!item->cache)
555                 return;
556         folder_item_write_cache(item);
557 }
558
559 static void exit_sylpheed(MainWindow *mainwin)
560 {
561         gchar *filename;
562
563         debug_print("shutting down\n");
564         inc_autocheck_timer_remove();
565
566         if (prefs_common.clean_on_exit)
567                 main_window_empty_trash(mainwin, prefs_common.ask_on_clean);
568
569         /* save prefs for opened folder */
570         if(mainwin->folderview->opened)
571         {
572                 FolderItem *item;
573
574                 item = gtk_ctree_node_get_row_data(GTK_CTREE(mainwin->folderview->ctree), mainwin->folderview->opened);
575                 summary_save_prefs_to_folderitem(mainwin->folderview->summaryview, item);
576         }
577
578         /* save all state before exiting */
579         folder_write_list();
580         folder_func_to_all_folders(save_all_caches, NULL);
581
582         main_window_get_size(mainwin);
583         main_window_get_position(mainwin);
584         prefs_common_write_config();
585         account_write_config_all();
586         addressbook_export_to_file();
587
588         filename = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
589         gtk_accel_map_save(filename);
590         g_free(filename);
591
592         /* delete temporary files */
593         remove_all_files(get_tmp_dir());
594         remove_all_files(get_mime_tmp_dir());
595
596         close_log_file();
597
598 #ifdef HAVE_LIBETPAN
599         imap_main_done();
600 #endif
601         /* delete crashfile */
602         if (!cmd.crash)
603                 g_unlink(get_crashfile_name());
604
605         lock_socket_remove();
606
607         main_window_destroy(mainwin);
608         
609         plugin_unload_all("GTK2");
610
611         prefs_toolbar_done();
612
613         addressbook_destroy();
614
615         prefs_themes_done();
616         prefs_fonts_done();
617         prefs_ext_prog_done();
618         prefs_wrapping_done();
619         prefs_compose_writing_done();
620         prefs_msg_colors_done();
621         prefs_image_viewer_done();
622         image_viewer_done();
623         prefs_quote_done();
624         prefs_summaries_done();
625         prefs_message_done();
626         prefs_other_done();
627         prefs_receive_done();
628         prefs_send_done();
629 #ifdef USE_ASPELL       
630         prefs_spelling_done();
631         gtkaspell_checkers_quit();
632 #endif
633         sylpheed_done();
634
635 }
636
637 static void parse_cmd_opt(int argc, char *argv[])
638 {
639         gint i;
640
641         for (i = 1; i < argc; i++) {
642                 if (!strncmp(argv[i], "--receive-all", 13))
643                         cmd.receive_all = TRUE;
644                 else if (!strncmp(argv[i], "--receive", 9))
645                         cmd.receive = TRUE;
646                 else if (!strncmp(argv[i], "--compose", 9)) {
647                         const gchar *p = argv[i + 1];
648
649                         cmd.compose = TRUE;
650                         cmd.compose_mailto = NULL;
651                         if (p && *p != '\0' && *p != '-') {
652                                 if (!strncmp(p, "mailto:", 7))
653                                         cmd.compose_mailto = p + 7;
654                                 else
655                                         cmd.compose_mailto = p;
656                                 i++;
657                         }
658                 } else if (!strncmp(argv[i], "--attach", 8)) {
659                         const gchar *p = argv[i + 1];
660                         gchar *file;
661
662                         while (p && *p != '\0' && *p != '-') {
663                                 if (!cmd.attach_files)
664                                         cmd.attach_files = g_ptr_array_new();
665                                 if (*p != G_DIR_SEPARATOR)
666                                         file = g_strconcat(sylpheed_get_startup_dir(),
667                                                            G_DIR_SEPARATOR_S,
668                                                            p, NULL);
669                                 else
670                                         file = g_strdup(p);
671                                 g_ptr_array_add(cmd.attach_files, file);
672                                 i++;
673                                 p = argv[i + 1];
674                         }
675                 } else if (!strncmp(argv[i], "--send", 6)) {
676                         cmd.send = TRUE;
677                 } else if (!strncmp(argv[i], "--version", 9)) {
678                         puts("Sylpheed version " VERSION);
679                         exit(0);
680                 } else if (!strncmp(argv[i], "--status-full", 13)) {
681                         const gchar *p = argv[i + 1];
682  
683                         cmd.status_full = TRUE;
684                         while (p && *p != '\0' && *p != '-') {
685                                 if (!cmd.status_full_folders)
686                                         cmd.status_full_folders =
687                                                 g_ptr_array_new();
688                                 g_ptr_array_add(cmd.status_full_folders,
689                                                 g_strdup(p));
690                                 i++;
691                                 p = argv[i + 1];
692                         }
693                 } else if (!strncmp(argv[i], "--status", 8)) {
694                         const gchar *p = argv[i + 1];
695  
696                         cmd.status = TRUE;
697                         while (p && *p != '\0' && *p != '-') {
698                                 if (!cmd.status_folders)
699                                         cmd.status_folders = g_ptr_array_new();
700                                 g_ptr_array_add(cmd.status_folders,
701                                                 g_strdup(p));
702                                 i++;
703                                 p = argv[i + 1];
704                         }
705                 } else if (!strncmp(argv[i], "--online", 8)) {
706                         cmd.online_mode = ONLINE_MODE_ONLINE;
707                 } else if (!strncmp(argv[i], "--offline", 9)) {
708                         cmd.online_mode = ONLINE_MODE_OFFLINE;
709                 } else if (!strncmp(argv[i], "--help", 6)) {
710                         gchar *base = g_path_get_basename(argv[0]);
711                         g_print(_("Usage: %s [OPTION]...\n"), base);
712
713                         g_print("%s\n", _("  --compose [address]    open composition window"));
714                         g_print("%s\n", _("  --attach file1 [file2]...\n"
715                                   "                         open composition window with specified files\n"
716                                   "                         attached"));
717                         g_print("%s\n", _("  --receive              receive new messages"));
718                         g_print("%s\n", _("  --receive-all          receive new messages of all accounts"));
719                         g_print("%s\n", _("  --send                 send all queued messages"));
720                         g_print("%s\n", _("  --status [folder]...   show the total number of messages"));
721                         g_print("%s\n", _("  --status-full [folder]...\n"
722                                "                         show the status of each folder"));
723                         g_print("%s\n", _("  --online               switch to online mode"));
724                         g_print("%s\n", _("  --offline              switch to offline mode"));
725                         g_print("%s\n", _("  --debug                debug mode"));
726                         g_print("%s\n", _("  --help                 display this help and exit"));
727                         g_print("%s\n", _("  --version              output version information and exit"));
728                         g_print("%s\n", _("  --config-dir           output configuration directory"));
729
730                         g_free(base);
731                         exit(1);
732                 } else if (!strncmp(argv[i], "--crash", 7)) {
733                         cmd.crash = TRUE;
734                         cmd.crash_params = g_strdup(argv[i + 1]);
735                         i++;
736                 } else if (!strncmp(argv[i], "--config-dir", sizeof "--config-dir" - 1)) {
737                         puts(RC_DIR);
738                         exit(0);
739                 }
740                 
741         }
742
743         if (cmd.attach_files && cmd.compose == FALSE) {
744                 cmd.compose = TRUE;
745                 cmd.compose_mailto = NULL;
746         }
747 }
748
749 static gint get_queued_message_num(void)
750 {
751         FolderItem *queue;
752
753         queue = folder_get_default_queue();
754         if (!queue) return -1;
755
756         folder_item_scan(queue);
757         return queue->total_msgs;
758 }
759
760 static void initial_processing(FolderItem *item, gpointer data)
761 {
762         MainWindow *mainwin = (MainWindow *)data;
763         gchar *buf;
764
765         g_return_if_fail(item);
766         buf = g_strdup_printf(_("Processing (%s)..."), 
767                               item->path 
768                               ? item->path 
769                               : _("top level folder"));
770         debug_print("%s\n", buf);
771         g_free(buf);
772
773         
774         if (item->prefs->enable_processing)
775                 folder_item_apply_processing(item);
776
777         debug_print("done.\n");
778         STATUSBAR_POP(mainwin);
779 }
780
781 static void draft_all_messages(void)
782 {
783         GList *compose_list = NULL;
784         
785         while ((compose_list = compose_get_compose_list()) != NULL) {
786                 Compose *c = (Compose*)compose_list->data;
787                 compose_draft(c);
788         }       
789 }
790
791 gboolean clean_quit(gpointer data)
792 {
793         static gboolean firstrun = TRUE;
794
795         if (!firstrun)
796                 return FALSE;
797         firstrun = FALSE;
798
799         /*!< Good idea to have the main window stored in a 
800          *   static variable so we can check that variable
801          *   to see if we're really allowed to do things
802          *   that actually the spawner is supposed to 
803          *   do (like: sending mail, composing messages).
804          *   Because, really, if we're the spawnee, and
805          *   we touch GTK stuff, we're hosed. See the 
806          *   next fixme. */
807
808         /* FIXME: Use something else to signal that we're
809          * in the original spawner, and not in a spawned
810          * child. */
811         if (!static_mainwindow) 
812                 return FALSE;
813                 
814         draft_all_messages();
815
816         exit_sylpheed(static_mainwindow);
817         exit(0);
818
819         return FALSE;
820 }
821
822 void app_will_exit(GtkWidget *widget, gpointer data)
823 {
824         MainWindow *mainwin = data;
825
826         if (compose_get_compose_list()) {
827                 gint val = alertpanel(_("Really quit?"),
828                                _("Composing message exists."),
829                                _("_Save to Draft"), _("_Discard them"), _("Do_n't quit"));
830                 switch (val) {
831                         case G_ALERTOTHER:
832                                 return;
833                         case G_ALERTALTERNATE:
834                                 break;
835                         default:
836                                 draft_all_messages();
837                 }
838
839                 manage_window_focus_in(mainwin->window, NULL, NULL);
840         }
841
842         if (prefs_common.warn_queued_on_exit && get_queued_message_num() > 0) {
843                 if (alertpanel(_("Queued messages"),
844                                _("Some unsent messages are queued. Exit now?"),
845                                GTK_STOCK_OK, GTK_STOCK_CANCEL, NULL)
846                     != G_ALERTDEFAULT)
847                         return;
848                 manage_window_focus_in(mainwin->window, NULL, NULL);
849         }
850
851         sock_cleanup();
852
853         gtk_main_quit();
854 }
855
856 /*
857  * CLAWS: want this public so crash dialog can delete the
858  * lock file too
859  */
860 #ifndef CLAWS
861 static
862 #endif
863 gchar *get_socket_name(void)
864 {
865         static gchar *filename = NULL;
866
867         if (filename == NULL) {
868                 filename = g_strdup_printf("%s%csylpheed-claws-%d",
869                                            g_get_tmp_dir(), G_DIR_SEPARATOR,
870 #if HAVE_GETUID
871                                            getuid());
872 #else
873                                            0);                                          
874 #endif
875         }
876
877         return filename;
878 }
879
880 static gchar *get_crashfile_name(void)
881 {
882         static gchar *filename = NULL;
883
884         if (filename == NULL) {
885                 filename = g_strdup_printf("%s%csylpheed-crashed",
886                                            get_tmp_dir(), G_DIR_SEPARATOR);
887         }
888
889         return filename;
890 }
891
892 static gint prohibit_duplicate_launch(void)
893 {
894         gint uxsock;
895         gchar *path;
896
897         path = get_socket_name();
898         uxsock = fd_connect_unix(path);
899         if (uxsock < 0) {
900                 g_unlink(path);
901                 return fd_open_unix(path);
902         }
903
904         /* remote command mode */
905
906         debug_print("another Sylpheed is already running.\n");
907
908         if (cmd.receive_all)
909                 fd_write_all(uxsock, "receive_all\n", 12);
910         else if (cmd.receive)
911                 fd_write_all(uxsock, "receive\n", 8);
912         else if (cmd.compose && cmd.attach_files) {
913                 gchar *str, *compose_str;
914                 gint i;
915
916                 if (cmd.compose_mailto)
917                         compose_str = g_strdup_printf("compose_attach %s\n",
918                                                       cmd.compose_mailto);
919                 else
920                         compose_str = g_strdup("compose_attach\n");
921
922                 fd_write_all(uxsock, compose_str, strlen(compose_str));
923                 g_free(compose_str);
924
925                 for (i = 0; i < cmd.attach_files->len; i++) {
926                         str = g_ptr_array_index(cmd.attach_files, i);
927                         fd_write_all(uxsock, str, strlen(str));
928                         fd_write_all(uxsock, "\n", 1);
929                 }
930
931                 fd_write_all(uxsock, ".\n", 2);
932         } else if (cmd.compose) {
933                 gchar *compose_str;
934
935                 if (cmd.compose_mailto)
936                         compose_str = g_strdup_printf
937                                 ("compose %s\n", cmd.compose_mailto);
938                 else
939                         compose_str = g_strdup("compose\n");
940
941                 fd_write_all(uxsock, compose_str, strlen(compose_str));
942                 g_free(compose_str);
943         } else if (cmd.send) {
944                 fd_write_all(uxsock, "send\n", 5);
945         } else if (cmd.online_mode == ONLINE_MODE_ONLINE) {
946                 fd_write(uxsock, "online\n", 6);
947         } else if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
948                 fd_write(uxsock, "offline\n", 7);
949         } else if (cmd.status || cmd.status_full) {
950                 gchar buf[BUFFSIZE];
951                 gint i;
952                 const gchar *command;
953                 GPtrArray *folders;
954                 gchar *folder;
955  
956                 command = cmd.status_full ? "status-full\n" : "status\n";
957                 folders = cmd.status_full ? cmd.status_full_folders :
958                         cmd.status_folders;
959  
960                 fd_write_all(uxsock, command, strlen(command));
961                 for (i = 0; folders && i < folders->len; ++i) {
962                         folder = g_ptr_array_index(folders, i);
963                         fd_write_all(uxsock, folder, strlen(folder));
964                         fd_write_all(uxsock, "\n", 1);
965                 }
966                 fd_write_all(uxsock, ".\n", 2);
967                 for (;;) {
968                         fd_gets(uxsock, buf, sizeof(buf));
969                         if (!strncmp(buf, ".\n", 2)) break;
970                         fputs(buf, stdout);
971                 }
972         } else
973                 fd_write_all(uxsock, "popup\n", 6);
974
975         fd_close(uxsock);
976         return -1;
977 }
978
979 static gint lock_socket_remove(void)
980 {
981 #ifdef G_OS_UNIX
982         gchar *filename;
983
984         if (lock_socket < 0) return -1;
985
986         if (lock_socket_tag > 0)
987                 gdk_input_remove(lock_socket_tag);
988         fd_close(lock_socket);
989         filename = get_socket_name();
990         g_unlink(filename);
991 #endif
992
993         return 0;
994 }
995
996 static GPtrArray *get_folder_item_list(gint sock)
997 {
998         gchar buf[BUFFSIZE];
999         FolderItem *item;
1000         GPtrArray *folders = NULL;
1001
1002         for (;;) {
1003                 fd_gets(sock, buf, sizeof(buf));
1004                 if (!strncmp(buf, ".\n", 2)) break;
1005                 strretchomp(buf);
1006                 if (!folders) folders = g_ptr_array_new();
1007                 item = folder_find_item_from_identifier(buf);
1008                 if (item)
1009                         g_ptr_array_add(folders, item);
1010                 else
1011                         g_warning("no such folder: %s\n", buf);
1012         }
1013
1014         return folders;
1015 }
1016
1017 static void lock_socket_input_cb(gpointer data,
1018                                  gint source,
1019                                  GdkInputCondition condition)
1020 {
1021         MainWindow *mainwin = (MainWindow *)data;
1022         gint sock;
1023         gchar buf[BUFFSIZE];
1024
1025         sock = fd_accept(source);
1026         fd_gets(sock, buf, sizeof(buf));
1027
1028         if (!strncmp(buf, "popup", 5)) {
1029                 main_window_popup(mainwin);
1030         } else if (!strncmp(buf, "receive_all", 11)) {
1031                 inc_all_account_mail(mainwin, FALSE,
1032                                      prefs_common.newmail_notify_manu);
1033         } else if (!strncmp(buf, "receive", 7)) {
1034                 inc_mail(mainwin, prefs_common.newmail_notify_manu);
1035         } else if (!strncmp(buf, "compose_attach", 14)) {
1036                 GPtrArray *files;
1037                 gchar *mailto;
1038
1039                 mailto = g_strdup(buf + strlen("compose_attach") + 1);
1040                 files = g_ptr_array_new();
1041                 while (fd_gets(sock, buf, sizeof(buf)) > 0) {
1042                         if (buf[0] == '.' && buf[1] == '\n') break;
1043                         strretchomp(buf);
1044                         g_ptr_array_add(files, g_strdup(buf));
1045                 }
1046                 open_compose_new(mailto, files);
1047                 ptr_array_free_strings(files);
1048                 g_ptr_array_free(files, TRUE);
1049                 g_free(mailto);
1050         } else if (!strncmp(buf, "compose", 7)) {
1051                 open_compose_new(buf + strlen("compose") + 1, NULL);
1052         } else if (!strncmp(buf, "send", 4)) {
1053                 send_queue();
1054         } else if (!strncmp(buf, "online", 6)) {
1055                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
1056         } else if (!strncmp(buf, "offline", 7)) {
1057                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
1058         } else if (!strncmp(buf, "status-full", 11) ||
1059                    !strncmp(buf, "status", 6)) {
1060                 gchar *status;
1061                 GPtrArray *folders;
1062  
1063                 folders = get_folder_item_list(sock);
1064                 status = folder_get_status
1065                         (folders, !strncmp(buf, "status-full", 11));
1066                 fd_write_all(sock, status, strlen(status));
1067                 fd_write_all(sock, ".\n", 2);
1068                 g_free(status);
1069                 if (folders) g_ptr_array_free(folders, TRUE);
1070         }
1071
1072         fd_close(sock);
1073 }
1074
1075 static void open_compose_new(const gchar *address, GPtrArray *attach_files)
1076 {
1077         gchar *addr = NULL;
1078
1079         if (address) {
1080                 Xstrdup_a(addr, address, return);
1081                 g_strstrip(addr);
1082         }
1083
1084         compose_new(NULL, addr, attach_files);
1085 }
1086
1087 static void send_queue(void)
1088 {
1089         GList *list;
1090
1091         for (list = folder_get_list(); list != NULL; list = list->next) {
1092                 Folder *folder = list->data;
1093
1094                 if (folder->queue) {
1095                         gint res = procmsg_send_queue
1096                                 (folder->queue, prefs_common.savemsg);
1097
1098                         if (res < 0)    
1099                                 alertpanel_error(_("Some errors occurred while sending queued messages."));
1100                         if (res)        
1101                                 folder_item_scan(folder->queue);
1102                 }
1103         }
1104 }
1105
1106 static void quit_signal_handler(int sig)
1107 {
1108         debug_print("Quitting on signal %d\n", sig);
1109
1110         g_timeout_add(0, clean_quit, NULL);
1111 }
1112
1113 static void install_basic_sighandlers()
1114 {
1115         sigset_t    mask;
1116         struct sigaction act;
1117
1118         sigemptyset(&mask);
1119
1120 #ifdef SIGTERM
1121         sigaddset(&mask, SIGTERM);
1122 #endif
1123 #ifdef SIGINT
1124         sigaddset(&mask, SIGINT);
1125 #endif
1126 #ifdef SIGHUP
1127         sigaddset(&mask, SIGHUP);
1128 #endif
1129
1130         act.sa_handler = quit_signal_handler;
1131         act.sa_mask    = mask;
1132         act.sa_flags   = 0;
1133
1134 #ifdef SIGTERM
1135         sigaction(SIGTERM, &act, 0);
1136 #endif
1137 #ifdef SIGINT
1138         sigaction(SIGINT, &act, 0);
1139 #endif  
1140 #ifdef SIGHUP
1141         sigaction(SIGHUP, &act, 0);
1142 #endif  
1143
1144         sigprocmask(SIG_UNBLOCK, &mask, 0);
1145 }