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