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