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