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