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