2004-10-27 [paul] 0.9.12cvs134.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         folder_func_to_all_folders(initial_processing, (gpointer *)mainwin);
374
375         /* if Sylpheed crashed, rebuild caches */
376         if (!cmd.crash && is_file_exist(get_crashfile_name())) {
377                 debug_print("Sylpheed crashed, checking for new messages in local folders\n");
378                 folderview_check_new(NULL);
379         }
380         /* make the crash-indicator file */
381         str_write_to_file("foo", get_crashfile_name());
382
383         addressbook_read_file();
384
385         inc_autocheck_timer_init(mainwin);
386
387         /* ignore SIGPIPE signal for preventing sudden death of program */
388         signal(SIGPIPE, SIG_IGN);
389
390         if (cmd.online_mode == ONLINE_MODE_OFFLINE)
391                 main_window_toggle_work_offline(mainwin, TRUE);
392         if (cmd.online_mode == ONLINE_MODE_ONLINE)
393                 main_window_toggle_work_offline(mainwin, FALSE);
394
395         if (cmd.receive_all)
396                 inc_all_account_mail(mainwin, FALSE, 
397                                      prefs_common.newmail_notify_manu);
398         else if (prefs_common.chk_on_startup)
399                 inc_all_account_mail(mainwin, TRUE, 
400                                      prefs_common.newmail_notify_manu);
401         else if (cmd.receive)
402                 inc_mail(mainwin, prefs_common.newmail_notify_manu);
403         else
404                 gtk_widget_grab_focus(folderview->ctree);
405
406         if (cmd.compose)
407                 open_compose_new(cmd.compose_mailto, cmd.attach_files);
408         if (cmd.attach_files) {
409                 ptr_array_free_strings(cmd.attach_files);
410                 g_ptr_array_free(cmd.attach_files, TRUE);
411                 cmd.attach_files = NULL;
412         }
413         if (cmd.send)
414                 send_queue();
415         if (cmd.status_folders) {
416                 g_ptr_array_free(cmd.status_folders, TRUE);
417                 cmd.status_folders = NULL;
418         }
419         if (cmd.status_full_folders) {
420                 g_ptr_array_free(cmd.status_full_folders, TRUE);
421                 cmd.status_full_folders = NULL;
422         }
423
424         sylpheed_register_idle_function(sylpheed_gtk_idle);
425
426         prefs_toolbar_init();
427
428         plugin_load_all("GTK2");
429         
430         static_mainwindow = mainwin;
431
432 #ifdef HAVE_STARTUP_NOTIFICATION
433         startup_notification_complete(FALSE);
434 #endif
435         gtk_main();
436
437         exit_sylpheed(mainwin);
438
439         return 0;
440 }
441
442 static void save_all_caches(FolderItem *item, gpointer data)
443 {
444         if (!item->cache)
445                 return;
446         folder_item_write_cache(item);
447 }
448
449 static void exit_sylpheed(MainWindow *mainwin)
450 {
451         gchar *filename;
452
453         debug_print("shutting down\n");
454
455         inc_autocheck_timer_remove();
456
457         if (prefs_common.clean_on_exit)
458                 main_window_empty_trash(mainwin, prefs_common.ask_on_clean);
459
460         /* save prefs for opened folder */
461         if(mainwin->folderview->opened)
462         {
463                 FolderItem *item;
464
465                 item = gtk_ctree_node_get_row_data(GTK_CTREE(mainwin->folderview->ctree), mainwin->folderview->opened);
466                 summary_save_prefs_to_folderitem(mainwin->folderview->summaryview, item);
467         }
468
469         /* save all state before exiting */
470         folder_write_list();
471         folder_func_to_all_folders(save_all_caches, NULL);
472
473         main_window_get_size(mainwin);
474         main_window_get_position(mainwin);
475         prefs_common_write_config();
476         account_write_config_all();
477         addressbook_export_to_file();
478
479         filename = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
480         gtk_accel_map_save(filename);
481         g_free(filename);
482
483         /* delete temporary files */
484         remove_all_files(get_mime_tmp_dir());
485
486         close_log_file();
487
488         /* delete crashfile */
489         if (!cmd.crash)
490                 unlink(get_crashfile_name());
491
492         lock_socket_remove();
493
494         main_window_destroy(mainwin);
495         
496         plugin_unload_all("GTK2");
497
498         prefs_toolbar_done();
499
500         addressbook_destroy();
501
502         prefs_themes_done();
503         prefs_fonts_done();
504         prefs_ext_prog_done();
505         prefs_wrapping_done();
506         prefs_msg_colors_done();
507 #ifdef USE_ASPELL       
508         prefs_spelling_done();
509         gtkaspell_checkers_quit();
510 #endif
511         sylpheed_done();
512
513 }
514
515 static void parse_cmd_opt(int argc, char *argv[])
516 {
517         gint i;
518
519         for (i = 1; i < argc; i++) {
520                 if (!strncmp(argv[i], "--receive-all", 13))
521                         cmd.receive_all = TRUE;
522                 else if (!strncmp(argv[i], "--receive", 9))
523                         cmd.receive = TRUE;
524                 else if (!strncmp(argv[i], "--compose", 9)) {
525                         const gchar *p = argv[i + 1];
526
527                         cmd.compose = TRUE;
528                         cmd.compose_mailto = NULL;
529                         if (p && *p != '\0' && *p != '-') {
530                                 if (!strncmp(p, "mailto:", 7))
531                                         cmd.compose_mailto = p + 7;
532                                 else
533                                         cmd.compose_mailto = p;
534                                 i++;
535                         }
536                 } else if (!strncmp(argv[i], "--attach", 8)) {
537                         const gchar *p = argv[i + 1];
538                         gchar *file;
539
540                         while (p && *p != '\0' && *p != '-') {
541                                 if (!cmd.attach_files)
542                                         cmd.attach_files = g_ptr_array_new();
543                                 if (*p != G_DIR_SEPARATOR)
544                                         file = g_strconcat(sylpheed_get_startup_dir(),
545                                                            G_DIR_SEPARATOR_S,
546                                                            p, NULL);
547                                 else
548                                         file = g_strdup(p);
549                                 g_ptr_array_add(cmd.attach_files, file);
550                                 i++;
551                                 p = argv[i + 1];
552                         }
553                 } else if (!strncmp(argv[i], "--send", 6)) {
554                         cmd.send = TRUE;
555                 } else if (!strncmp(argv[i], "--version", 9)) {
556                         puts("Sylpheed version " VERSION);
557                         exit(0);
558                 } else if (!strncmp(argv[i], "--status-full", 13)) {
559                         const gchar *p = argv[i + 1];
560  
561                         cmd.status_full = TRUE;
562                         while (p && *p != '\0' && *p != '-') {
563                                 if (!cmd.status_full_folders)
564                                         cmd.status_full_folders =
565                                                 g_ptr_array_new();
566                                 g_ptr_array_add(cmd.status_full_folders,
567                                                 g_strdup(p));
568                                 i++;
569                                 p = argv[i + 1];
570                         }
571                 } else if (!strncmp(argv[i], "--status", 8)) {
572                         const gchar *p = argv[i + 1];
573  
574                         cmd.status = TRUE;
575                         while (p && *p != '\0' && *p != '-') {
576                                 if (!cmd.status_folders)
577                                         cmd.status_folders = g_ptr_array_new();
578                                 g_ptr_array_add(cmd.status_folders,
579                                                 g_strdup(p));
580                                 i++;
581                                 p = argv[i + 1];
582                         }
583                 } else if (!strncmp(argv[i], "--online", 8)) {
584                         cmd.online_mode = ONLINE_MODE_ONLINE;
585                 } else if (!strncmp(argv[i], "--offline", 9)) {
586                         cmd.online_mode = ONLINE_MODE_OFFLINE;
587                 } else if (!strncmp(argv[i], "--help", 6)) {
588                         g_print(_("Usage: %s [OPTION]...\n"),
589                                 g_basename(argv[0]));
590
591                         puts(_("  --compose [address]    open composition window"));
592                         puts(_("  --attach file1 [file2]...\n"
593                                "                         open composition window with specified files\n"
594                                "                         attached"));
595                         puts(_("  --receive              receive new messages"));
596                         puts(_("  --receive-all          receive new messages of all accounts"));
597                         puts(_("  --send                 send all queued messages"));
598                         puts(_("  --status [folder]...   show the total number of messages"));
599                         puts(_("  --status-full [folder]...\n"
600                                "                         show the status of each folder"));
601                         puts(_("  --online               switch to online mode"));
602                         puts(_("  --offline              switch to offline mode"));
603                         puts(_("  --debug                debug mode"));
604                         puts(_("  --help                 display this help and exit"));
605                         puts(_("  --version              output version information and exit"));
606                         puts(_("  --config-dir           output configuration directory"));
607
608                         exit(1);
609                 } else if (!strncmp(argv[i], "--crash", 7)) {
610                         cmd.crash = TRUE;
611                         cmd.crash_params = g_strdup(argv[i + 1]);
612                         i++;
613                 } else if (!strncmp(argv[i], "--config-dir", sizeof "--config-dir" - 1)) {
614                         puts(RC_DIR);
615                         exit(0);
616                 }
617                 
618         }
619
620         if (cmd.attach_files && cmd.compose == FALSE) {
621                 cmd.compose = TRUE;
622                 cmd.compose_mailto = NULL;
623         }
624 }
625
626 static gint get_queued_message_num(void)
627 {
628         FolderItem *queue;
629
630         queue = folder_get_default_queue();
631         if (!queue) return -1;
632
633         folder_item_scan(queue);
634         return queue->total_msgs;
635 }
636
637 static void initial_processing(FolderItem *item, gpointer data)
638 {
639         MainWindow *mainwin = (MainWindow *)data;
640         gchar *buf;
641
642         g_return_if_fail(item);
643         buf = g_strdup_printf(_("Processing (%s)..."), 
644                               item->path 
645                               ? item->path 
646                               : _("top level folder"));
647         debug_print("%s\n", buf);
648         g_free(buf);
649
650         main_window_cursor_wait(mainwin);
651         
652         if (item->prefs->enable_processing)
653                 folder_item_apply_processing(item);
654
655         debug_print("done.\n");
656         STATUSBAR_POP(mainwin);
657         main_window_cursor_normal(mainwin);
658 }
659
660 static void draft_all_messages(void)
661 {
662         GList *compose_list = compose_get_compose_list();
663         GList *elem = NULL;
664         
665         if (compose_list) {
666                 for (elem = compose_list; elem != NULL && elem->data != NULL; 
667                      elem = elem->next) {
668                         Compose *c = (Compose*)elem->data;
669                         compose_draft(c);
670                 }
671         }       
672 }
673
674 gboolean clean_quit(gpointer data)
675 {
676         static gboolean firstrun = TRUE;
677
678         if (!firstrun)
679                 return FALSE;
680         firstrun = FALSE;
681
682         /*!< Good idea to have the main window stored in a 
683          *   static variable so we can check that variable
684          *   to see if we're really allowed to do things
685          *   that actually the spawner is supposed to 
686          *   do (like: sending mail, composing messages).
687          *   Because, really, if we're the spawnee, and
688          *   we touch GTK stuff, we're hosed. See the 
689          *   next fixme. */
690
691         /* FIXME: Use something else to signal that we're
692          * in the original spawner, and not in a spawned
693          * child. */
694         if (!static_mainwindow) 
695                 return FALSE;
696                 
697         draft_all_messages();
698
699         exit_sylpheed(static_mainwindow);
700         exit(0);
701
702         return FALSE;
703 }
704
705 void app_will_exit(GtkWidget *widget, gpointer data)
706 {
707         MainWindow *mainwin = data;
708         
709         if (compose_get_compose_list()) {
710                 gint val = alertpanel(_("Really quit?"),
711                                _("Composing message exists."),
712                                _("Draft them"), _("Discard them"), _("Don't quit"));
713                 switch (val) {
714                         case G_ALERTOTHER:
715                                 return;
716                         case G_ALERTALTERNATE:
717                                 break;
718                         default:
719                                 draft_all_messages();
720                 }
721                 
722                 manage_window_focus_in(mainwin->window, NULL, NULL);
723         }
724
725         if (prefs_common.warn_queued_on_exit && get_queued_message_num() > 0) {
726                 if (alertpanel(_("Queued messages"),
727                                _("Some unsent messages are queued. Exit now?"),
728                                _("OK"), _("Cancel"), NULL) != G_ALERTDEFAULT)
729                         return;
730                 manage_window_focus_in(mainwin->window, NULL, NULL);
731         }
732         gtk_main_quit();
733 }
734
735 /*
736  * CLAWS: want this public so crash dialog can delete the
737  * lock file too
738  */
739 #ifndef CLAWS
740 static
741 #endif
742 gchar *get_socket_name(void)
743 {
744         static gchar *filename = NULL;
745
746         if (filename == NULL) {
747                 filename = g_strdup_printf("%s%csylpheed-%d",
748                                            g_get_tmp_dir(), G_DIR_SEPARATOR,
749                                            getuid());
750         }
751
752         return filename;
753 }
754
755 static gchar *get_crashfile_name(void)
756 {
757         static gchar *filename = NULL;
758
759         if (filename == NULL) {
760                 filename = g_strdup_printf("%s%csylpheed-crashed",
761                                            get_tmp_dir(), G_DIR_SEPARATOR);
762         }
763
764         return filename;
765 }
766
767 static gint prohibit_duplicate_launch(void)
768 {
769         gint uxsock;
770         gchar *path;
771
772         path = get_socket_name();
773         uxsock = fd_connect_unix(path);
774         if (uxsock < 0) {
775                 unlink(path);
776                 return fd_open_unix(path);
777         }
778
779         /* remote command mode */
780
781         debug_print("another Sylpheed is already running.\n");
782
783         if (cmd.receive_all)
784                 fd_write_all(uxsock, "receive_all\n", 12);
785         else if (cmd.receive)
786                 fd_write_all(uxsock, "receive\n", 8);
787         else if (cmd.compose && cmd.attach_files) {
788                 gchar *str, *compose_str;
789                 gint i;
790
791                 if (cmd.compose_mailto)
792                         compose_str = g_strdup_printf("compose_attach %s\n",
793                                                       cmd.compose_mailto);
794                 else
795                         compose_str = g_strdup("compose_attach\n");
796
797                 fd_write_all(uxsock, compose_str, strlen(compose_str));
798                 g_free(compose_str);
799
800                 for (i = 0; i < cmd.attach_files->len; i++) {
801                         str = g_ptr_array_index(cmd.attach_files, i);
802                         fd_write_all(uxsock, str, strlen(str));
803                         fd_write_all(uxsock, "\n", 1);
804                 }
805
806                 fd_write_all(uxsock, ".\n", 2);
807         } else if (cmd.compose) {
808                 gchar *compose_str;
809
810                 if (cmd.compose_mailto)
811                         compose_str = g_strdup_printf
812                                 ("compose %s\n", cmd.compose_mailto);
813                 else
814                         compose_str = g_strdup("compose\n");
815
816                 fd_write_all(uxsock, compose_str, strlen(compose_str));
817                 g_free(compose_str);
818         } else if (cmd.send) {
819                 fd_write_all(uxsock, "send\n", 5);
820         } else if (cmd.online_mode == ONLINE_MODE_ONLINE) {
821                 fd_write(uxsock, "online\n", 6);
822         } else if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
823                 fd_write(uxsock, "offline\n", 7);
824         } else if (cmd.status || cmd.status_full) {
825                 gchar buf[BUFFSIZE];
826                 gint i;
827                 const gchar *command;
828                 GPtrArray *folders;
829                 gchar *folder;
830  
831                 command = cmd.status_full ? "status-full\n" : "status\n";
832                 folders = cmd.status_full ? cmd.status_full_folders :
833                         cmd.status_folders;
834  
835                 fd_write_all(uxsock, command, strlen(command));
836                 for (i = 0; folders && i < folders->len; ++i) {
837                         folder = g_ptr_array_index(folders, i);
838                         fd_write_all(uxsock, folder, strlen(folder));
839                         fd_write_all(uxsock, "\n", 1);
840                 }
841                 fd_write_all(uxsock, ".\n", 2);
842                 for (;;) {
843                         fd_gets(uxsock, buf, sizeof(buf));
844                         if (!strncmp(buf, ".\n", 2)) break;
845                         fputs(buf, stdout);
846                 }
847         } else
848                 fd_write_all(uxsock, "popup\n", 6);
849
850         fd_close(uxsock);
851         return -1;
852 }
853
854 static gint lock_socket_remove(void)
855 {
856         gchar *filename;
857
858         if (lock_socket < 0) return -1;
859
860         if (lock_socket_tag > 0)
861                 gdk_input_remove(lock_socket_tag);
862         fd_close(lock_socket);
863         filename = get_socket_name();
864         unlink(filename);
865
866         return 0;
867 }
868
869 static GPtrArray *get_folder_item_list(gint sock)
870 {
871         gchar buf[BUFFSIZE];
872         FolderItem *item;
873         GPtrArray *folders = NULL;
874
875         for (;;) {
876                 fd_gets(sock, buf, sizeof(buf));
877                 if (!strncmp(buf, ".\n", 2)) break;
878                 strretchomp(buf);
879                 if (!folders) folders = g_ptr_array_new();
880                 item = folder_find_item_from_identifier(buf);
881                 if (item)
882                         g_ptr_array_add(folders, item);
883                 else
884                         g_warning("no such folder: %s\n", buf);
885         }
886
887         return folders;
888 }
889
890 static void lock_socket_input_cb(gpointer data,
891                                  gint source,
892                                  GdkInputCondition condition)
893 {
894         MainWindow *mainwin = (MainWindow *)data;
895         gint sock;
896         gchar buf[BUFFSIZE];
897
898         sock = fd_accept(source);
899         fd_gets(sock, buf, sizeof(buf));
900
901         if (!strncmp(buf, "popup", 5)) {
902                 main_window_popup(mainwin);
903         } else if (!strncmp(buf, "receive_all", 11)) {
904                 inc_all_account_mail(mainwin, FALSE,
905                                      prefs_common.newmail_notify_manu);
906         } else if (!strncmp(buf, "receive", 7)) {
907                 inc_mail(mainwin, prefs_common.newmail_notify_manu);
908         } else if (!strncmp(buf, "compose_attach", 14)) {
909                 GPtrArray *files;
910                 gchar *mailto;
911
912                 mailto = g_strdup(buf + strlen("compose_attach") + 1);
913                 files = g_ptr_array_new();
914                 while (fd_gets(sock, buf, sizeof(buf)) > 0) {
915                         if (buf[0] == '.' && buf[1] == '\n') break;
916                         strretchomp(buf);
917                         g_ptr_array_add(files, g_strdup(buf));
918                 }
919                 open_compose_new(mailto, files);
920                 ptr_array_free_strings(files);
921                 g_ptr_array_free(files, TRUE);
922                 g_free(mailto);
923         } else if (!strncmp(buf, "compose", 7)) {
924                 open_compose_new(buf + strlen("compose") + 1, NULL);
925         } else if (!strncmp(buf, "send", 4)) {
926                 send_queue();
927         } else if (!strncmp(buf, "online", 6)) {
928                 main_window_toggle_work_offline(mainwin, FALSE);
929         } else if (!strncmp(buf, "offline", 7)) {
930                 main_window_toggle_work_offline(mainwin, TRUE);
931         } else if (!strncmp(buf, "status-full", 11) ||
932                    !strncmp(buf, "status", 6)) {
933                 gchar *status;
934                 GPtrArray *folders;
935  
936                 folders = get_folder_item_list(sock);
937                 status = folder_get_status
938                         (folders, !strncmp(buf, "status-full", 11));
939                 fd_write_all(sock, status, strlen(status));
940                 fd_write_all(sock, ".\n", 2);
941                 g_free(status);
942                 if (folders) g_ptr_array_free(folders, TRUE);
943         }
944
945         fd_close(sock);
946 }
947
948 static void open_compose_new(const gchar *address, GPtrArray *attach_files)
949 {
950         gchar *addr = NULL;
951
952         if (address) {
953                 Xstrdup_a(addr, address, return);
954                 g_strstrip(addr);
955         }
956
957         compose_new(NULL, addr, attach_files);
958 }
959
960 static void send_queue(void)
961 {
962         GList *list;
963
964         for (list = folder_get_list(); list != NULL; list = list->next) {
965                 Folder *folder = list->data;
966
967                 if (folder->queue) {
968                         gint res = procmsg_send_queue
969                                 (folder->queue, prefs_common.savemsg);
970
971                         if (res < 0)    
972                                 alertpanel_error(_("Some errors occurred while sending queued messages."));
973                         if (res)        
974                                 folder_item_scan(folder->queue);
975                 }
976         }
977 }
978
979 static void quit_signal_handler(int sig)
980 {
981         debug_print("Quitting on signal %d\n", sig);
982
983         g_timeout_add(0, clean_quit, NULL);
984 }
985
986 static void install_basic_sighandlers()
987 {
988         sigset_t    mask;
989         struct sigaction act;
990
991         sigemptyset(&mask);
992
993 #ifdef SIGTERM
994         sigaddset(&mask, SIGTERM);
995 #endif
996 #ifdef SIGINT
997         sigaddset(&mask, SIGINT);
998 #endif
999 #ifdef SIGHUP
1000         sigaddset(&mask, SIGHUP);
1001 #endif
1002
1003         act.sa_handler = quit_signal_handler;
1004         act.sa_mask    = mask;
1005         act.sa_flags   = 0;
1006
1007 #ifdef SIGTERM
1008         sigaction(SIGTERM, &act, 0);
1009 #endif
1010 #ifdef SIGINT
1011         sigaction(SIGINT, &act, 0);
1012 #endif  
1013 #ifdef SIGHUP
1014         sigaction(SIGHUP, &act, 0);
1015 #endif  
1016
1017         sigprocmask(SIG_UNBLOCK, &mask, 0);
1018 }