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