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