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