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