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