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