2004-11-23 [colin] 0.9.12cvs163.1
[claws.git] / src / main.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2004 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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 <gtk/gtkmain.h>
28 #include <gtk/gtkrc.h>
29
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <ctype.h>
34 #include <unistd.h>
35 #include <time.h>
36 #include <sys/stat.h>
37 #include <sys/types.h>
38 #include <signal.h>
39 #include "wizard.h"
40 #ifdef HAVE_STARTUP_NOTIFICATION
41 # define SN_API_NOT_YET_FROZEN
42 # include <libsn/sn-launchee.h>
43 # include <gdk/gdkx.h>
44 #endif
45
46 #include "sylpheed.h"
47 #include "intl.h"
48 #include "main.h"
49 #include "mainwindow.h"
50 #include "folderview.h"
51 #include "summaryview.h"
52 #include "prefs_common.h"
53 #include "prefs_account.h"
54 #include "prefs_actions.h"
55 #include "prefs_ext_prog.h"
56 #include "prefs_fonts.h"
57 #include "prefs_msg_colors.h"
58 #include "prefs_spelling.h"
59 #include "prefs_themes.h"
60 #include "prefs_wrapping.h"
61 #include "prefs_display_header.h"
62 #include "account.h"
63 #include "procmsg.h"
64 #include "inc.h"
65 #include "import.h"
66 #include "manage_window.h"
67 #include "alertpanel.h"
68 #include "statusbar.h"
69 #include "addressbook.h"
70 #include "compose.h"
71 #include "folder.h"
72 #include "setup.h"
73 #include "utils.h"
74 #include "gtkutils.h"
75 #include "socket.h"
76 #include "log.h"
77 #include "prefs_toolbar.h"
78 #include "plugin.h"
79 #include "mh_gtk.h"
80 #include "imap_gtk.h"
81 #include "news_gtk.h"
82 #include "matcher.h"
83
84 #if USE_OPENSSL
85 #  include "ssl.h"
86 #endif
87
88 #include "version.h"
89
90 #include "crash.h"
91
92 gchar *prog_version;
93 #ifdef CRASH_DIALOG
94 gchar *argv0;
95 #endif
96
97 #ifdef HAVE_STARTUP_NOTIFICATION
98 static SnLauncheeContext *sn_context = NULL;
99 static SnDisplay *sn_display = NULL;
100 #endif
101
102 static gint lock_socket = -1;
103 static gint lock_socket_tag = 0;
104
105 typedef enum 
106 {
107         ONLINE_MODE_DONT_CHANGE,
108         ONLINE_MODE_ONLINE,
109         ONLINE_MODE_OFFLINE
110 } OnlineMode;
111
112 static struct RemoteCmd {
113         gboolean receive;
114         gboolean receive_all;
115         gboolean compose;
116         const gchar *compose_mailto;
117         GPtrArray *attach_files;
118         gboolean status;
119         gboolean status_full;
120         GPtrArray *status_folders;
121         GPtrArray *status_full_folders;
122         gboolean send;
123         gboolean crash;
124         int online_mode;
125         gchar   *crash_params;
126 } cmd;
127
128 static void parse_cmd_opt(int argc, char *argv[]);
129
130 static gint prohibit_duplicate_launch   (void);
131 static gchar * get_crashfile_name       (void);
132 static gint lock_socket_remove          (void);
133 static void lock_socket_input_cb        (gpointer          data,
134                                          gint              source,
135                                          GdkInputCondition condition);
136 #ifndef CLAWS                                    
137 static 
138 #endif
139 gchar *get_socket_name          (void);
140
141
142 static void open_compose_new            (const gchar    *address,
143                                          GPtrArray      *attach_files);
144
145 static void send_queue                  (void);
146 static void initial_processing          (FolderItem *item, gpointer data);
147 static void quit_signal_handler         (int sig);
148 static void install_basic_sighandlers   (void);
149 static void exit_sylpheed               (MainWindow *mainwin);
150
151 #if 0
152 /* for gettext */
153 _("File `%s' already exists.\n"
154   "Can't create folder.")
155 #endif
156
157 #define MAKE_DIR_IF_NOT_EXIST(dir) \
158 { \
159         if (!is_dir_exist(dir)) { \
160                 if (is_file_exist(dir)) { \
161                         alertpanel_warning \
162                                 (_("File `%s' already exists.\n" \
163                                    "Can't create folder."), \
164                                  dir); \
165                         return 1; \
166                 } \
167                 if (make_dir(dir) < 0) \
168                         return 1; \
169         } \
170 }
171
172 static MainWindow *static_mainwindow;
173
174 #ifdef HAVE_STARTUP_NOTIFICATION
175 static void sn_error_trap_push(SnDisplay *display, Display *xdisplay)
176 {
177         gdk_error_trap_push();
178 }
179
180 static void sn_error_trap_pop(SnDisplay *display, Display *xdisplay)
181 {
182         gdk_error_trap_pop();
183 }
184
185 static void startup_notification_complete(gboolean with_window)
186 {
187         Display *xdisplay;
188         GtkWidget *hack = NULL;
189
190         if (with_window) {
191                 /* this is needed to make the startup notification leave,
192                  * if we have been launched from a menu.
193                  * We have to display a window, so let it be very little */
194                 hack = gtk_window_new(GTK_WINDOW_POPUP);
195                 gtk_widget_set_uposition(hack, 0, 0);
196                 gtk_widget_set_usize(hack, 1, 1);
197                 gtk_widget_show(hack);
198         }
199
200         xdisplay = GDK_DISPLAY();
201         sn_display = sn_display_new(xdisplay,
202                                 sn_error_trap_push,
203                                 sn_error_trap_pop);
204         sn_context = sn_launchee_context_new_from_environment(sn_display,
205                                                  DefaultScreen(xdisplay));
206
207         if (sn_context != NULL)
208         {
209                 sn_launchee_context_complete(sn_context);
210                 sn_launchee_context_unref(sn_context);
211                 sn_display_unref(sn_display);
212         }
213 }
214 #endif /* HAVE_STARTUP_NOTIFICATION */
215
216 void sylpheed_gtk_idle(void) 
217 {
218         while(gtk_events_pending())
219                 gtk_main_iteration();
220 }
221
222 int main(int argc, char *argv[])
223 {
224         gchar *userrc;
225         MainWindow *mainwin;
226         FolderView *folderview;
227
228         if (!sylpheed_init(&argc, &argv)) {
229                 return 0;
230         }
231
232         prog_version = PROG_VERSION;
233 #ifdef CRASH_DIALOG
234         argv0 = g_strdup(argv[0]);
235 #endif
236
237         parse_cmd_opt(argc, argv);
238
239 #ifdef CRASH_DIALOG
240         if (cmd.crash) {
241                 gtk_set_locale();
242                 gtk_init(&argc, &argv);
243                 crash_main(cmd.crash_params);
244                 return 0;
245         }
246         crash_install_handlers();
247 #endif
248         install_basic_sighandlers();
249
250         /* check and create unix domain socket */
251         lock_socket = prohibit_duplicate_launch();
252         if (lock_socket < 0) {
253 #ifdef HAVE_STARTUP_NOTIFICATION
254                 if(gtk_init_check(&argc, &argv))
255                         startup_notification_complete(TRUE);
256 #endif
257                 return 0;
258         }
259
260         if (cmd.status || cmd.status_full) {
261                 puts("0 Sylpheed not running.");
262                 lock_socket_remove();
263                 return 0;
264         }
265
266         gtk_set_locale();
267         gtk_init(&argc, &argv);
268
269         gdk_rgb_init();
270         gtk_widget_set_default_colormap(gdk_rgb_get_cmap());
271         gtk_widget_set_default_visual(gdk_rgb_get_visual());
272
273 #if USE_THREADS || USE_LDAP
274         g_thread_init(NULL);
275         if (!g_thread_supported())
276                 g_error(_("g_thread is not supported by glib.\n"));
277 #endif
278
279         /* parse gtkrc files */
280         userrc = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".gtkrc-2.0",
281                              NULL);
282         gtk_rc_parse(userrc);
283         g_free(userrc);
284         userrc = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".gtk",
285                              G_DIR_SEPARATOR_S, "gtkrc-2.0", NULL);
286         gtk_rc_parse(userrc);
287         g_free(userrc);
288         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, "gtkrc-2.0", NULL);
289         gtk_rc_parse(userrc);
290         g_free(userrc);
291
292         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
293         gtk_accel_map_load (userrc);
294         g_free(userrc);
295
296         gtk_settings_set_long_property(gtk_settings_get_default(), 
297                                        "gtk-can-change-accels",
298                                        (glong)TRUE, "XProperty");
299
300         CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
301
302         MAKE_DIR_IF_NOT_EXIST(RC_DIR);
303         MAKE_DIR_IF_NOT_EXIST(get_imap_cache_dir());
304         MAKE_DIR_IF_NOT_EXIST(get_news_cache_dir());
305         MAKE_DIR_IF_NOT_EXIST(get_mime_tmp_dir());
306         MAKE_DIR_IF_NOT_EXIST(get_tmp_dir());
307         MAKE_DIR_IF_NOT_EXIST(RC_DIR G_DIR_SEPARATOR_S "uidl");
308
309         set_log_file(RC_DIR G_DIR_SEPARATOR_S "sylpheed.log");
310
311         folder_system_init();
312         prefs_common_init();
313         prefs_common_read_config();
314
315         prefs_themes_init();
316         prefs_fonts_init();
317         prefs_ext_prog_init();
318         prefs_wrapping_init();
319         prefs_msg_colors_init();
320 #ifdef USE_ASPELL
321         gtkaspell_checkers_init();
322         prefs_spelling_init();
323 #endif
324         
325         sock_set_io_timeout(prefs_common.io_timeout_secs);
326
327         prefs_actions_read_config();
328         prefs_display_header_read_config();
329         /* prefs_filtering_read_config(); */
330         addressbook_read_file();
331         renderer_read_config();
332
333         gtkut_widget_init();
334
335         folderview_initialize();
336         mh_gtk_init();
337         imap_gtk_init();
338         news_gtk_init();
339                 
340         mainwin = main_window_create
341                 (prefs_common.sep_folder | prefs_common.sep_msg << 1);
342         folderview = mainwin->folderview;
343
344         /* register the callback of unix domain socket input */
345         lock_socket_tag = gdk_input_add(lock_socket,
346                                         GDK_INPUT_READ | GDK_INPUT_EXCEPTION,
347                                         lock_socket_input_cb,
348                                         mainwin);
349
350         account_read_config_all();
351
352         if (folder_read_list() < 0) {
353                 if (!run_wizard(mainwin, TRUE))
354                         exit(1);
355                 folder_write_list();
356         }
357
358         if (!account_get_list()) {
359                 if (!run_wizard(mainwin, FALSE))
360                         exit(1);
361                 account_read_config_all();
362                 if(!account_get_list())
363                         exit_sylpheed(mainwin);
364         }
365
366         account_set_missing_folder();
367         folder_set_missing_folders();
368         folderview_set(folderview);
369
370         prefs_matcher_read_config();
371
372         /* make one all-folder processing before using sylpheed */
373         main_window_cursor_wait(mainwin);
374         folder_func_to_all_folders(initial_processing, (gpointer *)mainwin);
375         main_window_cursor_normal(mainwin);
376
377         /* if Sylpheed crashed, rebuild caches */
378         if (!cmd.crash && is_file_exist(get_crashfile_name())) {
379                 debug_print("Sylpheed crashed, checking for new messages in local folders\n");
380                 folderview_check_new(NULL);
381         }
382         /* make the crash-indicator file */
383         str_write_to_file("foo", get_crashfile_name());
384
385         addressbook_read_file();
386
387         inc_autocheck_timer_init(mainwin);
388
389         /* ignore SIGPIPE signal for preventing sudden death of program */
390         signal(SIGPIPE, SIG_IGN);
391
392         if (cmd.online_mode == ONLINE_MODE_OFFLINE)
393                 main_window_toggle_work_offline(mainwin, TRUE);
394         if (cmd.online_mode == ONLINE_MODE_ONLINE)
395                 main_window_toggle_work_offline(mainwin, FALSE);
396
397         if (cmd.receive_all)
398                 inc_all_account_mail(mainwin, FALSE, 
399                                      prefs_common.newmail_notify_manu);
400         else if (prefs_common.chk_on_startup)
401                 inc_all_account_mail(mainwin, TRUE, 
402                                      prefs_common.newmail_notify_manu);
403         else if (cmd.receive)
404                 inc_mail(mainwin, prefs_common.newmail_notify_manu);
405         else
406                 gtk_widget_grab_focus(folderview->ctree);
407
408         if (cmd.compose)
409                 open_compose_new(cmd.compose_mailto, cmd.attach_files);
410         if (cmd.attach_files) {
411                 ptr_array_free_strings(cmd.attach_files);
412                 g_ptr_array_free(cmd.attach_files, TRUE);
413                 cmd.attach_files = NULL;
414         }
415         if (cmd.send)
416                 send_queue();
417         if (cmd.status_folders) {
418                 g_ptr_array_free(cmd.status_folders, TRUE);
419                 cmd.status_folders = NULL;
420         }
421         if (cmd.status_full_folders) {
422                 g_ptr_array_free(cmd.status_full_folders, TRUE);
423                 cmd.status_full_folders = NULL;
424         }
425
426         sylpheed_register_idle_function(sylpheed_gtk_idle);
427
428         prefs_toolbar_init();
429
430         plugin_load_all("GTK2");
431         
432         static_mainwindow = mainwin;
433
434 #ifdef HAVE_STARTUP_NOTIFICATION
435         startup_notification_complete(FALSE);
436 #endif
437         gtk_main();
438
439         exit_sylpheed(mainwin);
440
441         return 0;
442 }
443
444 static void save_all_caches(FolderItem *item, gpointer data)
445 {
446         if (!item->cache)
447                 return;
448         folder_item_write_cache(item);
449 }
450
451 static void exit_sylpheed(MainWindow *mainwin)
452 {
453         gchar *filename;
454
455         debug_print("shutting down\n");
456
457         inc_autocheck_timer_remove();
458
459         if (prefs_common.clean_on_exit)
460                 main_window_empty_trash(mainwin, prefs_common.ask_on_clean);
461
462         /* save prefs for opened folder */
463         if(mainwin->folderview->opened)
464         {
465                 FolderItem *item;
466
467                 item = gtk_ctree_node_get_row_data(GTK_CTREE(mainwin->folderview->ctree), mainwin->folderview->opened);
468                 summary_save_prefs_to_folderitem(mainwin->folderview->summaryview, item);
469         }
470
471         /* save all state before exiting */
472         folder_write_list();
473         folder_func_to_all_folders(save_all_caches, NULL);
474
475         main_window_get_size(mainwin);
476         main_window_get_position(mainwin);
477         prefs_common_write_config();
478         account_write_config_all();
479         addressbook_export_to_file();
480
481         filename = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
482         gtk_accel_map_save(filename);
483         g_free(filename);
484
485         /* delete temporary files */
486         remove_all_files(get_mime_tmp_dir());
487
488         close_log_file();
489
490         /* delete crashfile */
491         if (!cmd.crash)
492                 unlink(get_crashfile_name());
493
494         lock_socket_remove();
495
496         main_window_destroy(mainwin);
497         
498         plugin_unload_all("GTK2");
499
500         prefs_toolbar_done();
501
502         addressbook_destroy();
503
504         prefs_themes_done();
505         prefs_fonts_done();
506         prefs_ext_prog_done();
507         prefs_wrapping_done();
508         prefs_msg_colors_done();
509 #ifdef USE_ASPELL       
510         prefs_spelling_done();
511         gtkaspell_checkers_quit();
512 #endif
513         sylpheed_done();
514
515 }
516
517 static void parse_cmd_opt(int argc, char *argv[])
518 {
519         gint i;
520
521         for (i = 1; i < argc; i++) {
522                 if (!strncmp(argv[i], "--receive-all", 13))
523                         cmd.receive_all = TRUE;
524                 else if (!strncmp(argv[i], "--receive", 9))
525                         cmd.receive = TRUE;
526                 else if (!strncmp(argv[i], "--compose", 9)) {
527                         const gchar *p = argv[i + 1];
528
529                         cmd.compose = TRUE;
530                         cmd.compose_mailto = NULL;
531                         if (p && *p != '\0' && *p != '-') {
532                                 if (!strncmp(p, "mailto:", 7))
533                                         cmd.compose_mailto = p + 7;
534                                 else
535                                         cmd.compose_mailto = p;
536                                 i++;
537                         }
538                 } else if (!strncmp(argv[i], "--attach", 8)) {
539                         const gchar *p = argv[i + 1];
540                         gchar *file;
541
542                         while (p && *p != '\0' && *p != '-') {
543                                 if (!cmd.attach_files)
544                                         cmd.attach_files = g_ptr_array_new();
545                                 if (*p != G_DIR_SEPARATOR)
546                                         file = g_strconcat(sylpheed_get_startup_dir(),
547                                                            G_DIR_SEPARATOR_S,
548                                                            p, NULL);
549                                 else
550                                         file = g_strdup(p);
551                                 g_ptr_array_add(cmd.attach_files, file);
552                                 i++;
553                                 p = argv[i + 1];
554                         }
555                 } else if (!strncmp(argv[i], "--send", 6)) {
556                         cmd.send = TRUE;
557                 } else if (!strncmp(argv[i], "--version", 9)) {
558                         puts("Sylpheed version " VERSION);
559                         exit(0);
560                 } else if (!strncmp(argv[i], "--status-full", 13)) {
561                         const gchar *p = argv[i + 1];
562  
563                         cmd.status_full = TRUE;
564                         while (p && *p != '\0' && *p != '-') {
565                                 if (!cmd.status_full_folders)
566                                         cmd.status_full_folders =
567                                                 g_ptr_array_new();
568                                 g_ptr_array_add(cmd.status_full_folders,
569                                                 g_strdup(p));
570                                 i++;
571                                 p = argv[i + 1];
572                         }
573                 } else if (!strncmp(argv[i], "--status", 8)) {
574                         const gchar *p = argv[i + 1];
575  
576                         cmd.status = TRUE;
577                         while (p && *p != '\0' && *p != '-') {
578                                 if (!cmd.status_folders)
579                                         cmd.status_folders = g_ptr_array_new();
580                                 g_ptr_array_add(cmd.status_folders,
581                                                 g_strdup(p));
582                                 i++;
583                                 p = argv[i + 1];
584                         }
585                 } else if (!strncmp(argv[i], "--online", 8)) {
586                         cmd.online_mode = ONLINE_MODE_ONLINE;
587                 } else if (!strncmp(argv[i], "--offline", 9)) {
588                         cmd.online_mode = ONLINE_MODE_OFFLINE;
589                 } else if (!strncmp(argv[i], "--help", 6)) {
590                         gchar *base = g_path_get_basename(argv[0]);
591                         g_print(_("Usage: %s [OPTION]...\n"), base);
592
593                         puts(_("  --compose [address]    open composition window"));
594                         puts(_("  --attach file1 [file2]...\n"
595                                "                         open composition window with specified files\n"
596                                "                         attached"));
597                         puts(_("  --receive              receive new messages"));
598                         puts(_("  --receive-all          receive new messages of all accounts"));
599                         puts(_("  --send                 send all queued messages"));
600                         puts(_("  --status [folder]...   show the total number of messages"));
601                         puts(_("  --status-full [folder]...\n"
602                                "                         show the status of each folder"));
603                         puts(_("  --online               switch to online mode"));
604                         puts(_("  --offline              switch to offline mode"));
605                         puts(_("  --debug                debug mode"));
606                         puts(_("  --help                 display this help and exit"));
607                         puts(_("  --version              output version information and exit"));
608                         puts(_("  --config-dir           output configuration directory"));
609
610                         g_free(base);
611                         exit(1);
612                 } else if (!strncmp(argv[i], "--crash", 7)) {
613                         cmd.crash = TRUE;
614                         cmd.crash_params = g_strdup(argv[i + 1]);
615                         i++;
616                 } else if (!strncmp(argv[i], "--config-dir", sizeof "--config-dir" - 1)) {
617                         puts(RC_DIR);
618                         exit(0);
619                 }
620                 
621         }
622
623         if (cmd.attach_files && cmd.compose == FALSE) {
624                 cmd.compose = TRUE;
625                 cmd.compose_mailto = NULL;
626         }
627 }
628
629 static gint get_queued_message_num(void)
630 {
631         FolderItem *queue;
632
633         queue = folder_get_default_queue();
634         if (!queue) return -1;
635
636         folder_item_scan(queue);
637         return queue->total_msgs;
638 }
639
640 static void initial_processing(FolderItem *item, gpointer data)
641 {
642         MainWindow *mainwin = (MainWindow *)data;
643         gchar *buf;
644
645         g_return_if_fail(item);
646         buf = g_strdup_printf(_("Processing (%s)..."), 
647                               item->path 
648                               ? item->path 
649                               : _("top level folder"));
650         debug_print("%s\n", buf);
651         g_free(buf);
652
653         
654         if (item->prefs->enable_processing)
655                 folder_item_apply_processing(item);
656
657         debug_print("done.\n");
658         STATUSBAR_POP(mainwin);
659 }
660
661 static void draft_all_messages(void)
662 {
663         GList *compose_list = compose_get_compose_list();
664         GList *elem = NULL;
665         
666         if (compose_list) {
667                 for (elem = compose_list; elem != NULL && elem->data != NULL; 
668                      elem = elem->next) {
669                         Compose *c = (Compose*)elem->data;
670                         compose_draft(c);
671                 }
672         }       
673 }
674
675 gboolean clean_quit(gpointer data)
676 {
677         static gboolean firstrun = TRUE;
678
679         if (!firstrun)
680                 return FALSE;
681         firstrun = FALSE;
682
683         /*!< Good idea to have the main window stored in a 
684          *   static variable so we can check that variable
685          *   to see if we're really allowed to do things
686          *   that actually the spawner is supposed to 
687          *   do (like: sending mail, composing messages).
688          *   Because, really, if we're the spawnee, and
689          *   we touch GTK stuff, we're hosed. See the 
690          *   next fixme. */
691
692         /* FIXME: Use something else to signal that we're
693          * in the original spawner, and not in a spawned
694          * child. */
695         if (!static_mainwindow) 
696                 return FALSE;
697                 
698         draft_all_messages();
699
700         exit_sylpheed(static_mainwindow);
701         exit(0);
702
703         return FALSE;
704 }
705
706 void app_will_exit(GtkWidget *widget, gpointer data)
707 {
708         MainWindow *mainwin = data;
709         
710         if (compose_get_compose_list()) {
711                 gint val = alertpanel(_("Really quit?"),
712                                _("Composing message exists."),
713                                _("Draft them"), _("Discard them"), _("Don't quit"));
714                 switch (val) {
715                         case G_ALERTOTHER:
716                                 return;
717                         case G_ALERTALTERNATE:
718                                 break;
719                         default:
720                                 draft_all_messages();
721                 }
722                 
723                 manage_window_focus_in(mainwin->window, NULL, NULL);
724         }
725
726         if (prefs_common.warn_queued_on_exit && get_queued_message_num() > 0) {
727                 if (alertpanel(_("Queued messages"),
728                                _("Some unsent messages are queued. Exit now?"),
729                                _("OK"), _("Cancel"), NULL) != G_ALERTDEFAULT)
730                         return;
731                 manage_window_focus_in(mainwin->window, NULL, NULL);
732         }
733         gtk_main_quit();
734 }
735
736 /*
737  * CLAWS: want this public so crash dialog can delete the
738  * lock file too
739  */
740 #ifndef CLAWS
741 static
742 #endif
743 gchar *get_socket_name(void)
744 {
745         static gchar *filename = NULL;
746
747         if (filename == NULL) {
748                 filename = g_strdup_printf("%s%csylpheed-%d",
749                                            g_get_tmp_dir(), G_DIR_SEPARATOR,
750                                            getuid());
751         }
752
753         return filename;
754 }
755
756 static gchar *get_crashfile_name(void)
757 {
758         static gchar *filename = NULL;
759
760         if (filename == NULL) {
761                 filename = g_strdup_printf("%s%csylpheed-crashed",
762                                            get_tmp_dir(), G_DIR_SEPARATOR);
763         }
764
765         return filename;
766 }
767
768 static gint prohibit_duplicate_launch(void)
769 {
770         gint uxsock;
771         gchar *path;
772
773         path = get_socket_name();
774         uxsock = fd_connect_unix(path);
775         if (uxsock < 0) {
776                 unlink(path);
777                 return fd_open_unix(path);
778         }
779
780         /* remote command mode */
781
782         debug_print("another Sylpheed is already running.\n");
783
784         if (cmd.receive_all)
785                 fd_write_all(uxsock, "receive_all\n", 12);
786         else if (cmd.receive)
787                 fd_write_all(uxsock, "receive\n", 8);
788         else if (cmd.compose && cmd.attach_files) {
789                 gchar *str, *compose_str;
790                 gint i;
791
792                 if (cmd.compose_mailto)
793                         compose_str = g_strdup_printf("compose_attach %s\n",
794                                                       cmd.compose_mailto);
795                 else
796                         compose_str = g_strdup("compose_attach\n");
797
798                 fd_write_all(uxsock, compose_str, strlen(compose_str));
799                 g_free(compose_str);
800
801                 for (i = 0; i < cmd.attach_files->len; i++) {
802                         str = g_ptr_array_index(cmd.attach_files, i);
803                         fd_write_all(uxsock, str, strlen(str));
804                         fd_write_all(uxsock, "\n", 1);
805                 }
806
807                 fd_write_all(uxsock, ".\n", 2);
808         } else if (cmd.compose) {
809                 gchar *compose_str;
810
811                 if (cmd.compose_mailto)
812                         compose_str = g_strdup_printf
813                                 ("compose %s\n", cmd.compose_mailto);
814                 else
815                         compose_str = g_strdup("compose\n");
816
817                 fd_write_all(uxsock, compose_str, strlen(compose_str));
818                 g_free(compose_str);
819         } else if (cmd.send) {
820                 fd_write_all(uxsock, "send\n", 5);
821         } else if (cmd.online_mode == ONLINE_MODE_ONLINE) {
822                 fd_write(uxsock, "online\n", 6);
823         } else if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
824                 fd_write(uxsock, "offline\n", 7);
825         } else if (cmd.status || cmd.status_full) {
826                 gchar buf[BUFFSIZE];
827                 gint i;
828                 const gchar *command;
829                 GPtrArray *folders;
830                 gchar *folder;
831  
832                 command = cmd.status_full ? "status-full\n" : "status\n";
833                 folders = cmd.status_full ? cmd.status_full_folders :
834                         cmd.status_folders;
835  
836                 fd_write_all(uxsock, command, strlen(command));
837                 for (i = 0; folders && i < folders->len; ++i) {
838                         folder = g_ptr_array_index(folders, i);
839                         fd_write_all(uxsock, folder, strlen(folder));
840                         fd_write_all(uxsock, "\n", 1);
841                 }
842                 fd_write_all(uxsock, ".\n", 2);
843                 for (;;) {
844                         fd_gets(uxsock, buf, sizeof(buf));
845                         if (!strncmp(buf, ".\n", 2)) break;
846                         fputs(buf, stdout);
847                 }
848         } else
849                 fd_write_all(uxsock, "popup\n", 6);
850
851         fd_close(uxsock);
852         return -1;
853 }
854
855 static gint lock_socket_remove(void)
856 {
857         gchar *filename;
858
859         if (lock_socket < 0) return -1;
860
861         if (lock_socket_tag > 0)
862                 gdk_input_remove(lock_socket_tag);
863         fd_close(lock_socket);
864         filename = get_socket_name();
865         unlink(filename);
866
867         return 0;
868 }
869
870 static GPtrArray *get_folder_item_list(gint sock)
871 {
872         gchar buf[BUFFSIZE];
873         FolderItem *item;
874         GPtrArray *folders = NULL;
875
876         for (;;) {
877                 fd_gets(sock, buf, sizeof(buf));
878                 if (!strncmp(buf, ".\n", 2)) break;
879                 strretchomp(buf);
880                 if (!folders) folders = g_ptr_array_new();
881                 item = folder_find_item_from_identifier(buf);
882                 if (item)
883                         g_ptr_array_add(folders, item);
884                 else
885                         g_warning("no such folder: %s\n", buf);
886         }
887
888         return folders;
889 }
890
891 static void lock_socket_input_cb(gpointer data,
892                                  gint source,
893                                  GdkInputCondition condition)
894 {
895         MainWindow *mainwin = (MainWindow *)data;
896         gint sock;
897         gchar buf[BUFFSIZE];
898
899         sock = fd_accept(source);
900         fd_gets(sock, buf, sizeof(buf));
901
902         if (!strncmp(buf, "popup", 5)) {
903                 main_window_popup(mainwin);
904         } else if (!strncmp(buf, "receive_all", 11)) {
905                 inc_all_account_mail(mainwin, FALSE,
906                                      prefs_common.newmail_notify_manu);
907         } else if (!strncmp(buf, "receive", 7)) {
908                 inc_mail(mainwin, prefs_common.newmail_notify_manu);
909         } else if (!strncmp(buf, "compose_attach", 14)) {
910                 GPtrArray *files;
911                 gchar *mailto;
912
913                 mailto = g_strdup(buf + strlen("compose_attach") + 1);
914                 files = g_ptr_array_new();
915                 while (fd_gets(sock, buf, sizeof(buf)) > 0) {
916                         if (buf[0] == '.' && buf[1] == '\n') break;
917                         strretchomp(buf);
918                         g_ptr_array_add(files, g_strdup(buf));
919                 }
920                 open_compose_new(mailto, files);
921                 ptr_array_free_strings(files);
922                 g_ptr_array_free(files, TRUE);
923                 g_free(mailto);
924         } else if (!strncmp(buf, "compose", 7)) {
925                 open_compose_new(buf + strlen("compose") + 1, NULL);
926         } else if (!strncmp(buf, "send", 4)) {
927                 send_queue();
928         } else if (!strncmp(buf, "online", 6)) {
929                 main_window_toggle_work_offline(mainwin, FALSE);
930         } else if (!strncmp(buf, "offline", 7)) {
931                 main_window_toggle_work_offline(mainwin, TRUE);
932         } else if (!strncmp(buf, "status-full", 11) ||
933                    !strncmp(buf, "status", 6)) {
934                 gchar *status;
935                 GPtrArray *folders;
936  
937                 folders = get_folder_item_list(sock);
938                 status = folder_get_status
939                         (folders, !strncmp(buf, "status-full", 11));
940                 fd_write_all(sock, status, strlen(status));
941                 fd_write_all(sock, ".\n", 2);
942                 g_free(status);
943                 if (folders) g_ptr_array_free(folders, TRUE);
944         }
945
946         fd_close(sock);
947 }
948
949 static void open_compose_new(const gchar *address, GPtrArray *attach_files)
950 {
951         gchar *addr = NULL;
952
953         if (address) {
954                 Xstrdup_a(addr, address, return);
955                 g_strstrip(addr);
956         }
957
958         compose_new(NULL, addr, attach_files);
959 }
960
961 static void send_queue(void)
962 {
963         GList *list;
964
965         for (list = folder_get_list(); list != NULL; list = list->next) {
966                 Folder *folder = list->data;
967
968                 if (folder->queue) {
969                         gint res = procmsg_send_queue
970                                 (folder->queue, prefs_common.savemsg);
971
972                         if (res < 0)    
973                                 alertpanel_error(_("Some errors occurred while sending queued messages."));
974                         if (res)        
975                                 folder_item_scan(folder->queue);
976                 }
977         }
978 }
979
980 static void quit_signal_handler(int sig)
981 {
982         debug_print("Quitting on signal %d\n", sig);
983
984         g_timeout_add(0, clean_quit, NULL);
985 }
986
987 static void install_basic_sighandlers()
988 {
989         sigset_t    mask;
990         struct sigaction act;
991
992         sigemptyset(&mask);
993
994 #ifdef SIGTERM
995         sigaddset(&mask, SIGTERM);
996 #endif
997 #ifdef SIGINT
998         sigaddset(&mask, SIGINT);
999 #endif
1000 #ifdef SIGHUP
1001         sigaddset(&mask, SIGHUP);
1002 #endif
1003
1004         act.sa_handler = quit_signal_handler;
1005         act.sa_mask    = mask;
1006         act.sa_flags   = 0;
1007
1008 #ifdef SIGTERM
1009         sigaction(SIGTERM, &act, 0);
1010 #endif
1011 #ifdef SIGINT
1012         sigaction(SIGINT, &act, 0);
1013 #endif  
1014 #ifdef SIGHUP
1015         sigaction(SIGHUP, &act, 0);
1016 #endif  
1017
1018         sigprocmask(SIG_UNBLOCK, &mask, 0);
1019 }