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