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