2004-10-19 [colin] 0.9.12cvs128.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 <features.h>
27
28 #include <glib.h>
29 #include <gtk/gtkmain.h>
30 #include <gtk/gtkrc.h>
31
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <ctype.h>
36 #include <unistd.h>
37 #include <time.h>
38 #include <sys/stat.h>
39 #include <sys/types.h>
40 #include <signal.h>
41 #include "wizard.h"
42 #ifdef HAVE_STARTUP_NOTIFICATION
43 # define SN_API_NOT_YET_FROZEN
44 # include <libsn/sn-launchee.h>
45 # include <gdk/gdkx.h>
46 #endif
47
48 #include "sylpheed.h"
49 #include "intl.h"
50 #include "main.h"
51 #include "mainwindow.h"
52 #include "folderview.h"
53 #include "summaryview.h"
54 #include "prefs_common.h"
55 #include "prefs_account.h"
56 #include "prefs_actions.h"
57 #include "prefs_ext_prog.h"
58 #include "prefs_fonts.h"
59 #include "prefs_msg_colors.h"
60 #include "prefs_spelling.h"
61 #include "prefs_themes.h"
62 #include "prefs_wrapping.h"
63 #include "prefs_display_header.h"
64 #include "account.h"
65 #include "procmsg.h"
66 #include "inc.h"
67 #include "import.h"
68 #include "manage_window.h"
69 #include "alertpanel.h"
70 #include "statusbar.h"
71 #include "addressbook.h"
72 #include "compose.h"
73 #include "folder.h"
74 #include "setup.h"
75 #include "utils.h"
76 #include "gtkutils.h"
77 #include "socket.h"
78 #include "log.h"
79 #include "prefs_toolbar.h"
80 #include "plugin.h"
81 #include "mh_gtk.h"
82 #include "imap_gtk.h"
83 #include "news_gtk.h"
84 #include "matcher.h"
85
86 #if USE_OPENSSL
87 #  include "ssl.h"
88 #endif
89
90 #include "version.h"
91
92 #include "crash.h"
93
94 gchar *prog_version;
95 #ifdef CRASH_DIALOG
96 gchar *argv0;
97 #endif
98
99 #ifdef HAVE_STARTUP_NOTIFICATION
100 static SnLauncheeContext *sn_context = NULL;
101 static SnDisplay *sn_display = NULL;
102 #endif
103
104 static gint lock_socket = -1;
105 static gint lock_socket_tag = 0;
106
107 typedef enum 
108 {
109         ONLINE_MODE_DONT_CHANGE,
110         ONLINE_MODE_ONLINE,
111         ONLINE_MODE_OFFLINE
112 } OnlineMode;
113
114 static struct RemoteCmd {
115         gboolean receive;
116         gboolean receive_all;
117         gboolean compose;
118         const gchar *compose_mailto;
119         GPtrArray *attach_files;
120         gboolean status;
121         gboolean status_full;
122         GPtrArray *status_folders;
123         GPtrArray *status_full_folders;
124         gboolean send;
125         gboolean crash;
126         int online_mode;
127         gchar   *crash_params;
128 } cmd;
129
130 static void parse_cmd_opt(int argc, char *argv[]);
131
132 static gint prohibit_duplicate_launch   (void);
133 static gchar * get_crashfile_name       (void);
134 static gint lock_socket_remove          (void);
135 static void lock_socket_input_cb        (gpointer          data,
136                                          gint              source,
137                                          GdkInputCondition condition);
138 #ifndef CLAWS                                    
139 static 
140 #endif
141 gchar *get_socket_name          (void);
142
143
144 static void open_compose_new            (const gchar    *address,
145                                          GPtrArray      *attach_files);
146
147 static void send_queue                  (void);
148 static void initial_processing          (FolderItem *item, gpointer data);
149 static void quit_signal_handler         (int sig);
150 static void install_basic_sighandlers   (void);
151 static void exit_sylpheed               (MainWindow *mainwin);
152
153 #if 0
154 /* for gettext */
155 _("File `%s' already exists.\n"
156   "Can't create folder.")
157 #endif
158
159 #define MAKE_DIR_IF_NOT_EXIST(dir) \
160 { \
161         if (!is_dir_exist(dir)) { \
162                 if (is_file_exist(dir)) { \
163                         alertpanel_warning \
164                                 (_("File `%s' already exists.\n" \
165                                    "Can't create folder."), \
166                                  dir); \
167                         return 1; \
168                 } \
169                 if (make_dir(dir) < 0) \
170                         return 1; \
171         } \
172 }
173
174 static MainWindow *static_mainwindow;
175
176 #ifdef HAVE_STARTUP_NOTIFICATION
177 static void sn_error_trap_push(SnDisplay *display, Display *xdisplay)
178 {
179         gdk_error_trap_push();
180 }
181
182 static void sn_error_trap_pop(SnDisplay *display, Display *xdisplay)
183 {
184         gdk_error_trap_pop();
185 }
186
187 static void startup_notification_complete(gboolean with_window)
188 {
189         Display *xdisplay;
190         GtkWidget *hack = NULL;
191
192         if (with_window) {
193                 /* this is needed to make the startup notification leave,
194                  * if we have been launched from a menu.
195                  * We have to display a window, so let it be very little */
196                 hack = gtk_window_new(GTK_WINDOW_POPUP);
197                 gtk_widget_set_uposition(hack, 0, 0);
198                 gtk_widget_set_usize(hack, 1, 1);
199                 gtk_widget_show(hack);
200         }
201
202         xdisplay = GDK_DISPLAY();
203         sn_display = sn_display_new(xdisplay,
204                                 sn_error_trap_push,
205                                 sn_error_trap_pop);
206         sn_context = sn_launchee_context_new_from_environment(sn_display,
207                                                  DefaultScreen(xdisplay));
208
209         if (sn_context != NULL)
210         {
211                 sn_launchee_context_complete(sn_context);
212                 sn_launchee_context_unref(sn_context);
213                 sn_display_unref(sn_display);
214         }
215 }
216 #endif /* HAVE_STARTUP_NOTIFICATION */
217
218 void sylpheed_gtk_idle(void) 
219 {
220         while(gtk_events_pending())
221                 gtk_main_iteration();
222 }
223
224 int main(int argc, char *argv[])
225 {
226         gchar *userrc;
227         MainWindow *mainwin;
228         FolderView *folderview;
229
230         if (!sylpheed_init(&argc, &argv)) {
231                 return 0;
232         }
233
234         prog_version = PROG_VERSION;
235 #ifdef CRASH_DIALOG
236         argv0 = g_strdup(argv[0]);
237 #endif
238
239         parse_cmd_opt(argc, argv);
240
241 #ifdef CRASH_DIALOG
242         if (cmd.crash) {
243                 gtk_set_locale();
244                 gtk_init(&argc, &argv);
245                 crash_main(cmd.crash_params);
246                 return 0;
247         }
248         crash_install_handlers();
249 #endif
250         install_basic_sighandlers();
251
252         /* check and create unix domain socket */
253         lock_socket = prohibit_duplicate_launch();
254         if (lock_socket < 0) {
255 #ifdef HAVE_STARTUP_NOTIFICATION
256                 if(gtk_init_check(&argc, &argv))
257                         startup_notification_complete(TRUE);
258 #endif
259                 return 0;
260         }
261         if (cmd.status || cmd.status_full) {
262                 puts("0 Sylpheed not running.");
263                 lock_socket_remove();
264                 return 0;
265         }
266
267         gtk_set_locale();
268         gtk_init(&argc, &argv);
269
270         gdk_rgb_init();
271         gtk_widget_set_default_colormap(gdk_rgb_get_cmap());
272         gtk_widget_set_default_visual(gdk_rgb_get_visual());
273
274 #if USE_THREADS || USE_LDAP
275         g_thread_init(NULL);
276         if (!g_thread_supported())
277                 g_error(_("g_thread is not supported by glib.\n"));
278 #endif
279
280         /* parse gtkrc files */
281         userrc = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".gtkrc-2.0",
282                              NULL);
283         gtk_rc_parse(userrc);
284         g_free(userrc);
285         userrc = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".gtk",
286                              G_DIR_SEPARATOR_S, "gtkrc-2.0", NULL);
287         gtk_rc_parse(userrc);
288         g_free(userrc);
289         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, "gtkrc-2.0", NULL);
290         gtk_rc_parse(userrc);
291         g_free(userrc);
292
293         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
294         gtk_accel_map_load (userrc);
295         g_free(userrc);
296
297         gtk_settings_set_long_property(gtk_settings_get_default(), 
298                                        "gtk-can-change-accels",
299                                        (glong)TRUE, "XProperty");
300
301         CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
302
303         MAKE_DIR_IF_NOT_EXIST(RC_DIR);
304         MAKE_DIR_IF_NOT_EXIST(get_imap_cache_dir());
305         MAKE_DIR_IF_NOT_EXIST(get_news_cache_dir());
306         MAKE_DIR_IF_NOT_EXIST(get_mime_tmp_dir());
307         MAKE_DIR_IF_NOT_EXIST(get_tmp_dir());
308         MAKE_DIR_IF_NOT_EXIST(RC_DIR G_DIR_SEPARATOR_S "uidl");
309
310         set_log_file(RC_DIR G_DIR_SEPARATOR_S "sylpheed.log");
311
312         folder_system_init();
313         prefs_common_init();
314         prefs_common_read_config();
315
316         prefs_themes_init();
317         prefs_fonts_init();
318         prefs_ext_prog_init();
319         prefs_wrapping_init();
320         prefs_msg_colors_init();
321 #ifdef USE_ASPELL
322         gtkaspell_checkers_init();
323         prefs_spelling_init();
324 #endif
325         
326         sock_set_io_timeout(prefs_common.io_timeout_secs);
327
328         prefs_actions_read_config();
329         prefs_display_header_read_config();
330         /* prefs_filtering_read_config(); */
331         addressbook_read_file();
332         renderer_read_config();
333
334         gtkut_widget_init();
335
336         folderview_initialize();
337         mh_gtk_init();
338         imap_gtk_init();
339         news_gtk_init();
340                 
341         mainwin = main_window_create
342                 (prefs_common.sep_folder | prefs_common.sep_msg << 1);
343         folderview = mainwin->folderview;
344
345         /* register the callback of unix domain socket input */
346         lock_socket_tag = gdk_input_add(lock_socket,
347                                         GDK_INPUT_READ | GDK_INPUT_EXCEPTION,
348                                         lock_socket_input_cb,
349                                         mainwin);
350
351         account_read_config_all();
352
353         if (folder_read_list() < 0) {
354                 if (!run_wizard(mainwin, TRUE))
355                         exit(1);
356                 folder_write_list();
357         }
358
359         if (!account_get_list()) {
360                 if (!run_wizard(mainwin, FALSE))
361                         exit(1);
362                 account_read_config_all();
363                 if(!account_get_list())
364                         exit_sylpheed(mainwin);
365         }
366
367         account_set_missing_folder();
368         folder_set_missing_folders();
369         folderview_set(folderview);
370
371         prefs_matcher_read_config();
372
373         /* make one all-folder processing before using sylpheed */
374         folder_func_to_all_folders(initial_processing, (gpointer *)mainwin);
375
376         /* if Sylpheed crashed, rebuild caches */
377         if (!cmd.crash && is_file_exist(get_crashfile_name())) {
378                 debug_print("Sylpheed crashed, checking for new messages in local folders\n");
379                 folderview_check_new(NULL);
380         }
381         /* make the crash-indicator file */
382         str_write_to_file("foo", get_crashfile_name());
383
384         addressbook_read_file();
385
386         inc_autocheck_timer_init(mainwin);
387
388         /* ignore SIGPIPE signal for preventing sudden death of program */
389         signal(SIGPIPE, SIG_IGN);
390
391         if (cmd.online_mode == ONLINE_MODE_OFFLINE)
392                 main_window_toggle_work_offline(mainwin, TRUE);
393         if (cmd.online_mode == ONLINE_MODE_ONLINE)
394                 main_window_toggle_work_offline(mainwin, FALSE);
395
396         if (cmd.receive_all)
397                 inc_all_account_mail(mainwin, FALSE, 
398                                      prefs_common.newmail_notify_manu);
399         else if (prefs_common.chk_on_startup)
400                 inc_all_account_mail(mainwin, TRUE, 
401                                      prefs_common.newmail_notify_manu);
402         else if (cmd.receive)
403                 inc_mail(mainwin, prefs_common.newmail_notify_manu);
404         else
405                 gtk_widget_grab_focus(folderview->ctree);
406
407         if (cmd.compose)
408                 open_compose_new(cmd.compose_mailto, cmd.attach_files);
409         if (cmd.attach_files) {
410                 ptr_array_free_strings(cmd.attach_files);
411                 g_ptr_array_free(cmd.attach_files, TRUE);
412                 cmd.attach_files = NULL;
413         }
414         if (cmd.send)
415                 send_queue();
416         if (cmd.status_folders) {
417                 g_ptr_array_free(cmd.status_folders, TRUE);
418                 cmd.status_folders = NULL;
419         }
420         if (cmd.status_full_folders) {
421                 g_ptr_array_free(cmd.status_full_folders, TRUE);
422                 cmd.status_full_folders = NULL;
423         }
424
425         sylpheed_register_idle_function(sylpheed_gtk_idle);
426
427         prefs_toolbar_init();
428
429         plugin_load_all("GTK2");
430         
431         static_mainwindow = mainwin;
432
433 #ifdef HAVE_STARTUP_NOTIFICATION
434         startup_notification_complete(FALSE);
435 #endif
436         gtk_main();
437
438         exit_sylpheed(mainwin);
439
440         return 0;
441 }
442
443 static void save_all_caches(FolderItem *item, gpointer data)
444 {
445         if (!item->cache)
446                 return;
447         folder_item_write_cache(item);
448 }
449
450 static void exit_sylpheed(MainWindow *mainwin)
451 {
452         gchar *filename;
453
454         debug_print("shutting down\n");
455
456         inc_autocheck_timer_remove();
457
458         if (prefs_common.clean_on_exit)
459                 main_window_empty_trash(mainwin, prefs_common.ask_on_clean);
460
461         /* save prefs for opened folder */
462         if(mainwin->folderview->opened)
463         {
464                 FolderItem *item;
465
466                 item = gtk_ctree_node_get_row_data(GTK_CTREE(mainwin->folderview->ctree), mainwin->folderview->opened);
467                 summary_save_prefs_to_folderitem(mainwin->folderview->summaryview, item);
468         }
469
470         /* save all state before exiting */
471         folder_write_list();
472         folder_func_to_all_folders(save_all_caches, NULL);
473
474         main_window_get_size(mainwin);
475         main_window_get_position(mainwin);
476         prefs_common_write_config();
477         account_write_config_all();
478         addressbook_export_to_file();
479
480         filename = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
481         gtk_accel_map_save(filename);
482         g_free(filename);
483
484         /* delete temporary files */
485         remove_all_files(get_mime_tmp_dir());
486
487         close_log_file();
488
489         /* delete crashfile */
490         if (!cmd.crash)
491                 unlink(get_crashfile_name());
492
493         lock_socket_remove();
494
495         main_window_destroy(mainwin);
496         
497         plugin_unload_all("GTK2");
498
499         prefs_toolbar_done();
500
501         addressbook_destroy();
502
503         prefs_themes_done();
504         prefs_fonts_done();
505         prefs_ext_prog_done();
506         prefs_wrapping_done();
507         prefs_msg_colors_done();
508 #ifdef USE_ASPELL       
509         prefs_spelling_done();
510         gtkaspell_checkers_quit();
511 #endif
512         sylpheed_done();
513
514 }
515
516 static void parse_cmd_opt(int argc, char *argv[])
517 {
518         gint i;
519
520         for (i = 1; i < argc; i++) {
521                 if (!strncmp(argv[i], "--receive-all", 13))
522                         cmd.receive_all = TRUE;
523                 else if (!strncmp(argv[i], "--receive", 9))
524                         cmd.receive = TRUE;
525                 else if (!strncmp(argv[i], "--compose", 9)) {
526                         const gchar *p = argv[i + 1];
527
528                         cmd.compose = TRUE;
529                         cmd.compose_mailto = NULL;
530                         if (p && *p != '\0' && *p != '-') {
531                                 if (!strncmp(p, "mailto:", 7))
532                                         cmd.compose_mailto = p + 7;
533                                 else
534                                         cmd.compose_mailto = p;
535                                 i++;
536                         }
537                 } else if (!strncmp(argv[i], "--attach", 8)) {
538                         const gchar *p = argv[i + 1];
539                         gchar *file;
540
541                         while (p && *p != '\0' && *p != '-') {
542                                 if (!cmd.attach_files)
543                                         cmd.attach_files = g_ptr_array_new();
544                                 if (*p != G_DIR_SEPARATOR)
545                                         file = g_strconcat(sylpheed_get_startup_dir(),
546                                                            G_DIR_SEPARATOR_S,
547                                                            p, NULL);
548                                 else
549                                         file = g_strdup(p);
550                                 g_ptr_array_add(cmd.attach_files, file);
551                                 i++;
552                                 p = argv[i + 1];
553                         }
554                 } else if (!strncmp(argv[i], "--send", 6)) {
555                         cmd.send = TRUE;
556                 } else if (!strncmp(argv[i], "--version", 9)) {
557                         puts("Sylpheed version " VERSION);
558                         exit(0);
559                 } else if (!strncmp(argv[i], "--status-full", 13)) {
560                         const gchar *p = argv[i + 1];
561  
562                         cmd.status_full = TRUE;
563                         while (p && *p != '\0' && *p != '-') {
564                                 if (!cmd.status_full_folders)
565                                         cmd.status_full_folders =
566                                                 g_ptr_array_new();
567                                 g_ptr_array_add(cmd.status_full_folders,
568                                                 g_strdup(p));
569                                 i++;
570                                 p = argv[i + 1];
571                         }
572                 } else if (!strncmp(argv[i], "--status", 8)) {
573                         const gchar *p = argv[i + 1];
574  
575                         cmd.status = TRUE;
576                         while (p && *p != '\0' && *p != '-') {
577                                 if (!cmd.status_folders)
578                                         cmd.status_folders = g_ptr_array_new();
579                                 g_ptr_array_add(cmd.status_folders,
580                                                 g_strdup(p));
581                                 i++;
582                                 p = argv[i + 1];
583                         }
584                 } else if (!strncmp(argv[i], "--online", 8)) {
585                         cmd.online_mode = ONLINE_MODE_ONLINE;
586                 } else if (!strncmp(argv[i], "--offline", 9)) {
587                         cmd.online_mode = ONLINE_MODE_OFFLINE;
588                 } else if (!strncmp(argv[i], "--help", 6)) {
589                         g_print(_("Usage: %s [OPTION]...\n"),
590                                 g_basename(argv[0]));
591
592                         puts(_("  --compose [address]    open composition window"));
593                         puts(_("  --attach file1 [file2]...\n"
594                                "                         open composition window with specified files\n"
595                                "                         attached"));
596                         puts(_("  --receive              receive new messages"));
597                         puts(_("  --receive-all          receive new messages of all accounts"));
598                         puts(_("  --send                 send all queued messages"));
599                         puts(_("  --status [folder]...   show the total number of messages"));
600                         puts(_("  --status-full [folder]...\n"
601                                "                         show the status of each folder"));
602                         puts(_("  --online               switch to online mode"));
603                         puts(_("  --offline              switch to offline mode"));
604                         puts(_("  --debug                debug mode"));
605                         puts(_("  --help                 display this help and exit"));
606                         puts(_("  --version              output version information and exit"));
607                         puts(_("  --config-dir           output configuration directory"));
608
609                         exit(1);
610                 } else if (!strncmp(argv[i], "--crash", 7)) {
611                         cmd.crash = TRUE;
612                         cmd.crash_params = g_strdup(argv[i + 1]);
613                         i++;
614                 } else if (!strncmp(argv[i], "--config-dir", sizeof "--config-dir" - 1)) {
615                         puts(RC_DIR);
616                         exit(0);
617                 }
618                 
619         }
620
621         if (cmd.attach_files && cmd.compose == FALSE) {
622                 cmd.compose = TRUE;
623                 cmd.compose_mailto = NULL;
624         }
625 }
626
627 static gint get_queued_message_num(void)
628 {
629         FolderItem *queue;
630
631         queue = folder_get_default_queue();
632         if (!queue) return -1;
633
634         folder_item_scan(queue);
635         return queue->total_msgs;
636 }
637
638 static void initial_processing(FolderItem *item, gpointer data)
639 {
640         MainWindow *mainwin = (MainWindow *)data;
641         gchar *buf;
642
643         g_return_if_fail(item);
644         buf = g_strdup_printf(_("Processing (%s)..."), 
645                               item->path 
646                               ? item->path 
647                               : _("top level folder"));
648         debug_print("%s\n", buf);
649         g_free(buf);
650
651         main_window_cursor_wait(mainwin);
652         
653         if (item->prefs->enable_processing)
654                 folder_item_apply_processing(item);
655
656         debug_print("done.\n");
657         STATUSBAR_POP(mainwin);
658         main_window_cursor_normal(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 }