e48435e408357ba6b21e9d34d13fbc79a1bc16bf
[claws.git] / src / main.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2006 Hiroyuki Yamamoto and the Sylpheed-Claws team
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         gboolean exit;
142         gboolean subscribe;
143         const gchar *subscribe_uri;
144 } cmd;
145
146 static void parse_cmd_opt(int argc, char *argv[]);
147
148 static gint prohibit_duplicate_launch   (void);
149 static gchar * get_crashfile_name       (void);
150 static gint lock_socket_remove          (void);
151 static void lock_socket_input_cb        (gpointer          data,
152                                          gint              source,
153                                          GdkInputCondition condition);
154 #ifndef CLAWS                                    
155 static 
156 #endif
157 gchar *get_socket_name          (void);
158
159
160 static void open_compose_new            (const gchar    *address,
161                                          GPtrArray      *attach_files);
162
163 static void send_queue                  (void);
164 static void initial_processing          (FolderItem *item, gpointer data);
165 static void quit_signal_handler         (int sig);
166 static void install_basic_sighandlers   (void);
167 static void exit_sylpheed               (MainWindow *mainwin);
168
169 #define MAKE_DIR_IF_NOT_EXIST(dir) \
170 { \
171         if (!is_dir_exist(dir)) { \
172                 if (is_file_exist(dir)) { \
173                         alertpanel_warning \
174                                 (_("File '%s' already exists.\n" \
175                                    "Can't create folder."), \
176                                  dir); \
177                         return 1; \
178                 } \
179                 if (make_dir(dir) < 0) \
180                         return 1; \
181         } \
182 }
183
184 static MainWindow *static_mainwindow;
185
186 #ifdef HAVE_STARTUP_NOTIFICATION
187 static void sn_error_trap_push(SnDisplay *display, Display *xdisplay)
188 {
189         gdk_error_trap_push();
190 }
191
192 static void sn_error_trap_pop(SnDisplay *display, Display *xdisplay)
193 {
194         gdk_error_trap_pop();
195 }
196
197 static void startup_notification_complete(gboolean with_window)
198 {
199         Display *xdisplay;
200         GtkWidget *hack = NULL;
201
202         if (with_window) {
203                 /* this is needed to make the startup notification leave,
204                  * if we have been launched from a menu.
205                  * We have to display a window, so let it be very little */
206                 hack = gtk_window_new(GTK_WINDOW_POPUP);
207                 gtk_widget_set_uposition(hack, 0, 0);
208                 gtk_widget_set_size_request(hack, 1, 1);
209                 gtk_widget_show(hack);
210         }
211
212         xdisplay = GDK_DISPLAY();
213         sn_display = sn_display_new(xdisplay,
214                                 sn_error_trap_push,
215                                 sn_error_trap_pop);
216         sn_context = sn_launchee_context_new_from_environment(sn_display,
217                                                  DefaultScreen(xdisplay));
218
219         if (sn_context != NULL) {
220                 sn_launchee_context_complete(sn_context);
221                 sn_launchee_context_unref(sn_context);
222                 sn_display_unref(sn_display);
223         }
224         if (with_window) {
225                 gtk_widget_destroy(hack);
226         }
227 }
228 #endif /* HAVE_STARTUP_NOTIFICATION */
229
230 void sylpheed_gtk_idle(void) 
231 {
232         while(gtk_events_pending()) {
233                 gtk_main_iteration();
234         }
235         g_usleep(50000);
236 }
237
238 gboolean defer_check_all(void *data)
239 {
240         gboolean autochk = GPOINTER_TO_INT(data);
241
242         inc_all_account_mail(static_mainwindow, autochk, 
243                         prefs_common.newmail_notify_manu);
244
245         return FALSE;
246 }
247
248 gboolean defer_check(void *data)
249 {
250         inc_mail(static_mainwindow, prefs_common.newmail_notify_manu);
251
252         return FALSE;
253 }
254
255 static gboolean migrate_old_config(const gchar *old_cfg_dir, const gchar *new_cfg_dir)
256 {
257         gchar *message = g_strdup_printf(_("Configuration for Sylpheed-Claws %s found.\n"
258                          "Do you want to migrate this configuration?"),
259                          !strcmp(old_cfg_dir, OLD_GTK1_RC_DIR)?
260                                 _("1.0.5 or previous"):_("1.9.15 or previous"));
261         gint r = 0;
262         GtkWidget *window = NULL;
263         if (alertpanel(_("Migration of configuration"),
264                        message,
265                        GTK_STOCK_NO, GTK_STOCK_YES, NULL) != G_ALERTALTERNATE) {
266                 return FALSE;
267         }
268         
269         window = label_window_create(_("Copying configuration..."));
270         GTK_EVENTS_FLUSH();
271         r = copy_dir(old_cfg_dir, new_cfg_dir);
272         gtk_widget_destroy(window);
273         if (r != 0) {
274                 alertpanel_error(_("Migration failed!"));
275         }
276         return (r == 0);
277 }
278
279 int main(int argc, char *argv[])
280 {
281         gchar *userrc;
282         MainWindow *mainwin;
283         FolderView *folderview;
284         GdkPixbuf *icon;
285         gboolean crash_file_present = FALSE;
286
287         if (!sylpheed_init(&argc, &argv)) {
288                 return 0;
289         }
290
291         prog_version = PROG_VERSION;
292 #ifdef CRASH_DIALOG
293         argv0 = g_strdup(argv[0]);
294 #endif
295
296         parse_cmd_opt(argc, argv);
297
298 #ifdef CRASH_DIALOG
299         if (cmd.crash) {
300                 gtk_set_locale();
301                 gtk_init(&argc, &argv);
302                 crash_main(cmd.crash_params);
303                 return 0;
304         }
305         crash_install_handlers();
306 #endif
307         install_basic_sighandlers();
308         sock_init();
309
310         /* check and create unix domain socket for remote operation */
311 #ifdef G_OS_UNIX
312         lock_socket = prohibit_duplicate_launch();
313         if (lock_socket < 0) {
314 #ifdef HAVE_STARTUP_NOTIFICATION
315                 if(gtk_init_check(&argc, &argv))
316                         startup_notification_complete(TRUE);
317 #endif
318                 return 0;
319         }
320
321         if (cmd.status || cmd.status_full) {
322                 puts("0 Sylpheed-Claws not running.");
323                 lock_socket_remove();
324                 return 0;
325         }
326         
327         if (cmd.exit)
328                 return 0;
329 #endif
330         g_thread_init(NULL);
331         /* gdk_threads_init(); */
332
333         gtk_set_locale();
334         gtk_init(&argc, &argv);
335
336         gdk_rgb_init();
337         gtk_widget_set_default_colormap(gdk_rgb_get_colormap());
338         gtk_widget_set_default_visual(gdk_rgb_get_visual());
339
340         if (!g_thread_supported()) {
341                 g_error(_("g_thread is not supported by glib.\n"));
342         }
343
344         /* parse gtkrc files */
345         userrc = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".gtkrc-2.0",
346                              NULL);
347         gtk_rc_parse(userrc);
348         g_free(userrc);
349         userrc = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".gtk",
350                              G_DIR_SEPARATOR_S, "gtkrc-2.0", NULL);
351         gtk_rc_parse(userrc);
352         g_free(userrc);
353
354         CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
355         if (!is_dir_exist(RC_DIR)) {
356                 gboolean r = FALSE;
357                 if (is_dir_exist(OLD_GTK2_RC_DIR))
358                         r = migrate_old_config(OLD_GTK2_RC_DIR, RC_DIR);
359                 else if (is_dir_exist(OLD_GTK1_RC_DIR))
360                         r = migrate_old_config(OLD_GTK1_RC_DIR, RC_DIR);
361                 if (r == FALSE && !is_dir_exist(RC_DIR) && make_dir(RC_DIR) < 0)
362                         exit(1);
363         }
364
365         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, "gtkrc-2.0", NULL);
366         gtk_rc_parse(userrc);
367         g_free(userrc);
368
369         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
370         gtk_accel_map_load (userrc);
371         g_free(userrc);
372
373         gtk_settings_set_long_property(gtk_settings_get_default(), 
374                                        "gtk-can-change-accels",
375                                        (glong)TRUE, "XProperty");
376
377         CHDIR_RETURN_VAL_IF_FAIL(get_rc_dir(), 1);
378
379         MAKE_DIR_IF_NOT_EXIST(get_mail_base_dir());
380         MAKE_DIR_IF_NOT_EXIST(get_imap_cache_dir());
381         MAKE_DIR_IF_NOT_EXIST(get_news_cache_dir());
382         MAKE_DIR_IF_NOT_EXIST(get_mime_tmp_dir());
383         MAKE_DIR_IF_NOT_EXIST(get_tmp_dir());
384         MAKE_DIR_IF_NOT_EXIST(UIDL_DIR);
385
386         crash_file_present = is_file_exist(get_crashfile_name());
387         /* remove temporary files */
388         remove_all_files(get_tmp_dir());
389         remove_all_files(get_mime_tmp_dir());
390
391         if (is_file_exist("sylpheed.log")) {
392                 if (rename_force("sylpheed.log", "sylpheed.log.bak") < 0)
393                         FILE_OP_ERROR("sylpheed.log", "rename");
394         }
395         set_log_file("sylpheed.log");
396
397         CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
398
399         folder_system_init();
400         prefs_common_read_config();
401
402         prefs_themes_init();
403         prefs_fonts_init();
404         prefs_ext_prog_init();
405         prefs_wrapping_init();
406         prefs_compose_writing_init();
407         prefs_msg_colors_init();
408         image_viewer_init();
409         prefs_image_viewer_init();
410         prefs_quote_init();
411         prefs_summaries_init();
412         prefs_message_init();
413         prefs_other_init();
414         prefs_receive_init();
415         prefs_send_init();
416 #ifdef USE_ASPELL
417         gtkaspell_checkers_init();
418         prefs_spelling_init();
419 #endif
420         
421         sock_set_io_timeout(prefs_common.io_timeout_secs);
422 #ifdef HAVE_LIBETPAN
423         imap_main_set_timeout(prefs_common.io_timeout_secs);
424 #endif
425         prefs_actions_read_config();
426         prefs_display_header_read_config();
427         /* prefs_filtering_read_config(); */
428         addressbook_read_file();
429         renderer_read_config();
430
431         gtkut_widget_init();
432         stock_pixbuf_gdk(NULL, STOCK_PIXMAP_SYLPHEED_ICON, &icon);
433         gtk_window_set_default_icon(icon);
434
435         folderview_initialize();
436
437         mh_gtk_init();
438         imap_gtk_init();
439         news_gtk_init();
440                 
441         mainwin = main_window_create
442                 (prefs_common.sep_folder | prefs_common.sep_msg << 1);
443         folderview = mainwin->folderview;
444
445         gtk_clist_freeze(GTK_CLIST(mainwin->folderview->ctree));
446         folder_item_update_freeze();
447
448         /* register the callback of unix domain socket input */
449 #ifdef G_OS_UNIX
450         lock_socket_tag = gdk_input_add(lock_socket,
451                                         GDK_INPUT_READ | GDK_INPUT_EXCEPTION,
452                                         lock_socket_input_cb,
453                                         mainwin);
454 #endif
455
456         prefs_account_init();
457         account_read_config_all();
458
459         if (folder_read_list() < 0) {
460                 if (!run_wizard(mainwin, TRUE))
461                         exit(1);
462                 folder_write_list();
463         }
464
465         if (!account_get_list()) {
466                 if (!run_wizard(mainwin, FALSE))
467                         exit(1);
468                 account_read_config_all();
469                 if(!account_get_list())
470                         exit_sylpheed(mainwin);
471         }
472
473         main_window_popup(mainwin);
474
475 #ifdef HAVE_LIBETPAN
476         imap_main_init();
477 #endif  
478         account_set_missing_folder();
479         folder_set_missing_folders();
480         folderview_set(folderview);
481
482         prefs_matcher_read_config();
483
484         /* make one all-folder processing before using sylpheed */
485         main_window_cursor_wait(mainwin);
486         folder_func_to_all_folders(initial_processing, (gpointer *)mainwin);
487
488         /* if Sylpheed crashed, rebuild caches */
489         if (!cmd.crash && crash_file_present) {
490                 debug_print("Sylpheed-Claws crashed, checking for new messages in local folders\n");
491                 folder_item_update_thaw();
492                 folderview_check_new(NULL);
493                 folder_clean_cache_memory_force();
494                 folder_item_update_freeze();
495         }
496         /* make the crash-indicator file */
497         str_write_to_file("foo", get_crashfile_name());
498
499         addressbook_read_file();
500
501         inc_autocheck_timer_init(mainwin);
502
503         /* ignore SIGPIPE signal for preventing sudden death of program */
504 #ifdef G_OS_UNIX
505         signal(SIGPIPE, SIG_IGN);
506 #endif
507         if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
508                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
509         }
510         if (cmd.online_mode == ONLINE_MODE_ONLINE) {
511                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
512         }
513
514         if (cmd.status_folders) {
515                 g_ptr_array_free(cmd.status_folders, TRUE);
516                 cmd.status_folders = NULL;
517         }
518         if (cmd.status_full_folders) {
519                 g_ptr_array_free(cmd.status_full_folders, TRUE);
520                 cmd.status_full_folders = NULL;
521         }
522
523         sylpheed_register_idle_function(sylpheed_gtk_idle);
524
525         prefs_toolbar_init();
526
527         plugin_load_all("GTK2");
528         
529         if (plugin_get_unloaded_list() != NULL) {
530                 alertpanel_warning(_("Some plugin(s) failed to load. "
531                                      "Check the Plugins configuration "
532                                      "for more information."));
533         }
534         
535         if (!folder_have_mailbox()) {
536                 alertpanel_error(_("Sylpheed-Claws has detected a configured "
537                                    "mailbox, but could not load it. It is "
538                                    "probably provided by an out-of-date "
539                                    "external plugin. Please reinstall the "
540                                    "plugin and try again."));
541                 exit(1);
542         }
543         
544         static_mainwindow = mainwin;
545
546 #ifdef HAVE_STARTUP_NOTIFICATION
547         startup_notification_complete(FALSE);
548 #endif
549         folder_item_update_thaw();
550         gtk_clist_thaw(GTK_CLIST(mainwin->folderview->ctree));
551         main_window_cursor_normal(mainwin);
552
553         if (cmd.receive_all) {
554                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(FALSE));
555         } else if (prefs_common.chk_on_startup) {
556                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(TRUE));
557         } else if (cmd.receive) {
558                 g_timeout_add(1000, defer_check, NULL);
559         } else {
560                 gtk_widget_grab_focus(folderview->ctree);
561         }
562
563         if (cmd.compose) {
564                 open_compose_new(cmd.compose_mailto, cmd.attach_files);
565         }
566         if (cmd.attach_files) {
567                 ptr_array_free_strings(cmd.attach_files);
568                 g_ptr_array_free(cmd.attach_files, TRUE);
569                 cmd.attach_files = NULL;
570         }
571         if (cmd.subscribe) {
572                 folder_subscribe(cmd.subscribe_uri);
573         }
574
575         if (cmd.send) {
576                 send_queue();
577         }
578         
579         gtk_main();
580
581         exit_sylpheed(mainwin);
582
583         return 0;
584 }
585
586 static void save_all_caches(FolderItem *item, gpointer data)
587 {
588         if (!item->cache) {
589                 return;
590         }
591         folder_item_write_cache(item);
592 }
593
594 static void exit_sylpheed(MainWindow *mainwin)
595 {
596         gchar *filename;
597
598         debug_print("shutting down\n");
599         inc_autocheck_timer_remove();
600
601         if (prefs_common.clean_on_exit) {
602                 main_window_empty_trash(mainwin, prefs_common.ask_on_clean);
603         }
604
605         /* save prefs for opened folder */
606         if(mainwin->folderview->opened) {
607                 FolderItem *item;
608
609                 item = gtk_ctree_node_get_row_data(GTK_CTREE(mainwin->folderview->ctree), mainwin->folderview->opened);
610                 summary_save_prefs_to_folderitem(mainwin->folderview->summaryview, item);
611         }
612
613         /* save all state before exiting */
614         folder_write_list();
615         folder_func_to_all_folders(save_all_caches, NULL);
616
617         main_window_get_size(mainwin);
618         main_window_get_position(mainwin);
619         prefs_common_write_config();
620         account_write_config_all();
621         addressbook_export_to_file();
622
623         filename = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
624         gtk_accel_map_save(filename);
625         g_free(filename);
626
627         /* delete temporary files */
628         remove_all_files(get_tmp_dir());
629         remove_all_files(get_mime_tmp_dir());
630
631         close_log_file();
632
633 #ifdef HAVE_LIBETPAN
634         imap_main_done();
635 #endif
636         /* delete crashfile */
637         if (!cmd.crash)
638                 g_unlink(get_crashfile_name());
639
640         lock_socket_remove();
641
642         main_window_destroy_all();
643         
644         plugin_unload_all("GTK2");
645
646         prefs_toolbar_done();
647
648         addressbook_destroy();
649
650         prefs_themes_done();
651         prefs_fonts_done();
652         prefs_ext_prog_done();
653         prefs_wrapping_done();
654         prefs_compose_writing_done();
655         prefs_msg_colors_done();
656         prefs_image_viewer_done();
657         image_viewer_done();
658         prefs_quote_done();
659         prefs_summaries_done();
660         prefs_message_done();
661         prefs_other_done();
662         prefs_receive_done();
663         prefs_send_done();
664 #ifdef USE_ASPELL       
665         prefs_spelling_done();
666         gtkaspell_checkers_quit();
667 #endif
668         sylpheed_done();
669
670 }
671
672 static void parse_cmd_opt(int argc, char *argv[])
673 {
674         gint i;
675
676         for (i = 1; i < argc; i++) {
677                 if (!strncmp(argv[i], "--receive-all", 13)) {
678                         cmd.receive_all = TRUE;
679                 } else if (!strncmp(argv[i], "--receive", 9)) {
680                         cmd.receive = TRUE;
681                 } else if (!strncmp(argv[i], "--compose", 9)) {
682                         const gchar *p = argv[i + 1];
683
684                         cmd.compose = TRUE;
685                         cmd.compose_mailto = NULL;
686                         if (p && *p != '\0' && *p != '-') {
687                                 if (!strncmp(p, "mailto:", 7)) {
688                                         cmd.compose_mailto = p + 7;
689                                 } else {
690                                         cmd.compose_mailto = p;
691                                 }
692                                 i++;
693                         }
694                 } else if (!strncmp(argv[i], "--subscribe", 11)) {
695                         const gchar *p = argv[i + 1];
696                         if (p && *p != '\0' && *p != '-') {
697                                 cmd.subscribe = TRUE;
698                                 cmd.subscribe_uri = p;
699                         }
700                 } else if (!strncmp(argv[i], "--attach", 8)) {
701                         const gchar *p = argv[i + 1];
702                         gchar *file;
703
704                         while (p && *p != '\0' && *p != '-') {
705                                 if (!cmd.attach_files) {
706                                         cmd.attach_files = g_ptr_array_new();
707                                 }
708                                 if (*p != G_DIR_SEPARATOR) {
709                                         file = g_strconcat(sylpheed_get_startup_dir(),
710                                                            G_DIR_SEPARATOR_S,
711                                                            p, NULL);
712                                 } else {
713                                         file = g_strdup(p);
714                                 }
715                                 g_ptr_array_add(cmd.attach_files, file);
716                                 i++;
717                                 p = argv[i + 1];
718                         }
719                 } else if (!strncmp(argv[i], "--send", 6)) {
720                         cmd.send = TRUE;
721                 } else if (!strncmp(argv[i], "--version", 9)) {
722                         puts("Sylpheed-Claws version " VERSION);
723                         exit(0);
724                 } else if (!strncmp(argv[i], "--status-full", 13)) {
725                         const gchar *p = argv[i + 1];
726  
727                         cmd.status_full = TRUE;
728                         while (p && *p != '\0' && *p != '-') {
729                                 if (!cmd.status_full_folders) {
730                                         cmd.status_full_folders =
731                                                 g_ptr_array_new();
732                                 }
733                                 g_ptr_array_add(cmd.status_full_folders,
734                                                 g_strdup(p));
735                                 i++;
736                                 p = argv[i + 1];
737                         }
738                 } else if (!strncmp(argv[i], "--status", 8)) {
739                         const gchar *p = argv[i + 1];
740  
741                         cmd.status = TRUE;
742                         while (p && *p != '\0' && *p != '-') {
743                                 if (!cmd.status_folders)
744                                         cmd.status_folders = g_ptr_array_new();
745                                 g_ptr_array_add(cmd.status_folders,
746                                                 g_strdup(p));
747                                 i++;
748                                 p = argv[i + 1];
749                         }
750                 } else if (!strncmp(argv[i], "--online", 8)) {
751                         cmd.online_mode = ONLINE_MODE_ONLINE;
752                 } else if (!strncmp(argv[i], "--offline", 9)) {
753                         cmd.online_mode = ONLINE_MODE_OFFLINE;
754                 } else if (!strncmp(argv[i], "--help", 6)) {
755                         gchar *base = g_path_get_basename(argv[0]);
756                         g_print(_("Usage: %s [OPTION]...\n"), base);
757
758                         g_print("%s\n", _("  --compose [address]    open composition window"));
759                         g_print("%s\n", _("  --subscribe [uri]      subscribe to the given URI if possible"));
760                         g_print("%s\n", _("  --attach file1 [file2]...\n"
761                                   "                         open composition window with specified files\n"
762                                   "                         attached"));
763                         g_print("%s\n", _("  --receive              receive new messages"));
764                         g_print("%s\n", _("  --receive-all          receive new messages of all accounts"));
765                         g_print("%s\n", _("  --send                 send all queued messages"));
766                         g_print("%s\n", _("  --status [folder]...   show the total number of messages"));
767                         g_print("%s\n", _("  --status-full [folder]...\n"
768                                "                         show the status of each folder"));
769                         g_print("%s\n", _("  --online               switch to online mode"));
770                         g_print("%s\n", _("  --offline              switch to offline mode"));
771                         g_print("%s\n", _("  --exit                 exit Sylpheed-Claws"));
772                         g_print("%s\n", _("  --debug                debug mode"));
773                         g_print("%s\n", _("  --help                 display this help and exit"));
774                         g_print("%s\n", _("  --version              output version information and exit"));
775                         g_print("%s\n", _("  --config-dir           output configuration directory"));
776
777                         g_free(base);
778                         exit(1);
779                 } else if (!strncmp(argv[i], "--crash", 7)) {
780                         cmd.crash = TRUE;
781                         cmd.crash_params = g_strdup(argv[i + 1]);
782                         i++;
783                 } else if (!strncmp(argv[i], "--config-dir", sizeof "--config-dir" - 1)) {
784                         puts(RC_DIR);
785                         exit(0);
786                 } else if (!strncmp(argv[i], "--exit", 6)) {
787                         cmd.exit = TRUE;
788                 } else if (i == 1 && argc == 2) {
789                         /* only one parameter. Do something intelligent about it */
790                         if (strstr(argv[i], "@") && !strstr(argv[i], "://")) {
791                                 const gchar *p = argv[i];
792
793                                 cmd.compose = TRUE;
794                                 cmd.compose_mailto = NULL;
795                                 if (p && *p != '\0' && *p != '-') {
796                                         if (!strncmp(p, "mailto:", 7)) {
797                                                 cmd.compose_mailto = p + 7;
798                                         } else {
799                                                 cmd.compose_mailto = p;
800                                         }
801                                 }
802                         } else if (strstr(argv[i], "://")) {
803                                 const gchar *p = argv[i];
804                                 if (p && *p != '\0' && *p != '-') {
805                                         cmd.subscribe = TRUE;
806                                         cmd.subscribe_uri = p;
807                                 }
808                         }
809                 }
810                 
811         }
812
813         if (cmd.attach_files && cmd.compose == FALSE) {
814                 cmd.compose = TRUE;
815                 cmd.compose_mailto = NULL;
816         }
817 }
818
819 static gint get_queued_message_num(void)
820 {
821         FolderItem *queue;
822
823         queue = folder_get_default_queue();
824         if (!queue) {
825                 return -1;
826         }
827
828         folder_item_scan(queue);
829         return queue->total_msgs;
830 }
831
832 static void initial_processing(FolderItem *item, gpointer data)
833 {
834         MainWindow *mainwin = (MainWindow *)data;
835         gchar *buf;
836
837         g_return_if_fail(item);
838         buf = g_strdup_printf(_("Processing (%s)..."), 
839                               item->path 
840                               ? item->path 
841                               : _("top level folder"));
842         debug_print("%s\n", buf);
843         g_free(buf);
844
845         
846         if (item->prefs->enable_processing) {
847                 folder_item_apply_processing(item);
848         }
849
850         debug_print("done.\n");
851         STATUSBAR_POP(mainwin);
852 }
853
854 static void draft_all_messages(void)
855 {
856         GList *compose_list = NULL;
857         
858         while ((compose_list = compose_get_compose_list()) != NULL) {
859                 Compose *c = (Compose*)compose_list->data;
860                 compose_draft(c);
861         }       
862 }
863
864 gboolean clean_quit(gpointer data)
865 {
866         static gboolean firstrun = TRUE;
867
868         if (!firstrun) {
869                 return FALSE;
870         }
871         firstrun = FALSE;
872
873         /*!< Good idea to have the main window stored in a 
874          *   static variable so we can check that variable
875          *   to see if we're really allowed to do things
876          *   that actually the spawner is supposed to 
877          *   do (like: sending mail, composing messages).
878          *   Because, really, if we're the spawnee, and
879          *   we touch GTK stuff, we're hosed. See the 
880          *   next fixme. */
881
882         /* FIXME: Use something else to signal that we're
883          * in the original spawner, and not in a spawned
884          * child. */
885         if (!static_mainwindow) {
886                 return FALSE;
887         }
888                 
889         draft_all_messages();
890
891         exit_sylpheed(static_mainwindow);
892         exit(0);
893
894         return FALSE;
895 }
896
897 void app_will_exit(GtkWidget *widget, gpointer data)
898 {
899         MainWindow *mainwin = data;
900
901         if (compose_get_compose_list()) {
902                 gint val = alertpanel(_("Really quit?"),
903                                _("Composing message exists."),
904                                _("_Save to Draft"), _("_Discard them"), _("Do_n't quit"));
905                 switch (val) {
906                         case G_ALERTOTHER:
907                                 return;
908                         case G_ALERTALTERNATE:
909                                 break;
910                         default:
911                                 draft_all_messages();
912                 }
913
914                 manage_window_focus_in(mainwin->window, NULL, NULL);
915         }
916
917         if (prefs_common.warn_queued_on_exit && get_queued_message_num() > 0) {
918                 if (alertpanel(_("Queued messages"),
919                                _("Some unsent messages are queued. Exit now?"),
920                                GTK_STOCK_CANCEL, GTK_STOCK_OK, NULL)
921                     != G_ALERTALTERNATE) {
922                         return;
923                 }
924                 manage_window_focus_in(mainwin->window, NULL, NULL);
925         }
926
927         sock_cleanup();
928
929         gtk_main_quit();
930 }
931
932 /*
933  * CLAWS: want this public so crash dialog can delete the
934  * lock file too
935  */
936 #ifndef CLAWS
937 static
938 #endif
939 gchar *get_socket_name(void)
940 {
941         static gchar *filename = NULL;
942
943         if (filename == NULL) {
944                 filename = g_strdup_printf("%s%csylpheed-claws-%d",
945                                            g_get_tmp_dir(), G_DIR_SEPARATOR,
946 #if HAVE_GETUID
947                                            getuid());
948 #else
949                                            0);                                          
950 #endif
951         }
952
953         return filename;
954 }
955
956 static gchar *get_crashfile_name(void)
957 {
958         static gchar *filename = NULL;
959
960         if (filename == NULL) {
961                 filename = g_strdup_printf("%s%csylpheed-crashed",
962                                            get_tmp_dir(), G_DIR_SEPARATOR);
963         }
964
965         return filename;
966 }
967
968 static gint prohibit_duplicate_launch(void)
969 {
970         gint uxsock;
971         gchar *path;
972
973         path = get_socket_name();
974         uxsock = fd_connect_unix(path);
975         if (uxsock < 0) {
976                 g_unlink(path);
977                 return fd_open_unix(path);
978         }
979
980         /* remote command mode */
981
982         debug_print("another Sylpheed-Claws instance is already running.\n");
983
984         if (cmd.receive_all) {
985                 fd_write_all(uxsock, "receive_all\n", 12);
986         } else if (cmd.receive) {
987                 fd_write_all(uxsock, "receive\n", 8);
988         } else if (cmd.compose && cmd.attach_files) {
989                 gchar *str, *compose_str;
990                 gint i;
991
992                 if (cmd.compose_mailto) {
993                         compose_str = g_strdup_printf("compose_attach %s\n",
994                                                       cmd.compose_mailto);
995                 } else {
996                         compose_str = g_strdup("compose_attach\n");
997                 }
998
999                 fd_write_all(uxsock, compose_str, strlen(compose_str));
1000                 g_free(compose_str);
1001
1002                 for (i = 0; i < cmd.attach_files->len; i++) {
1003                         str = g_ptr_array_index(cmd.attach_files, i);
1004                         fd_write_all(uxsock, str, strlen(str));
1005                         fd_write_all(uxsock, "\n", 1);
1006                 }
1007
1008                 fd_write_all(uxsock, ".\n", 2);
1009         } else if (cmd.compose) {
1010                 gchar *compose_str;
1011
1012                 if (cmd.compose_mailto) {
1013                         compose_str = g_strdup_printf
1014                                 ("compose %s\n", cmd.compose_mailto);
1015                 } else {
1016                         compose_str = g_strdup("compose\n");
1017                 }
1018
1019                 fd_write_all(uxsock, compose_str, strlen(compose_str));
1020                 g_free(compose_str);
1021         } else if (cmd.subscribe) {
1022                 gchar *str = g_strdup_printf("subscribe %s\n", cmd.subscribe_uri);
1023                 fd_write_all(uxsock, str, strlen(str));
1024                 g_free(str);
1025         } else if (cmd.send) {
1026                 fd_write_all(uxsock, "send\n", 5);
1027         } else if (cmd.online_mode == ONLINE_MODE_ONLINE) {
1028                 fd_write(uxsock, "online\n", 6);
1029         } else if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
1030                 fd_write(uxsock, "offline\n", 7);
1031         } else if (cmd.status || cmd.status_full) {
1032                 gchar buf[BUFFSIZE];
1033                 gint i;
1034                 const gchar *command;
1035                 GPtrArray *folders;
1036                 gchar *folder;
1037  
1038                 command = cmd.status_full ? "status-full\n" : "status\n";
1039                 folders = cmd.status_full ? cmd.status_full_folders :
1040                         cmd.status_folders;
1041  
1042                 fd_write_all(uxsock, command, strlen(command));
1043                 for (i = 0; folders && i < folders->len; ++i) {
1044                         folder = g_ptr_array_index(folders, i);
1045                         fd_write_all(uxsock, folder, strlen(folder));
1046                         fd_write_all(uxsock, "\n", 1);
1047                 }
1048                 fd_write_all(uxsock, ".\n", 2);
1049                 for (;;) {
1050                         fd_gets(uxsock, buf, sizeof(buf));
1051                         if (!strncmp(buf, ".\n", 2)) break;
1052                         fputs(buf, stdout);
1053                 }
1054         } else if (cmd.exit) {
1055                 fd_write_all(uxsock, "exit\n", 5);
1056         } else
1057                 fd_write_all(uxsock, "popup\n", 6);
1058
1059         fd_close(uxsock);
1060         return -1;
1061 }
1062
1063 static gint lock_socket_remove(void)
1064 {
1065 #ifdef G_OS_UNIX
1066         gchar *filename;
1067
1068         if (lock_socket < 0) {
1069                 return -1;
1070         }
1071
1072         if (lock_socket_tag > 0) {
1073                 gdk_input_remove(lock_socket_tag);
1074         }
1075         fd_close(lock_socket);
1076         filename = get_socket_name();
1077         g_unlink(filename);
1078 #endif
1079
1080         return 0;
1081 }
1082
1083 static GPtrArray *get_folder_item_list(gint sock)
1084 {
1085         gchar buf[BUFFSIZE];
1086         FolderItem *item;
1087         GPtrArray *folders = NULL;
1088
1089         for (;;) {
1090                 fd_gets(sock, buf, sizeof(buf));
1091                 if (!strncmp(buf, ".\n", 2)) {
1092                         break;
1093                 }
1094                 strretchomp(buf);
1095                 if (!folders) {
1096                         folders = g_ptr_array_new();
1097                 }
1098                 item = folder_find_item_from_identifier(buf);
1099                 if (item) {
1100                         g_ptr_array_add(folders, item);
1101                 } else {
1102                         g_warning("no such folder: %s\n", buf);
1103                 }
1104         }
1105
1106         return folders;
1107 }
1108
1109 static void lock_socket_input_cb(gpointer data,
1110                                  gint source,
1111                                  GdkInputCondition condition)
1112 {
1113         MainWindow *mainwin = (MainWindow *)data;
1114         gint sock;
1115         gchar buf[BUFFSIZE];
1116
1117         sock = fd_accept(source);
1118         fd_gets(sock, buf, sizeof(buf));
1119
1120         if (!strncmp(buf, "popup", 5)) {
1121                 main_window_popup(mainwin);
1122         } else if (!strncmp(buf, "receive_all", 11)) {
1123                 inc_all_account_mail(mainwin, FALSE,
1124                                      prefs_common.newmail_notify_manu);
1125         } else if (!strncmp(buf, "receive", 7)) {
1126                 inc_mail(mainwin, prefs_common.newmail_notify_manu);
1127         } else if (!strncmp(buf, "compose_attach", 14)) {
1128                 GPtrArray *files;
1129                 gchar *mailto;
1130
1131                 mailto = g_strdup(buf + strlen("compose_attach") + 1);
1132                 files = g_ptr_array_new();
1133                 while (fd_gets(sock, buf, sizeof(buf)) > 0) {
1134                         if (buf[0] == '.' && buf[1] == '\n') {
1135                                 break;
1136                         }
1137                         strretchomp(buf);
1138                         g_ptr_array_add(files, g_strdup(buf));
1139                 }
1140                 open_compose_new(mailto, files);
1141                 ptr_array_free_strings(files);
1142                 g_ptr_array_free(files, TRUE);
1143                 g_free(mailto);
1144         } else if (!strncmp(buf, "compose", 7)) {
1145                 open_compose_new(buf + strlen("compose") + 1, NULL);
1146         } else if (!strncmp(buf, "subscribe", 9)) {
1147                 main_window_popup(mainwin);
1148                 folder_subscribe(buf + strlen("subscribe") + 1);
1149         } else if (!strncmp(buf, "send", 4)) {
1150                 send_queue();
1151         } else if (!strncmp(buf, "online", 6)) {
1152                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
1153         } else if (!strncmp(buf, "offline", 7)) {
1154                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
1155         } else if (!strncmp(buf, "status-full", 11) ||
1156                    !strncmp(buf, "status", 6)) {
1157                 gchar *status;
1158                 GPtrArray *folders;
1159  
1160                 folders = get_folder_item_list(sock);
1161                 status = folder_get_status
1162                         (folders, !strncmp(buf, "status-full", 11));
1163                 fd_write_all(sock, status, strlen(status));
1164                 fd_write_all(sock, ".\n", 2);
1165                 g_free(status);
1166                 if (folders) g_ptr_array_free(folders, TRUE);
1167         } else if (!strncmp(buf, "exit", 4)) {
1168                 app_will_exit(NULL, mainwin);
1169         }
1170
1171         fd_close(sock);
1172 }
1173
1174 static void open_compose_new(const gchar *address, GPtrArray *attach_files)
1175 {
1176         gchar *addr = NULL;
1177
1178         if (address) {
1179                 Xstrdup_a(addr, address, return);
1180                 g_strstrip(addr);
1181         }
1182
1183         compose_new(NULL, addr, attach_files);
1184 }
1185
1186 static void send_queue(void)
1187 {
1188         GList *list;
1189
1190         for (list = folder_get_list(); list != NULL; list = list->next) {
1191                 Folder *folder = list->data;
1192
1193                 if (folder->queue) {
1194                         gint res = procmsg_send_queue
1195                                 (folder->queue, prefs_common.savemsg);
1196
1197                         if (res < 0) {
1198                                 alertpanel_error(_("Some errors occurred while sending queued messages."));
1199                         }
1200                         if (res) {
1201                                 folder_item_scan(folder->queue);
1202                         }
1203                 }
1204         }
1205 }
1206
1207 static void quit_signal_handler(int sig)
1208 {
1209         debug_print("Quitting on signal %d\n", sig);
1210
1211         g_timeout_add(0, clean_quit, NULL);
1212 }
1213
1214 static void install_basic_sighandlers()
1215 {
1216 #ifndef G_OS_WIN32
1217         sigset_t    mask;
1218         struct sigaction act;
1219
1220         sigemptyset(&mask);
1221
1222 #ifdef SIGTERM
1223         sigaddset(&mask, SIGTERM);
1224 #endif
1225 #ifdef SIGINT
1226         sigaddset(&mask, SIGINT);
1227 #endif
1228 #ifdef SIGHUP
1229         sigaddset(&mask, SIGHUP);
1230 #endif
1231
1232         act.sa_handler = quit_signal_handler;
1233         act.sa_mask    = mask;
1234         act.sa_flags   = 0;
1235
1236 #ifdef SIGTERM
1237         sigaction(SIGTERM, &act, 0);
1238 #endif
1239 #ifdef SIGINT
1240         sigaction(SIGINT, &act, 0);
1241 #endif  
1242 #ifdef SIGHUP
1243         sigaction(SIGHUP, &act, 0);
1244 #endif  
1245
1246         sigprocmask(SIG_UNBLOCK, &mask, 0);
1247 #endif /* !G_OS_WIN32 */
1248 }