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