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