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