2006-02-16 [cleroy] 2.0.0cvs59
[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         if (plugin_get_unloaded_list() != NULL) {
525                 alertpanel_warning(_("Some plugin(s) failed to load. "
526                                      "Check the Plugins configuration "
527                                      "for more information."));
528         }
529         
530         if (!folder_have_mailbox()) {
531                 alertpanel_error(_("Sylpheed-Claws has detected a configured "
532                                    "mailbox, but could not load it. It is "
533                                    "probably provided by an out-of-date "
534                                    "external plugin. Please reinstall the "
535                                    "plugin and try again."));
536                 exit(1);
537         }
538         
539         static_mainwindow = mainwin;
540
541 #ifdef HAVE_STARTUP_NOTIFICATION
542         startup_notification_complete(FALSE);
543 #endif
544         folder_item_update_thaw();
545         gtk_clist_thaw(GTK_CLIST(mainwin->folderview->ctree));
546         main_window_cursor_normal(mainwin);
547
548         if (cmd.receive_all)
549                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(FALSE));
550         else if (prefs_common.chk_on_startup)
551                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(TRUE));
552         else if (cmd.receive)
553                 g_timeout_add(1000, defer_check, NULL);
554         else
555                 gtk_widget_grab_focus(folderview->ctree);
556
557         if (cmd.compose)
558                 open_compose_new(cmd.compose_mailto, cmd.attach_files);
559         if (cmd.attach_files) {
560                 ptr_array_free_strings(cmd.attach_files);
561                 g_ptr_array_free(cmd.attach_files, TRUE);
562                 cmd.attach_files = NULL;
563         }
564         if (cmd.subscribe)
565                 folder_subscribe(cmd.subscribe_uri);
566
567         if (cmd.send)
568                 send_queue();
569         
570         gtk_main();
571
572         exit_sylpheed(mainwin);
573
574         return 0;
575 }
576
577 static void save_all_caches(FolderItem *item, gpointer data)
578 {
579         if (!item->cache)
580                 return;
581         folder_item_write_cache(item);
582 }
583
584 static void exit_sylpheed(MainWindow *mainwin)
585 {
586         gchar *filename;
587
588         debug_print("shutting down\n");
589         inc_autocheck_timer_remove();
590
591         if (prefs_common.clean_on_exit)
592                 main_window_empty_trash(mainwin, prefs_common.ask_on_clean);
593
594         /* save prefs for opened folder */
595         if(mainwin->folderview->opened)
596         {
597                 FolderItem *item;
598
599                 item = gtk_ctree_node_get_row_data(GTK_CTREE(mainwin->folderview->ctree), mainwin->folderview->opened);
600                 summary_save_prefs_to_folderitem(mainwin->folderview->summaryview, item);
601         }
602
603         /* save all state before exiting */
604         folder_write_list();
605         folder_func_to_all_folders(save_all_caches, NULL);
606
607         main_window_get_size(mainwin);
608         main_window_get_position(mainwin);
609         prefs_common_write_config();
610         account_write_config_all();
611         addressbook_export_to_file();
612
613         filename = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
614         gtk_accel_map_save(filename);
615         g_free(filename);
616
617         /* delete temporary files */
618         remove_all_files(get_tmp_dir());
619         remove_all_files(get_mime_tmp_dir());
620
621         close_log_file();
622
623 #ifdef HAVE_LIBETPAN
624         imap_main_done();
625 #endif
626         /* delete crashfile */
627         if (!cmd.crash)
628                 g_unlink(get_crashfile_name());
629
630         lock_socket_remove();
631
632         main_window_destroy_all();
633         
634         plugin_unload_all("GTK2");
635
636         prefs_toolbar_done();
637
638         addressbook_destroy();
639
640         prefs_themes_done();
641         prefs_fonts_done();
642         prefs_ext_prog_done();
643         prefs_wrapping_done();
644         prefs_compose_writing_done();
645         prefs_msg_colors_done();
646         prefs_image_viewer_done();
647         image_viewer_done();
648         prefs_quote_done();
649         prefs_summaries_done();
650         prefs_message_done();
651         prefs_other_done();
652         prefs_receive_done();
653         prefs_send_done();
654 #ifdef USE_ASPELL       
655         prefs_spelling_done();
656         gtkaspell_checkers_quit();
657 #endif
658         sylpheed_done();
659
660 }
661
662 static void parse_cmd_opt(int argc, char *argv[])
663 {
664         gint i;
665
666         for (i = 1; i < argc; i++) {
667                 if (!strncmp(argv[i], "--receive-all", 13))
668                         cmd.receive_all = TRUE;
669                 else if (!strncmp(argv[i], "--receive", 9))
670                         cmd.receive = TRUE;
671                 else if (!strncmp(argv[i], "--compose", 9)) {
672                         const gchar *p = argv[i + 1];
673
674                         cmd.compose = TRUE;
675                         cmd.compose_mailto = NULL;
676                         if (p && *p != '\0' && *p != '-') {
677                                 if (!strncmp(p, "mailto:", 7))
678                                         cmd.compose_mailto = p + 7;
679                                 else
680                                         cmd.compose_mailto = p;
681                                 i++;
682                         }
683                 } else if (!strncmp(argv[i], "--subscribe", 11)) {
684                         const gchar *p = argv[i + 1];
685                         if (p && *p != '\0' && *p != '-') {
686                                 cmd.subscribe = TRUE;
687                                 cmd.subscribe_uri = p;
688                         }
689                 } else if (!strncmp(argv[i], "--attach", 8)) {
690                         const gchar *p = argv[i + 1];
691                         gchar *file;
692
693                         while (p && *p != '\0' && *p != '-') {
694                                 if (!cmd.attach_files)
695                                         cmd.attach_files = g_ptr_array_new();
696                                 if (*p != G_DIR_SEPARATOR)
697                                         file = g_strconcat(sylpheed_get_startup_dir(),
698                                                            G_DIR_SEPARATOR_S,
699                                                            p, NULL);
700                                 else
701                                         file = g_strdup(p);
702                                 g_ptr_array_add(cmd.attach_files, file);
703                                 i++;
704                                 p = argv[i + 1];
705                         }
706                 } else if (!strncmp(argv[i], "--send", 6)) {
707                         cmd.send = TRUE;
708                 } else if (!strncmp(argv[i], "--version", 9)) {
709                         puts("Sylpheed-Claws version " VERSION);
710                         exit(0);
711                 } else if (!strncmp(argv[i], "--status-full", 13)) {
712                         const gchar *p = argv[i + 1];
713  
714                         cmd.status_full = TRUE;
715                         while (p && *p != '\0' && *p != '-') {
716                                 if (!cmd.status_full_folders)
717                                         cmd.status_full_folders =
718                                                 g_ptr_array_new();
719                                 g_ptr_array_add(cmd.status_full_folders,
720                                                 g_strdup(p));
721                                 i++;
722                                 p = argv[i + 1];
723                         }
724                 } else if (!strncmp(argv[i], "--status", 8)) {
725                         const gchar *p = argv[i + 1];
726  
727                         cmd.status = TRUE;
728                         while (p && *p != '\0' && *p != '-') {
729                                 if (!cmd.status_folders)
730                                         cmd.status_folders = g_ptr_array_new();
731                                 g_ptr_array_add(cmd.status_folders,
732                                                 g_strdup(p));
733                                 i++;
734                                 p = argv[i + 1];
735                         }
736                 } else if (!strncmp(argv[i], "--online", 8)) {
737                         cmd.online_mode = ONLINE_MODE_ONLINE;
738                 } else if (!strncmp(argv[i], "--offline", 9)) {
739                         cmd.online_mode = ONLINE_MODE_OFFLINE;
740                 } else if (!strncmp(argv[i], "--help", 6)) {
741                         gchar *base = g_path_get_basename(argv[0]);
742                         g_print(_("Usage: %s [OPTION]...\n"), base);
743
744                         g_print("%s\n", _("  --compose [address]    open composition window"));
745                         g_print("%s\n", _("  --subscribe [uri]      subscribe to the given URI if possible"));
746                         g_print("%s\n", _("  --attach file1 [file2]...\n"
747                                   "                         open composition window with specified files\n"
748                                   "                         attached"));
749                         g_print("%s\n", _("  --receive              receive new messages"));
750                         g_print("%s\n", _("  --receive-all          receive new messages of all accounts"));
751                         g_print("%s\n", _("  --send                 send all queued messages"));
752                         g_print("%s\n", _("  --status [folder]...   show the total number of messages"));
753                         g_print("%s\n", _("  --status-full [folder]...\n"
754                                "                         show the status of each folder"));
755                         g_print("%s\n", _("  --online               switch to online mode"));
756                         g_print("%s\n", _("  --offline              switch to offline mode"));
757                         g_print("%s\n", _("  --exit                 exit Sylpheed-Claws"));
758                         g_print("%s\n", _("  --debug                debug mode"));
759                         g_print("%s\n", _("  --help                 display this help and exit"));
760                         g_print("%s\n", _("  --version              output version information and exit"));
761                         g_print("%s\n", _("  --config-dir           output configuration directory"));
762
763                         g_free(base);
764                         exit(1);
765                 } else if (!strncmp(argv[i], "--crash", 7)) {
766                         cmd.crash = TRUE;
767                         cmd.crash_params = g_strdup(argv[i + 1]);
768                         i++;
769                 } else if (!strncmp(argv[i], "--config-dir", sizeof "--config-dir" - 1)) {
770                         puts(RC_DIR);
771                         exit(0);
772                 } else if (!strncmp(argv[i], "--exit", 6)) {
773                         cmd.exit = TRUE;
774                 } else if (i == 1 && argc == 2) {
775                         /* only one parameter. Do something intelligent about it */
776                         if (strstr(argv[i], "@") && !strstr(argv[i], "://")) {
777                                 const gchar *p = argv[i];
778
779                                 cmd.compose = TRUE;
780                                 cmd.compose_mailto = NULL;
781                                 if (p && *p != '\0' && *p != '-') {
782                                         if (!strncmp(p, "mailto:", 7))
783                                                 cmd.compose_mailto = p + 7;
784                                         else
785                                                 cmd.compose_mailto = p;
786                                 }
787                         } else if (strstr(argv[i], "://")) {
788                                 const gchar *p = argv[i];
789                                 if (p && *p != '\0' && *p != '-') {
790                                         cmd.subscribe = TRUE;
791                                         cmd.subscribe_uri = p;
792                                 }
793                         }
794                 }
795                 
796         }
797
798         if (cmd.attach_files && cmd.compose == FALSE) {
799                 cmd.compose = TRUE;
800                 cmd.compose_mailto = NULL;
801         }
802 }
803
804 static gint get_queued_message_num(void)
805 {
806         FolderItem *queue;
807
808         queue = folder_get_default_queue();
809         if (!queue) return -1;
810
811         folder_item_scan(queue);
812         return queue->total_msgs;
813 }
814
815 static void initial_processing(FolderItem *item, gpointer data)
816 {
817         MainWindow *mainwin = (MainWindow *)data;
818         gchar *buf;
819
820         g_return_if_fail(item);
821         buf = g_strdup_printf(_("Processing (%s)..."), 
822                               item->path 
823                               ? item->path 
824                               : _("top level folder"));
825         debug_print("%s\n", buf);
826         g_free(buf);
827
828         
829         if (item->prefs->enable_processing)
830                 folder_item_apply_processing(item);
831
832         debug_print("done.\n");
833         STATUSBAR_POP(mainwin);
834 }
835
836 static void draft_all_messages(void)
837 {
838         GList *compose_list = NULL;
839         
840         while ((compose_list = compose_get_compose_list()) != NULL) {
841                 Compose *c = (Compose*)compose_list->data;
842                 compose_draft(c);
843         }       
844 }
845
846 gboolean clean_quit(gpointer data)
847 {
848         static gboolean firstrun = TRUE;
849
850         if (!firstrun)
851                 return FALSE;
852         firstrun = FALSE;
853
854         /*!< Good idea to have the main window stored in a 
855          *   static variable so we can check that variable
856          *   to see if we're really allowed to do things
857          *   that actually the spawner is supposed to 
858          *   do (like: sending mail, composing messages).
859          *   Because, really, if we're the spawnee, and
860          *   we touch GTK stuff, we're hosed. See the 
861          *   next fixme. */
862
863         /* FIXME: Use something else to signal that we're
864          * in the original spawner, and not in a spawned
865          * child. */
866         if (!static_mainwindow) 
867                 return FALSE;
868                 
869         draft_all_messages();
870
871         exit_sylpheed(static_mainwindow);
872         exit(0);
873
874         return FALSE;
875 }
876
877 void app_will_exit(GtkWidget *widget, gpointer data)
878 {
879         MainWindow *mainwin = data;
880
881         if (compose_get_compose_list()) {
882                 gint val = alertpanel(_("Really quit?"),
883                                _("Composing message exists."),
884                                _("_Save to Draft"), _("_Discard them"), _("Do_n't quit"));
885                 switch (val) {
886                         case G_ALERTOTHER:
887                                 return;
888                         case G_ALERTALTERNATE:
889                                 break;
890                         default:
891                                 draft_all_messages();
892                 }
893
894                 manage_window_focus_in(mainwin->window, NULL, NULL);
895         }
896
897         if (prefs_common.warn_queued_on_exit && get_queued_message_num() > 0) {
898                 if (alertpanel(_("Queued messages"),
899                                _("Some unsent messages are queued. Exit now?"),
900                                GTK_STOCK_CANCEL, GTK_STOCK_OK, NULL)
901                     != G_ALERTALTERNATE)
902                         return;
903                 manage_window_focus_in(mainwin->window, NULL, NULL);
904         }
905
906         sock_cleanup();
907
908         gtk_main_quit();
909 }
910
911 /*
912  * CLAWS: want this public so crash dialog can delete the
913  * lock file too
914  */
915 #ifndef CLAWS
916 static
917 #endif
918 gchar *get_socket_name(void)
919 {
920         static gchar *filename = NULL;
921
922         if (filename == NULL) {
923                 filename = g_strdup_printf("%s%csylpheed-claws-%d",
924                                            g_get_tmp_dir(), G_DIR_SEPARATOR,
925 #if HAVE_GETUID
926                                            getuid());
927 #else
928                                            0);                                          
929 #endif
930         }
931
932         return filename;
933 }
934
935 static gchar *get_crashfile_name(void)
936 {
937         static gchar *filename = NULL;
938
939         if (filename == NULL) {
940                 filename = g_strdup_printf("%s%csylpheed-crashed",
941                                            get_tmp_dir(), G_DIR_SEPARATOR);
942         }
943
944         return filename;
945 }
946
947 static gint prohibit_duplicate_launch(void)
948 {
949         gint uxsock;
950         gchar *path;
951
952         path = get_socket_name();
953         uxsock = fd_connect_unix(path);
954         if (uxsock < 0) {
955                 g_unlink(path);
956                 return fd_open_unix(path);
957         }
958
959         /* remote command mode */
960
961         debug_print("another Sylpheed-Claws instance is already running.\n");
962
963         if (cmd.receive_all)
964                 fd_write_all(uxsock, "receive_all\n", 12);
965         else if (cmd.receive)
966                 fd_write_all(uxsock, "receive\n", 8);
967         else if (cmd.compose && cmd.attach_files) {
968                 gchar *str, *compose_str;
969                 gint i;
970
971                 if (cmd.compose_mailto)
972                         compose_str = g_strdup_printf("compose_attach %s\n",
973                                                       cmd.compose_mailto);
974                 else
975                         compose_str = g_strdup("compose_attach\n");
976
977                 fd_write_all(uxsock, compose_str, strlen(compose_str));
978                 g_free(compose_str);
979
980                 for (i = 0; i < cmd.attach_files->len; i++) {
981                         str = g_ptr_array_index(cmd.attach_files, i);
982                         fd_write_all(uxsock, str, strlen(str));
983                         fd_write_all(uxsock, "\n", 1);
984                 }
985
986                 fd_write_all(uxsock, ".\n", 2);
987         } else if (cmd.compose) {
988                 gchar *compose_str;
989
990                 if (cmd.compose_mailto)
991                         compose_str = g_strdup_printf
992                                 ("compose %s\n", cmd.compose_mailto);
993                 else
994                         compose_str = g_strdup("compose\n");
995
996                 fd_write_all(uxsock, compose_str, strlen(compose_str));
997                 g_free(compose_str);
998         } else if (cmd.subscribe) {
999                 gchar *str = g_strdup_printf("subscribe %s\n", cmd.subscribe_uri);
1000                 fd_write_all(uxsock, str, strlen(str));
1001                 g_free(str);
1002         } else if (cmd.send) {
1003                 fd_write_all(uxsock, "send\n", 5);
1004         } else if (cmd.online_mode == ONLINE_MODE_ONLINE) {
1005                 fd_write(uxsock, "online\n", 6);
1006         } else if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
1007                 fd_write(uxsock, "offline\n", 7);
1008         } else if (cmd.status || cmd.status_full) {
1009                 gchar buf[BUFFSIZE];
1010                 gint i;
1011                 const gchar *command;
1012                 GPtrArray *folders;
1013                 gchar *folder;
1014  
1015                 command = cmd.status_full ? "status-full\n" : "status\n";
1016                 folders = cmd.status_full ? cmd.status_full_folders :
1017                         cmd.status_folders;
1018  
1019                 fd_write_all(uxsock, command, strlen(command));
1020                 for (i = 0; folders && i < folders->len; ++i) {
1021                         folder = g_ptr_array_index(folders, i);
1022                         fd_write_all(uxsock, folder, strlen(folder));
1023                         fd_write_all(uxsock, "\n", 1);
1024                 }
1025                 fd_write_all(uxsock, ".\n", 2);
1026                 for (;;) {
1027                         fd_gets(uxsock, buf, sizeof(buf));
1028                         if (!strncmp(buf, ".\n", 2)) break;
1029                         fputs(buf, stdout);
1030                 }
1031         } else if (cmd.exit) {
1032                 fd_write_all(uxsock, "exit\n", 5);
1033         } else
1034                 fd_write_all(uxsock, "popup\n", 6);
1035
1036         fd_close(uxsock);
1037         return -1;
1038 }
1039
1040 static gint lock_socket_remove(void)
1041 {
1042 #ifdef G_OS_UNIX
1043         gchar *filename;
1044
1045         if (lock_socket < 0) return -1;
1046
1047         if (lock_socket_tag > 0)
1048                 gdk_input_remove(lock_socket_tag);
1049         fd_close(lock_socket);
1050         filename = get_socket_name();
1051         g_unlink(filename);
1052 #endif
1053
1054         return 0;
1055 }
1056
1057 static GPtrArray *get_folder_item_list(gint sock)
1058 {
1059         gchar buf[BUFFSIZE];
1060         FolderItem *item;
1061         GPtrArray *folders = NULL;
1062
1063         for (;;) {
1064                 fd_gets(sock, buf, sizeof(buf));
1065                 if (!strncmp(buf, ".\n", 2)) break;
1066                 strretchomp(buf);
1067                 if (!folders) folders = g_ptr_array_new();
1068                 item = folder_find_item_from_identifier(buf);
1069                 if (item)
1070                         g_ptr_array_add(folders, item);
1071                 else
1072                         g_warning("no such folder: %s\n", buf);
1073         }
1074
1075         return folders;
1076 }
1077
1078 static void lock_socket_input_cb(gpointer data,
1079                                  gint source,
1080                                  GdkInputCondition condition)
1081 {
1082         MainWindow *mainwin = (MainWindow *)data;
1083         gint sock;
1084         gchar buf[BUFFSIZE];
1085
1086         sock = fd_accept(source);
1087         fd_gets(sock, buf, sizeof(buf));
1088
1089         if (!strncmp(buf, "popup", 5)) {
1090                 main_window_popup(mainwin);
1091         } else if (!strncmp(buf, "receive_all", 11)) {
1092                 inc_all_account_mail(mainwin, FALSE,
1093                                      prefs_common.newmail_notify_manu);
1094         } else if (!strncmp(buf, "receive", 7)) {
1095                 inc_mail(mainwin, prefs_common.newmail_notify_manu);
1096         } else if (!strncmp(buf, "compose_attach", 14)) {
1097                 GPtrArray *files;
1098                 gchar *mailto;
1099
1100                 mailto = g_strdup(buf + strlen("compose_attach") + 1);
1101                 files = g_ptr_array_new();
1102                 while (fd_gets(sock, buf, sizeof(buf)) > 0) {
1103                         if (buf[0] == '.' && buf[1] == '\n') break;
1104                         strretchomp(buf);
1105                         g_ptr_array_add(files, g_strdup(buf));
1106                 }
1107                 open_compose_new(mailto, files);
1108                 ptr_array_free_strings(files);
1109                 g_ptr_array_free(files, TRUE);
1110                 g_free(mailto);
1111         } else if (!strncmp(buf, "compose", 7)) {
1112                 open_compose_new(buf + strlen("compose") + 1, NULL);
1113         } else if (!strncmp(buf, "subscribe", 9)) {
1114                 main_window_popup(mainwin);
1115                 folder_subscribe(buf + strlen("subscribe") + 1);
1116         } else if (!strncmp(buf, "send", 4)) {
1117                 send_queue();
1118         } else if (!strncmp(buf, "online", 6)) {
1119                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
1120         } else if (!strncmp(buf, "offline", 7)) {
1121                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
1122         } else if (!strncmp(buf, "status-full", 11) ||
1123                    !strncmp(buf, "status", 6)) {
1124                 gchar *status;
1125                 GPtrArray *folders;
1126  
1127                 folders = get_folder_item_list(sock);
1128                 status = folder_get_status
1129                         (folders, !strncmp(buf, "status-full", 11));
1130                 fd_write_all(sock, status, strlen(status));
1131                 fd_write_all(sock, ".\n", 2);
1132                 g_free(status);
1133                 if (folders) g_ptr_array_free(folders, TRUE);
1134         } else if (!strncmp(buf, "exit", 4)) {
1135                 app_will_exit(NULL, mainwin);
1136         }
1137
1138         fd_close(sock);
1139 }
1140
1141 static void open_compose_new(const gchar *address, GPtrArray *attach_files)
1142 {
1143         gchar *addr = NULL;
1144
1145         if (address) {
1146                 Xstrdup_a(addr, address, return);
1147                 g_strstrip(addr);
1148         }
1149
1150         compose_new(NULL, addr, attach_files);
1151 }
1152
1153 static void send_queue(void)
1154 {
1155         GList *list;
1156
1157         for (list = folder_get_list(); list != NULL; list = list->next) {
1158                 Folder *folder = list->data;
1159
1160                 if (folder->queue) {
1161                         gint res = procmsg_send_queue
1162                                 (folder->queue, prefs_common.savemsg);
1163
1164                         if (res < 0)    
1165                                 alertpanel_error(_("Some errors occurred while sending queued messages."));
1166                         if (res)        
1167                                 folder_item_scan(folder->queue);
1168                 }
1169         }
1170 }
1171
1172 static void quit_signal_handler(int sig)
1173 {
1174         debug_print("Quitting on signal %d\n", sig);
1175
1176         g_timeout_add(0, clean_quit, NULL);
1177 }
1178
1179 static void install_basic_sighandlers()
1180 {
1181 #ifndef G_OS_WIN32
1182         sigset_t    mask;
1183         struct sigaction act;
1184
1185         sigemptyset(&mask);
1186
1187 #ifdef SIGTERM
1188         sigaddset(&mask, SIGTERM);
1189 #endif
1190 #ifdef SIGINT
1191         sigaddset(&mask, SIGINT);
1192 #endif
1193 #ifdef SIGHUP
1194         sigaddset(&mask, SIGHUP);
1195 #endif
1196
1197         act.sa_handler = quit_signal_handler;
1198         act.sa_mask    = mask;
1199         act.sa_flags   = 0;
1200
1201 #ifdef SIGTERM
1202         sigaction(SIGTERM, &act, 0);
1203 #endif
1204 #ifdef SIGINT
1205         sigaction(SIGINT, &act, 0);
1206 #endif  
1207 #ifdef SIGHUP
1208         sigaction(SIGHUP, &act, 0);
1209 #endif  
1210
1211         sigprocmask(SIG_UNBLOCK, &mask, 0);
1212 #endif /* !G_OS_WIN32 */
1213 }