2006-07-03 [colin] 2.3.1cvs53
[claws.git] / src / main.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2006 Hiroyuki Yamamoto and the Sylpheed-Claws team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <glib.h>
27 #include <glib/gi18n.h>
28 #include <gtk/gtkmain.h>
29 #include <gtk/gtkrc.h>
30
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <ctype.h>
35 #include <unistd.h>
36 #include <time.h>
37 #include <sys/stat.h>
38 #include <sys/types.h>
39 #ifdef G_OS_UNIX
40 #  include <signal.h>
41 #endif
42 #include "wizard.h"
43 #ifdef HAVE_STARTUP_NOTIFICATION
44 # define SN_API_NOT_YET_FROZEN
45 # include <libsn/sn-launchee.h>
46 # include <gdk/gdkx.h>
47 #endif
48
49 #include "sylpheed.h"
50 #include "main.h"
51 #include "mainwindow.h"
52 #include "folderview.h"
53 #include "image_viewer.h"
54 #include "summaryview.h"
55 #include "prefs_common.h"
56 #include "prefs_account.h"
57 #include "prefs_actions.h"
58 #include "prefs_ext_prog.h"
59 #include "prefs_fonts.h"
60 #include "prefs_image_viewer.h"
61 #include "prefs_message.h"
62 #include "prefs_receive.h"
63 #include "prefs_msg_colors.h"
64 #include "prefs_quote.h"
65 #include "prefs_spelling.h"
66 #include "prefs_summaries.h"
67 #include "prefs_themes.h"
68 #include "prefs_other.h"
69 #include "prefs_send.h"
70 #include "prefs_wrapping.h"
71 #include "prefs_compose_writing.h"
72 #include "prefs_display_header.h"
73 #include "account.h"
74 #include "procmsg.h"
75 #include "inc.h"
76 #include "import.h"
77 #include "manage_window.h"
78 #include "alertpanel.h"
79 #include "statusbar.h"
80 #include "addressbook.h"
81 #include "compose.h"
82 #include "folder.h"
83 #include "setup.h"
84 #include "utils.h"
85 #include "gtkutils.h"
86 #include "socket.h"
87 #include "log.h"
88 #include "prefs_toolbar.h"
89 #include "plugin.h"
90 #include "mh_gtk.h"
91 #include "imap_gtk.h"
92 #include "news_gtk.h"
93 #include "matcher.h"
94 #ifdef HAVE_LIBETPAN
95 #include "imap-thread.h"
96 #endif
97 #include "stock_pixmap.h"
98
99 #if USE_OPENSSL
100 #  include "ssl.h"
101 #endif
102
103 #include "version.h"
104
105 #include "crash.h"
106
107 gchar *prog_version;
108 #ifdef CRASH_DIALOG
109 gchar *argv0;
110 #endif
111
112 #ifdef HAVE_STARTUP_NOTIFICATION
113 static SnLauncheeContext *sn_context = NULL;
114 static SnDisplay *sn_display = NULL;
115 #endif
116
117 static gint lock_socket = -1;
118 static gint lock_socket_tag = 0;
119
120 typedef enum 
121 {
122         ONLINE_MODE_DONT_CHANGE,
123         ONLINE_MODE_ONLINE,
124         ONLINE_MODE_OFFLINE
125 } OnlineMode;
126
127 static struct RemoteCmd {
128         gboolean receive;
129         gboolean receive_all;
130         gboolean compose;
131         const gchar *compose_mailto;
132         GPtrArray *attach_files;
133         gboolean status;
134         gboolean status_full;
135         GPtrArray *status_folders;
136         GPtrArray *status_full_folders;
137         gboolean send;
138         gboolean crash;
139         int online_mode;
140         gchar   *crash_params;
141         gboolean exit;
142         gboolean subscribe;
143         const gchar *subscribe_uri;
144         const gchar *target;
145 } cmd;
146
147 static void parse_cmd_opt(int argc, char *argv[]);
148
149 static gint prohibit_duplicate_launch   (void);
150 static gchar * get_crashfile_name       (void);
151 static gint lock_socket_remove          (void);
152 static void lock_socket_input_cb        (gpointer          data,
153                                          gint              source,
154                                          GdkInputCondition condition);
155 #ifndef CLAWS                                    
156 static 
157 #endif
158 gchar *get_socket_name          (void);
159
160
161 static void open_compose_new            (const gchar    *address,
162                                          GPtrArray      *attach_files);
163
164 static void send_queue                  (void);
165 static void initial_processing          (FolderItem *item, gpointer data);
166 static void quit_signal_handler         (int sig);
167 static void install_basic_sighandlers   (void);
168 static void exit_sylpheed               (MainWindow *mainwin);
169
170 #define MAKE_DIR_IF_NOT_EXIST(dir) \
171 { \
172         if (!is_dir_exist(dir)) { \
173                 if (is_file_exist(dir)) { \
174                         alertpanel_warning \
175                                 (_("File '%s' already exists.\n" \
176                                    "Can't create folder."), \
177                                  dir); \
178                         return 1; \
179                 } \
180                 if (make_dir(dir) < 0) \
181                         return 1; \
182         } \
183 }
184
185 static MainWindow *static_mainwindow;
186
187 #ifdef HAVE_STARTUP_NOTIFICATION
188 static void sn_error_trap_push(SnDisplay *display, Display *xdisplay)
189 {
190         gdk_error_trap_push();
191 }
192
193 static void sn_error_trap_pop(SnDisplay *display, Display *xdisplay)
194 {
195         gdk_error_trap_pop();
196 }
197
198 static void startup_notification_complete(gboolean with_window)
199 {
200         Display *xdisplay;
201         GtkWidget *hack = NULL;
202
203         if (with_window) {
204                 /* this is needed to make the startup notification leave,
205                  * if we have been launched from a menu.
206                  * We have to display a window, so let it be very little */
207                 hack = gtk_window_new(GTK_WINDOW_POPUP);
208                 gtk_widget_set_uposition(hack, 0, 0);
209                 gtk_widget_set_size_request(hack, 1, 1);
210                 gtk_widget_show(hack);
211         }
212
213         xdisplay = GDK_DISPLAY();
214         sn_display = sn_display_new(xdisplay,
215                                 sn_error_trap_push,
216                                 sn_error_trap_pop);
217         sn_context = sn_launchee_context_new_from_environment(sn_display,
218                                                  DefaultScreen(xdisplay));
219
220         if (sn_context != NULL) {
221                 sn_launchee_context_complete(sn_context);
222                 sn_launchee_context_unref(sn_context);
223                 sn_display_unref(sn_display);
224         }
225         if (with_window) {
226                 gtk_widget_destroy(hack);
227         }
228 }
229 #endif /* HAVE_STARTUP_NOTIFICATION */
230
231 void sylpheed_gtk_idle(void) 
232 {
233         while(gtk_events_pending()) {
234                 gtk_main_iteration();
235         }
236         g_usleep(50000);
237 }
238
239 gboolean defer_check_all(void *data)
240 {
241         gboolean autochk = GPOINTER_TO_INT(data);
242
243         inc_all_account_mail(static_mainwindow, autochk, 
244                         prefs_common.newmail_notify_manu);
245
246         return FALSE;
247 }
248
249 gboolean defer_check(void *data)
250 {
251         inc_mail(static_mainwindow, prefs_common.newmail_notify_manu);
252
253         return FALSE;
254 }
255
256 static gboolean defer_jump(void *data)
257 {
258         mainwindow_jump_to(data);
259         return FALSE;
260 }
261
262 static gboolean migrate_old_config(const gchar *old_cfg_dir, const gchar *new_cfg_dir)
263 {
264         gchar *message = g_strdup_printf(_("Configuration for Sylpheed-Claws %s found.\n"
265                          "Do you want to migrate this configuration?"),
266                          !strcmp(old_cfg_dir, OLD_GTK1_RC_DIR)?
267                                 _("1.0.5 or previous"):_("1.9.15 or previous"));
268         gint r = 0;
269         GtkWidget *window = NULL;
270         if (alertpanel(_("Migration of configuration"),
271                        message,
272                        GTK_STOCK_NO, GTK_STOCK_YES, NULL) != G_ALERTALTERNATE) {
273                 return FALSE;
274         }
275         
276         window = label_window_create(_("Copying configuration..."));
277         GTK_EVENTS_FLUSH();
278         r = copy_dir(old_cfg_dir, new_cfg_dir);
279         gtk_widget_destroy(window);
280         if (r != 0) {
281                 alertpanel_error(_("Migration failed!"));
282         }
283         return (r == 0);
284 }
285
286 int main(int argc, char *argv[])
287 {
288         gchar *userrc;
289         MainWindow *mainwin;
290         FolderView *folderview;
291         GdkPixbuf *icon;
292         gboolean crash_file_present = FALSE;
293         gint num_folder_class = 0;
294         if (!sylpheed_init(&argc, &argv)) {
295                 return 0;
296         }
297
298         prog_version = PROG_VERSION;
299 #ifdef CRASH_DIALOG
300         argv0 = g_strdup(argv[0]);
301 #endif
302
303         parse_cmd_opt(argc, argv);
304
305 #ifdef CRASH_DIALOG
306         if (cmd.crash) {
307                 gtk_set_locale();
308                 gtk_init(&argc, &argv);
309                 crash_main(cmd.crash_params);
310                 return 0;
311         }
312         crash_install_handlers();
313 #endif
314         install_basic_sighandlers();
315         sock_init();
316
317         /* check and create unix domain socket for remote operation */
318 #ifdef G_OS_UNIX
319         lock_socket = prohibit_duplicate_launch();
320         if (lock_socket < 0) {
321 #ifdef HAVE_STARTUP_NOTIFICATION
322                 if(gtk_init_check(&argc, &argv))
323                         startup_notification_complete(TRUE);
324 #endif
325                 return 0;
326         }
327
328         if (cmd.status || cmd.status_full) {
329                 puts("0 Sylpheed-Claws not running.");
330                 lock_socket_remove();
331                 return 0;
332         }
333         
334         if (cmd.exit)
335                 return 0;
336 #endif
337         if (!g_thread_supported())
338                 g_thread_init(NULL);
339
340         gtk_set_locale();
341         gtk_init(&argc, &argv);
342
343         gdk_rgb_init();
344         gtk_widget_set_default_colormap(gdk_rgb_get_colormap());
345         gtk_widget_set_default_visual(gdk_rgb_get_visual());
346
347         if (!g_thread_supported()) {
348                 g_error(_("g_thread is not supported by glib.\n"));
349         }
350
351         /* parse gtkrc files */
352         userrc = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".gtkrc-2.0",
353                              NULL);
354         gtk_rc_parse(userrc);
355         g_free(userrc);
356         userrc = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".gtk",
357                              G_DIR_SEPARATOR_S, "gtkrc-2.0", NULL);
358         gtk_rc_parse(userrc);
359         g_free(userrc);
360
361         CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
362         if (!is_dir_exist(RC_DIR)) {
363                 gboolean r = FALSE;
364                 if (is_dir_exist(OLD_GTK2_RC_DIR))
365                         r = migrate_old_config(OLD_GTK2_RC_DIR, RC_DIR);
366                 else if (is_dir_exist(OLD_GTK1_RC_DIR))
367                         r = migrate_old_config(OLD_GTK1_RC_DIR, RC_DIR);
368                 if (r == FALSE && !is_dir_exist(RC_DIR) && make_dir(RC_DIR) < 0)
369                         exit(1);
370         }
371
372         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, "gtkrc-2.0", NULL);
373         gtk_rc_parse(userrc);
374         g_free(userrc);
375
376         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
377         gtk_accel_map_load (userrc);
378         g_free(userrc);
379
380         gtk_settings_set_long_property(gtk_settings_get_default(), 
381                                        "gtk-can-change-accels",
382                                        (glong)TRUE, "XProperty");
383
384         CHDIR_RETURN_VAL_IF_FAIL(get_rc_dir(), 1);
385
386         MAKE_DIR_IF_NOT_EXIST(get_mail_base_dir());
387         MAKE_DIR_IF_NOT_EXIST(get_imap_cache_dir());
388         MAKE_DIR_IF_NOT_EXIST(get_news_cache_dir());
389         MAKE_DIR_IF_NOT_EXIST(get_mime_tmp_dir());
390         MAKE_DIR_IF_NOT_EXIST(get_tmp_dir());
391         MAKE_DIR_IF_NOT_EXIST(UIDL_DIR);
392
393         crash_file_present = is_file_exist(get_crashfile_name());
394         /* remove temporary files */
395         remove_all_files(get_tmp_dir());
396         remove_all_files(get_mime_tmp_dir());
397
398         if (is_file_exist("sylpheed.log")) {
399                 if (rename_force("sylpheed.log", "sylpheed.log.bak") < 0)
400                         FILE_OP_ERROR("sylpheed.log", "rename");
401         }
402         set_log_file("sylpheed.log");
403
404         CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
405
406         folder_system_init();
407         prefs_common_read_config();
408
409         prefs_themes_init();
410         prefs_fonts_init();
411         prefs_ext_prog_init();
412         prefs_wrapping_init();
413         prefs_compose_writing_init();
414         prefs_msg_colors_init();
415         image_viewer_init();
416         prefs_image_viewer_init();
417         prefs_quote_init();
418         prefs_summaries_init();
419         prefs_message_init();
420         prefs_other_init();
421         prefs_receive_init();
422         prefs_send_init();
423 #ifdef USE_ASPELL
424         gtkaspell_checkers_init();
425         prefs_spelling_init();
426 #endif
427         
428         sock_set_io_timeout(prefs_common.io_timeout_secs);
429 #ifdef HAVE_LIBETPAN
430         imap_main_set_timeout(prefs_common.io_timeout_secs);
431 #endif
432         prefs_actions_read_config();
433         prefs_display_header_read_config();
434         /* prefs_filtering_read_config(); */
435         addressbook_read_file();
436         renderer_read_config();
437
438         gtkut_widget_init();
439         stock_pixbuf_gdk(NULL, STOCK_PIXMAP_SYLPHEED_ICON, &icon);
440         gtk_window_set_default_icon(icon);
441
442         folderview_initialize();
443
444         mh_gtk_init();
445         imap_gtk_init();
446         news_gtk_init();
447                 
448         mainwin = main_window_create
449                 (prefs_common.sep_folder | prefs_common.sep_msg << 1);
450         manage_window_focus_in(mainwin->window, NULL, NULL);
451         folderview = mainwin->folderview;
452
453         gtk_clist_freeze(GTK_CLIST(mainwin->folderview->ctree));
454         folder_item_update_freeze();
455
456         /* register the callback of unix domain socket input */
457 #ifdef G_OS_UNIX
458         lock_socket_tag = gdk_input_add(lock_socket,
459                                         GDK_INPUT_READ | GDK_INPUT_EXCEPTION,
460                                         lock_socket_input_cb,
461                                         mainwin);
462 #endif
463
464         prefs_account_init();
465         account_read_config_all();
466
467         if (folder_read_list() < 0) {
468                 if (!run_wizard(mainwin, TRUE))
469                         exit(1);
470                 folder_write_list();
471         }
472
473         if (!account_get_list()) {
474                 if (!run_wizard(mainwin, FALSE))
475                         exit(1);
476                 account_read_config_all();
477                 if(!account_get_list())
478                         exit_sylpheed(mainwin);
479         }
480
481         main_window_popup(mainwin);
482
483 #ifdef HAVE_LIBETPAN
484         imap_main_init(prefs_common.skip_ssl_cert_check);
485 #endif  
486         account_set_missing_folder();
487         folder_set_missing_folders();
488         folderview_set(folderview);
489
490         prefs_matcher_read_config();
491
492         /* make one all-folder processing before using sylpheed */
493         main_window_cursor_wait(mainwin);
494         folder_func_to_all_folders(initial_processing, (gpointer *)mainwin);
495
496         /* if Sylpheed crashed, rebuild caches */
497         if (!cmd.crash && crash_file_present) {
498                 GTK_EVENTS_FLUSH();
499                 debug_print("Sylpheed-Claws crashed, checking for new messages in local folders\n");
500                 folder_item_update_thaw();
501                 folderview_check_new(NULL);
502                 folder_clean_cache_memory_force();
503                 folder_item_update_freeze();
504         }
505         /* make the crash-indicator file */
506         str_write_to_file("foo", get_crashfile_name());
507
508         inc_autocheck_timer_init(mainwin);
509
510         if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
511                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
512         }
513         if (cmd.online_mode == ONLINE_MODE_ONLINE) {
514                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
515         }
516
517         if (cmd.status_folders) {
518                 g_ptr_array_free(cmd.status_folders, TRUE);
519                 cmd.status_folders = NULL;
520         }
521         if (cmd.status_full_folders) {
522                 g_ptr_array_free(cmd.status_full_folders, TRUE);
523                 cmd.status_full_folders = NULL;
524         }
525
526         sylpheed_register_idle_function(sylpheed_gtk_idle);
527
528         prefs_toolbar_init();
529
530         num_folder_class = g_list_length(folder_get_list());
531
532         plugin_load_all("GTK2");
533
534         if (g_list_length(folder_get_list()) != num_folder_class) {
535                 debug_print("new folders loaded, reloading processing rules\n");
536                 prefs_matcher_read_config();
537         }
538         
539         if (plugin_get_unloaded_list() != NULL) {
540                 main_window_cursor_normal(mainwin);
541                 alertpanel_warning(_("Some plugin(s) failed to load. "
542                                      "Check the Plugins configuration "
543                                      "for more information."));
544                 main_window_cursor_wait(mainwin);
545         }
546
547         plugin_load_standard_plugins ();
548        
549         if (!folder_have_mailbox()) {
550                 main_window_cursor_normal(mainwin);
551                 alertpanel_error(_("Sylpheed-Claws has detected a configured "
552                                    "mailbox, but could not load it. It is "
553                                    "probably provided by an out-of-date "
554                                    "external plugin. Please reinstall the "
555                                    "plugin and try again."));
556                 exit(1);
557         }
558         
559         static_mainwindow = mainwin;
560
561 #ifdef HAVE_STARTUP_NOTIFICATION
562         startup_notification_complete(FALSE);
563 #endif
564         folder_item_update_thaw();
565         gtk_clist_thaw(GTK_CLIST(mainwin->folderview->ctree));
566         main_window_cursor_normal(mainwin);
567
568         if (cmd.receive_all) {
569                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(FALSE));
570         } else if (prefs_common.chk_on_startup) {
571                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(TRUE));
572         } else if (cmd.receive) {
573                 g_timeout_add(1000, defer_check, NULL);
574         } else {
575                 gtk_widget_grab_focus(folderview->ctree);
576         }
577
578         if (cmd.compose) {
579                 open_compose_new(cmd.compose_mailto, cmd.attach_files);
580         }
581         if (cmd.attach_files) {
582                 ptr_array_free_strings(cmd.attach_files);
583                 g_ptr_array_free(cmd.attach_files, TRUE);
584                 cmd.attach_files = NULL;
585         }
586         if (cmd.subscribe) {
587                 folder_subscribe(cmd.subscribe_uri);
588         }
589
590         if (cmd.send) {
591                 send_queue();
592         }
593         
594         if (cmd.target) {
595                 g_timeout_add(500, defer_jump, (gpointer)cmd.target);
596         }
597
598         gtk_main();
599
600         exit_sylpheed(mainwin);
601
602         return 0;
603 }
604
605 static void save_all_caches(FolderItem *item, gpointer data)
606 {
607         gint free_caches = GPOINTER_TO_INT(data);
608         if (!item->cache) {
609                 return;
610         }
611
612         if (item->opened)
613                 folder_item_close(item);
614         
615         if (free_caches)
616                 folder_item_free_cache(item, TRUE);
617         else
618                 folder_item_write_cache(item);
619 }
620
621 static void exit_sylpheed(MainWindow *mainwin)
622 {
623         gchar *filename;
624
625         debug_print("shutting down\n");
626         inc_autocheck_timer_remove();
627
628         if (prefs_common.clean_on_exit) {
629                 main_window_empty_trash(mainwin, prefs_common.ask_on_clean);
630         }
631
632         /* save prefs for opened folder */
633         if(mainwin->folderview->opened) {
634                 FolderItem *item;
635
636                 item = gtk_ctree_node_get_row_data(GTK_CTREE(mainwin->folderview->ctree), mainwin->folderview->opened);
637                 summary_save_prefs_to_folderitem(mainwin->folderview->summaryview, item);
638         }
639
640         /* save all state before exiting */
641         folder_write_list();
642         folder_func_to_all_folders(save_all_caches, GINT_TO_POINTER(1));
643
644         main_window_get_size(mainwin);
645         main_window_get_position(mainwin);
646         prefs_common_write_config();
647         account_write_config_all();
648         addressbook_export_to_file();
649
650         filename = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
651         gtk_accel_map_save(filename);
652         g_free(filename);
653
654         /* delete temporary files */
655         remove_all_files(get_tmp_dir());
656         remove_all_files(get_mime_tmp_dir());
657
658         close_log_file();
659
660 #ifdef HAVE_LIBETPAN
661         imap_main_done();
662 #endif
663         /* delete crashfile */
664         if (!cmd.crash)
665                 g_unlink(get_crashfile_name());
666
667         lock_socket_remove();
668
669         main_window_destroy_all();
670         
671         plugin_unload_all("GTK2");
672
673         prefs_toolbar_done();
674
675         addressbook_destroy();
676
677         prefs_themes_done();
678         prefs_fonts_done();
679         prefs_ext_prog_done();
680         prefs_wrapping_done();
681         prefs_compose_writing_done();
682         prefs_msg_colors_done();
683         prefs_image_viewer_done();
684         image_viewer_done();
685         prefs_quote_done();
686         prefs_summaries_done();
687         prefs_message_done();
688         prefs_other_done();
689         prefs_receive_done();
690         prefs_send_done();
691 #ifdef USE_ASPELL       
692         prefs_spelling_done();
693         gtkaspell_checkers_quit();
694 #endif
695         sylpheed_done();
696
697 }
698
699 static void parse_cmd_opt(int argc, char *argv[])
700 {
701         gint i;
702
703         for (i = 1; i < argc; i++) {
704                 if (!strncmp(argv[i], "--receive-all", 13)) {
705                         cmd.receive_all = TRUE;
706                 } else if (!strncmp(argv[i], "--receive", 9)) {
707                         cmd.receive = TRUE;
708                 } else if (!strncmp(argv[i], "--compose", 9)) {
709                         const gchar *p = argv[i + 1];
710
711                         cmd.compose = TRUE;
712                         cmd.compose_mailto = NULL;
713                         if (p && *p != '\0' && *p != '-') {
714                                 if (!strncmp(p, "mailto:", 7)) {
715                                         cmd.compose_mailto = p + 7;
716                                 } else {
717                                         cmd.compose_mailto = p;
718                                 }
719                                 i++;
720                         }
721                 } else if (!strncmp(argv[i], "--subscribe", 11)) {
722                         const gchar *p = argv[i + 1];
723                         if (p && *p != '\0' && *p != '-') {
724                                 cmd.subscribe = TRUE;
725                                 cmd.subscribe_uri = p;
726                         }
727                 } else if (!strncmp(argv[i], "--attach", 8)) {
728                         const gchar *p = argv[i + 1];
729                         gchar *file;
730
731                         while (p && *p != '\0' && *p != '-') {
732                                 if (!cmd.attach_files) {
733                                         cmd.attach_files = g_ptr_array_new();
734                                 }
735                                 if (*p != G_DIR_SEPARATOR) {
736                                         file = g_strconcat(sylpheed_get_startup_dir(),
737                                                            G_DIR_SEPARATOR_S,
738                                                            p, NULL);
739                                 } else {
740                                         file = g_strdup(p);
741                                 }
742                                 g_ptr_array_add(cmd.attach_files, file);
743                                 i++;
744                                 p = argv[i + 1];
745                         }
746                 } else if (!strncmp(argv[i], "--send", 6)) {
747                         cmd.send = TRUE;
748                 } else if (!strncmp(argv[i], "--version", 9)) {
749                         puts("Sylpheed-Claws version " VERSION);
750                         exit(0);
751                 } else if (!strncmp(argv[i], "--status-full", 13)) {
752                         const gchar *p = argv[i + 1];
753  
754                         cmd.status_full = TRUE;
755                         while (p && *p != '\0' && *p != '-') {
756                                 if (!cmd.status_full_folders) {
757                                         cmd.status_full_folders =
758                                                 g_ptr_array_new();
759                                 }
760                                 g_ptr_array_add(cmd.status_full_folders,
761                                                 g_strdup(p));
762                                 i++;
763                                 p = argv[i + 1];
764                         }
765                 } else if (!strncmp(argv[i], "--status", 8)) {
766                         const gchar *p = argv[i + 1];
767  
768                         cmd.status = TRUE;
769                         while (p && *p != '\0' && *p != '-') {
770                                 if (!cmd.status_folders)
771                                         cmd.status_folders = g_ptr_array_new();
772                                 g_ptr_array_add(cmd.status_folders,
773                                                 g_strdup(p));
774                                 i++;
775                                 p = argv[i + 1];
776                         }
777                 } else if (!strncmp(argv[i], "--online", 8)) {
778                         cmd.online_mode = ONLINE_MODE_ONLINE;
779                 } else if (!strncmp(argv[i], "--offline", 9)) {
780                         cmd.online_mode = ONLINE_MODE_OFFLINE;
781                 } else if (!strncmp(argv[i], "--help", 6)) {
782                         gchar *base = g_path_get_basename(argv[0]);
783                         g_print(_("Usage: %s [OPTION]...\n"), base);
784
785                         g_print("%s\n", _("  --compose [address]    open composition window"));
786                         g_print("%s\n", _("  --subscribe [uri]      subscribe to the given URI if possible"));
787                         g_print("%s\n", _("  --attach file1 [file2]...\n"
788                                   "                         open composition window with specified files\n"
789                                   "                         attached"));
790                         g_print("%s\n", _("  --receive              receive new messages"));
791                         g_print("%s\n", _("  --receive-all          receive new messages of all accounts"));
792                         g_print("%s\n", _("  --send                 send all queued messages"));
793                         g_print("%s\n", _("  --status [folder]...   show the total number of messages"));
794                         g_print("%s\n", _("  --status-full [folder]...\n"
795                                "                         show the status of each folder"));
796                         g_print("%s\n", _("  --select folder[/msg]  jumps to the specified folder/message\n" 
797                                           "                         folder is a folder id like '#mh/Mailbox/inbox'"));
798                         g_print("%s\n", _("  --online               switch to online mode"));
799                         g_print("%s\n", _("  --offline              switch to offline mode"));
800                         g_print("%s\n", _("  --exit                 exit Sylpheed-Claws"));
801                         g_print("%s\n", _("  --debug                debug mode"));
802                         g_print("%s\n", _("  --help                 display this help and exit"));
803                         g_print("%s\n", _("  --version              output version information and exit"));
804                         g_print("%s\n", _("  --config-dir           output configuration directory"));
805
806                         g_free(base);
807                         exit(1);
808                 } else if (!strncmp(argv[i], "--crash", 7)) {
809                         cmd.crash = TRUE;
810                         cmd.crash_params = g_strdup(argv[i + 1]);
811                         i++;
812                 } else if (!strncmp(argv[i], "--config-dir", sizeof "--config-dir" - 1)) {
813                         puts(RC_DIR);
814                         exit(0);
815                 } else if (!strncmp(argv[i], "--exit", 6)) {
816                         cmd.exit = TRUE;
817                 } else if (!strncmp(argv[i], "--select", 8) && i+1 < argc) {
818                         cmd.target = argv[i+1];
819                 } else if (i == 1 && argc == 2) {
820                         /* only one parameter. Do something intelligent about it */
821                         if (strstr(argv[i], "@") && !strstr(argv[i], "://")) {
822                                 const gchar *p = argv[i];
823
824                                 cmd.compose = TRUE;
825                                 cmd.compose_mailto = NULL;
826                                 if (p && *p != '\0' && *p != '-') {
827                                         if (!strncmp(p, "mailto:", 7)) {
828                                                 cmd.compose_mailto = p + 7;
829                                         } else {
830                                                 cmd.compose_mailto = p;
831                                         }
832                                 }
833                         } else if (strstr(argv[i], "://")) {
834                                 const gchar *p = argv[i];
835                                 if (p && *p != '\0' && *p != '-') {
836                                         cmd.subscribe = TRUE;
837                                         cmd.subscribe_uri = p;
838                                 }
839                         }
840                 }
841                 
842         }
843
844         if (cmd.attach_files && cmd.compose == FALSE) {
845                 cmd.compose = TRUE;
846                 cmd.compose_mailto = NULL;
847         }
848 }
849
850 static gint get_queued_message_num(void)
851 {
852         FolderItem *queue;
853
854         queue = folder_get_default_queue();
855         if (!queue) {
856                 return -1;
857         }
858
859         folder_item_scan(queue);
860         return queue->total_msgs;
861 }
862
863 static void initial_processing(FolderItem *item, gpointer data)
864 {
865         MainWindow *mainwin = (MainWindow *)data;
866         gchar *buf;
867
868         g_return_if_fail(item);
869         buf = g_strdup_printf(_("Processing (%s)..."), 
870                               item->path 
871                               ? item->path 
872                               : _("top level folder"));
873         debug_print("%s\n", buf);
874         g_free(buf);
875
876         
877         if (item->prefs->enable_processing) {
878                 folder_item_apply_processing(item);
879         }
880
881         debug_print("done.\n");
882         STATUSBAR_POP(mainwin);
883 }
884
885 static void draft_all_messages(void)
886 {
887         GList *compose_list = NULL;
888         
889         while ((compose_list = compose_get_compose_list()) != NULL) {
890                 Compose *c = (Compose*)compose_list->data;
891                 compose_draft(c);
892         }       
893 }
894
895 gboolean clean_quit(gpointer data)
896 {
897         static gboolean firstrun = TRUE;
898
899         if (!firstrun) {
900                 return FALSE;
901         }
902         firstrun = FALSE;
903
904         /*!< Good idea to have the main window stored in a 
905          *   static variable so we can check that variable
906          *   to see if we're really allowed to do things
907          *   that actually the spawner is supposed to 
908          *   do (like: sending mail, composing messages).
909          *   Because, really, if we're the spawnee, and
910          *   we touch GTK stuff, we're hosed. See the 
911          *   next fixme. */
912
913         /* FIXME: Use something else to signal that we're
914          * in the original spawner, and not in a spawned
915          * child. */
916         if (!static_mainwindow) {
917                 return FALSE;
918         }
919                 
920         draft_all_messages();
921
922         exit_sylpheed(static_mainwindow);
923         exit(0);
924
925         return FALSE;
926 }
927
928 void app_will_exit(GtkWidget *widget, gpointer data)
929 {
930         MainWindow *mainwin = data;
931         
932         if (compose_get_compose_list()) {
933                 gint val = alertpanel(_("Really quit?"),
934                                _("Composing message exists."),
935                                _("_Save to Draft"), _("_Discard them"), _("Do_n't quit"));
936                 switch (val) {
937                         case G_ALERTOTHER:
938                                 return;
939                         case G_ALERTALTERNATE:
940                                 break;
941                         default:
942                                 draft_all_messages();
943                 }
944
945                 manage_window_focus_in(mainwin->window, NULL, NULL);
946         }
947
948         if (prefs_common.warn_queued_on_exit && get_queued_message_num() > 0) {
949                 if (alertpanel(_("Queued messages"),
950                                _("Some unsent messages are queued. Exit now?"),
951                                GTK_STOCK_CANCEL, GTK_STOCK_OK, NULL)
952                     != G_ALERTALTERNATE) {
953                         return;
954                 }
955                 manage_window_focus_in(mainwin->window, NULL, NULL);
956         }
957
958         sock_cleanup();
959         if (folderview_get_selected_item(mainwin->folderview))
960                 folder_item_close(folderview_get_selected_item(mainwin->folderview));
961         gtk_main_quit();
962 }
963
964 /*
965  * CLAWS: want this public so crash dialog can delete the
966  * lock file too
967  */
968 #ifndef CLAWS
969 static
970 #endif
971 gchar *get_socket_name(void)
972 {
973         static gchar *filename = NULL;
974
975         if (filename == NULL) {
976                 filename = g_strdup_printf("%s%csylpheed-claws-%d",
977                                            g_get_tmp_dir(), G_DIR_SEPARATOR,
978 #if HAVE_GETUID
979                                            getuid());
980 #else
981                                            0);                                          
982 #endif
983         }
984
985         return filename;
986 }
987
988 static gchar *get_crashfile_name(void)
989 {
990         static gchar *filename = NULL;
991
992         if (filename == NULL) {
993                 filename = g_strdup_printf("%s%csylpheed-crashed",
994                                            get_tmp_dir(), G_DIR_SEPARATOR);
995         }
996
997         return filename;
998 }
999
1000 static gint prohibit_duplicate_launch(void)
1001 {
1002         gint uxsock;
1003         gchar *path;
1004
1005         path = get_socket_name();
1006         uxsock = fd_connect_unix(path);
1007         if (uxsock < 0) {
1008                 g_unlink(path);
1009                 return fd_open_unix(path);
1010         }
1011
1012         /* remote command mode */
1013
1014         debug_print("another Sylpheed-Claws instance is already running.\n");
1015
1016         if (cmd.receive_all) {
1017                 fd_write_all(uxsock, "receive_all\n", 12);
1018         } else if (cmd.receive) {
1019                 fd_write_all(uxsock, "receive\n", 8);
1020         } else if (cmd.compose && cmd.attach_files) {
1021                 gchar *str, *compose_str;
1022                 gint i;
1023
1024                 if (cmd.compose_mailto) {
1025                         compose_str = g_strdup_printf("compose_attach %s\n",
1026                                                       cmd.compose_mailto);
1027                 } else {
1028                         compose_str = g_strdup("compose_attach\n");
1029                 }
1030
1031                 fd_write_all(uxsock, compose_str, strlen(compose_str));
1032                 g_free(compose_str);
1033
1034                 for (i = 0; i < cmd.attach_files->len; i++) {
1035                         str = g_ptr_array_index(cmd.attach_files, i);
1036                         fd_write_all(uxsock, str, strlen(str));
1037                         fd_write_all(uxsock, "\n", 1);
1038                 }
1039
1040                 fd_write_all(uxsock, ".\n", 2);
1041         } else if (cmd.compose) {
1042                 gchar *compose_str;
1043
1044                 if (cmd.compose_mailto) {
1045                         compose_str = g_strdup_printf
1046                                 ("compose %s\n", cmd.compose_mailto);
1047                 } else {
1048                         compose_str = g_strdup("compose\n");
1049                 }
1050
1051                 fd_write_all(uxsock, compose_str, strlen(compose_str));
1052                 g_free(compose_str);
1053         } else if (cmd.subscribe) {
1054                 gchar *str = g_strdup_printf("subscribe %s\n", cmd.subscribe_uri);
1055                 fd_write_all(uxsock, str, strlen(str));
1056                 g_free(str);
1057         } else if (cmd.send) {
1058                 fd_write_all(uxsock, "send\n", 5);
1059         } else if (cmd.online_mode == ONLINE_MODE_ONLINE) {
1060                 fd_write(uxsock, "online\n", 6);
1061         } else if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
1062                 fd_write(uxsock, "offline\n", 7);
1063         } else if (cmd.status || cmd.status_full) {
1064                 gchar buf[BUFFSIZE];
1065                 gint i;
1066                 const gchar *command;
1067                 GPtrArray *folders;
1068                 gchar *folder;
1069  
1070                 command = cmd.status_full ? "status-full\n" : "status\n";
1071                 folders = cmd.status_full ? cmd.status_full_folders :
1072                         cmd.status_folders;
1073  
1074                 fd_write_all(uxsock, command, strlen(command));
1075                 for (i = 0; folders && i < folders->len; ++i) {
1076                         folder = g_ptr_array_index(folders, i);
1077                         fd_write_all(uxsock, folder, strlen(folder));
1078                         fd_write_all(uxsock, "\n", 1);
1079                 }
1080                 fd_write_all(uxsock, ".\n", 2);
1081                 for (;;) {
1082                         fd_gets(uxsock, buf, sizeof(buf));
1083                         if (!strncmp(buf, ".\n", 2)) break;
1084                         fputs(buf, stdout);
1085                 }
1086         } else if (cmd.exit) {
1087                 fd_write_all(uxsock, "exit\n", 5);
1088         } else if (cmd.target) {
1089                 gchar *str = g_strdup_printf("select %s\n", cmd.target);
1090                 fd_write_all(uxsock, str, strlen(str));
1091                 g_free(str);
1092         } else
1093                 fd_write_all(uxsock, "popup\n", 6);
1094
1095         fd_close(uxsock);
1096         return -1;
1097 }
1098
1099 static gint lock_socket_remove(void)
1100 {
1101 #ifdef G_OS_UNIX
1102         gchar *filename;
1103
1104         if (lock_socket < 0) {
1105                 return -1;
1106         }
1107
1108         if (lock_socket_tag > 0) {
1109                 gdk_input_remove(lock_socket_tag);
1110         }
1111         fd_close(lock_socket);
1112         filename = get_socket_name();
1113         g_unlink(filename);
1114 #endif
1115
1116         return 0;
1117 }
1118
1119 static GPtrArray *get_folder_item_list(gint sock)
1120 {
1121         gchar buf[BUFFSIZE];
1122         FolderItem *item;
1123         GPtrArray *folders = NULL;
1124
1125         for (;;) {
1126                 fd_gets(sock, buf, sizeof(buf));
1127                 if (!strncmp(buf, ".\n", 2)) {
1128                         break;
1129                 }
1130                 strretchomp(buf);
1131                 if (!folders) {
1132                         folders = g_ptr_array_new();
1133                 }
1134                 item = folder_find_item_from_identifier(buf);
1135                 if (item) {
1136                         g_ptr_array_add(folders, item);
1137                 } else {
1138                         g_warning("no such folder: %s\n", buf);
1139                 }
1140         }
1141
1142         return folders;
1143 }
1144
1145 static void lock_socket_input_cb(gpointer data,
1146                                  gint source,
1147                                  GdkInputCondition condition)
1148 {
1149         MainWindow *mainwin = (MainWindow *)data;
1150         gint sock;
1151         gchar buf[BUFFSIZE];
1152
1153         sock = fd_accept(source);
1154         fd_gets(sock, buf, sizeof(buf));
1155
1156         if (!strncmp(buf, "popup", 5)) {
1157                 main_window_popup(mainwin);
1158         } else if (!strncmp(buf, "receive_all", 11)) {
1159                 inc_all_account_mail(mainwin, FALSE,
1160                                      prefs_common.newmail_notify_manu);
1161         } else if (!strncmp(buf, "receive", 7)) {
1162                 inc_mail(mainwin, prefs_common.newmail_notify_manu);
1163         } else if (!strncmp(buf, "compose_attach", 14)) {
1164                 GPtrArray *files;
1165                 gchar *mailto;
1166
1167                 mailto = g_strdup(buf + strlen("compose_attach") + 1);
1168                 files = g_ptr_array_new();
1169                 while (fd_gets(sock, buf, sizeof(buf)) > 0) {
1170                         if (buf[0] == '.' && buf[1] == '\n') {
1171                                 break;
1172                         }
1173                         strretchomp(buf);
1174                         g_ptr_array_add(files, g_strdup(buf));
1175                 }
1176                 open_compose_new(mailto, files);
1177                 ptr_array_free_strings(files);
1178                 g_ptr_array_free(files, TRUE);
1179                 g_free(mailto);
1180         } else if (!strncmp(buf, "compose", 7)) {
1181                 open_compose_new(buf + strlen("compose") + 1, NULL);
1182         } else if (!strncmp(buf, "subscribe", 9)) {
1183                 main_window_popup(mainwin);
1184                 folder_subscribe(buf + strlen("subscribe") + 1);
1185         } else if (!strncmp(buf, "send", 4)) {
1186                 send_queue();
1187         } else if (!strncmp(buf, "online", 6)) {
1188                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
1189         } else if (!strncmp(buf, "offline", 7)) {
1190                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
1191         } else if (!strncmp(buf, "status-full", 11) ||
1192                    !strncmp(buf, "status", 6)) {
1193                 gchar *status;
1194                 GPtrArray *folders;
1195  
1196                 folders = get_folder_item_list(sock);
1197                 status = folder_get_status
1198                         (folders, !strncmp(buf, "status-full", 11));
1199                 fd_write_all(sock, status, strlen(status));
1200                 fd_write_all(sock, ".\n", 2);
1201                 g_free(status);
1202                 if (folders) g_ptr_array_free(folders, TRUE);
1203         } else if (!strncmp(buf, "select ", 7)) {
1204                 const gchar *target = buf+7;
1205                 mainwindow_jump_to(target);
1206         } else if (!strncmp(buf, "exit", 4)) {
1207                 app_will_exit(NULL, mainwin);
1208         }
1209
1210         fd_close(sock);
1211 }
1212
1213 static void open_compose_new(const gchar *address, GPtrArray *attach_files)
1214 {
1215         gchar *addr = NULL;
1216
1217         if (address) {
1218                 Xstrdup_a(addr, address, return);
1219                 g_strstrip(addr);
1220         }
1221
1222         compose_new(NULL, addr, attach_files);
1223 }
1224
1225 static void send_queue(void)
1226 {
1227         GList *list;
1228         gchar *errstr = NULL;
1229         for (list = folder_get_list(); list != NULL; list = list->next) {
1230                 Folder *folder = list->data;
1231
1232                 if (folder->queue) {
1233                         gint res = procmsg_send_queue
1234                                 (folder->queue, prefs_common.savemsg,
1235                                 &errstr);
1236
1237                         if (res) {
1238                                 folder_item_scan(folder->queue);
1239                         }
1240                 }
1241         }
1242         if (errstr) {
1243                 gchar *tmp = g_strdup_printf(_("Some errors occurred "
1244                                 "while sending queued messages:\n%s"), errstr);
1245                 g_free(errstr);
1246                 alertpanel_error_log(tmp);
1247                 g_free(tmp);
1248         } else {
1249                 alertpanel_error_log("Some errors occurred "
1250                                 "while sending queued messages.");
1251         }
1252 }
1253
1254 static void quit_signal_handler(int sig)
1255 {
1256 #ifdef SIGPIPE
1257         if (sig == SIGPIPE) {
1258                 debug_print("caugth SIGPIPE, maybe X closing!\n");
1259                 folder_write_list();
1260                 folder_func_to_all_folders(save_all_caches, GINT_TO_POINTER(0));
1261                 return; 
1262         }
1263 #endif
1264         debug_print("Quitting on signal %d\n", sig);
1265
1266         g_timeout_add(0, clean_quit, NULL);
1267 }
1268
1269 static void install_basic_sighandlers()
1270 {
1271 #ifndef G_OS_WIN32
1272         sigset_t    mask;
1273         struct sigaction act;
1274
1275         sigemptyset(&mask);
1276
1277 #ifdef SIGTERM
1278         sigaddset(&mask, SIGTERM);
1279 #endif
1280 #ifdef SIGINT
1281         sigaddset(&mask, SIGINT);
1282 #endif
1283 #ifdef SIGHUP
1284         sigaddset(&mask, SIGHUP);
1285 #endif
1286 #ifdef SIGPIPE
1287         sigaddset(&mask, SIGPIPE);
1288 #endif
1289
1290         act.sa_handler = quit_signal_handler;
1291         act.sa_mask    = mask;
1292         act.sa_flags   = 0;
1293
1294 #ifdef SIGTERM
1295         sigaction(SIGTERM, &act, 0);
1296 #endif
1297 #ifdef SIGINT
1298         sigaction(SIGINT, &act, 0);
1299 #endif  
1300 #ifdef SIGHUP
1301         sigaction(SIGHUP, &act, 0);
1302 #endif  
1303 #ifdef SIGPIPE
1304         sigaction(SIGPIPE, &act, 0);
1305 #endif  
1306
1307         sigprocmask(SIG_UNBLOCK, &mask, 0);
1308 #endif /* !G_OS_WIN32 */
1309 }