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