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