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