2006-09-28 [colin] 2.5.2cvs17
[claws.git] / src / main.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2006 Hiroyuki Yamamoto and the Sylpheed-Claws team
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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 <glib/gi18n.h>
28 #include <gtk/gtkmain.h>
29 #include <gtk/gtkrc.h>
30
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <ctype.h>
35 #include <unistd.h>
36 #include <time.h>
37 #include <sys/stat.h>
38 #include <sys/types.h>
39 #ifdef G_OS_UNIX
40 #  include <signal.h>
41 #endif
42 #ifdef HAVE_LIBSM
43 #include <X11/SM/SMlib.h>
44 #include <fcntl.h>
45 #endif
46
47 #include "wizard.h"
48 #ifdef HAVE_STARTUP_NOTIFICATION
49 # define SN_API_NOT_YET_FROZEN
50 # include <libsn/sn-launchee.h>
51 # include <gdk/gdkx.h>
52 #endif
53
54 #include "sylpheed.h"
55 #include "main.h"
56 #include "mainwindow.h"
57 #include "folderview.h"
58 #include "image_viewer.h"
59 #include "summaryview.h"
60 #include "prefs_common.h"
61 #include "prefs_account.h"
62 #include "prefs_actions.h"
63 #include "prefs_ext_prog.h"
64 #include "prefs_fonts.h"
65 #include "prefs_image_viewer.h"
66 #include "prefs_message.h"
67 #include "prefs_receive.h"
68 #include "prefs_msg_colors.h"
69 #include "prefs_quote.h"
70 #include "prefs_spelling.h"
71 #include "prefs_summaries.h"
72 #include "prefs_themes.h"
73 #include "prefs_other.h"
74 #include "prefs_send.h"
75 #include "prefs_wrapping.h"
76 #include "prefs_compose_writing.h"
77 #include "prefs_display_header.h"
78 #include "account.h"
79 #include "procmsg.h"
80 #include "inc.h"
81 #include "import.h"
82 #include "manage_window.h"
83 #include "alertpanel.h"
84 #include "statusbar.h"
85 #include "addressbook.h"
86 #include "compose.h"
87 #include "folder.h"
88 #include "setup.h"
89 #include "utils.h"
90 #include "gtkutils.h"
91 #include "socket.h"
92 #include "log.h"
93 #include "prefs_toolbar.h"
94 #include "plugin.h"
95 #include "mh_gtk.h"
96 #include "imap_gtk.h"
97 #include "news_gtk.h"
98 #include "matcher.h"
99 #ifdef HAVE_LIBETPAN
100 #include "imap-thread.h"
101 #endif
102 #include "stock_pixmap.h"
103
104 #if USE_OPENSSL
105 #  include "ssl.h"
106 #endif
107
108 #include "version.h"
109
110 #include "crash.h"
111
112 gchar *prog_version;
113 gchar *argv0;
114
115 #ifdef HAVE_STARTUP_NOTIFICATION
116 static SnLauncheeContext *sn_context = NULL;
117 static SnDisplay *sn_display = NULL;
118 #endif
119
120 static gint lock_socket = -1;
121 static gint lock_socket_tag = 0;
122
123 typedef enum 
124 {
125         ONLINE_MODE_DONT_CHANGE,
126         ONLINE_MODE_ONLINE,
127         ONLINE_MODE_OFFLINE
128 } OnlineMode;
129
130 static struct RemoteCmd {
131         gboolean receive;
132         gboolean receive_all;
133         gboolean compose;
134         const gchar *compose_mailto;
135         GPtrArray *attach_files;
136         gboolean status;
137         gboolean status_full;
138         GPtrArray *status_folders;
139         GPtrArray *status_full_folders;
140         gboolean send;
141         gboolean crash;
142         int online_mode;
143         gchar   *crash_params;
144         gboolean exit;
145         gboolean subscribe;
146         const gchar *subscribe_uri;
147         const gchar *target;
148 } cmd;
149
150 static void parse_cmd_opt(int argc, char *argv[]);
151
152 static gint prohibit_duplicate_launch   (void);
153 static gchar * get_crashfile_name       (void);
154 static gint lock_socket_remove          (void);
155 static void lock_socket_input_cb        (gpointer          data,
156                                          gint              source,
157                                          GdkInputCondition condition);
158 #ifndef CLAWS                                    
159 static 
160 #endif
161 gchar *get_socket_name          (void);
162
163
164 static void open_compose_new            (const gchar    *address,
165                                          GPtrArray      *attach_files);
166
167 static void send_queue                  (void);
168 static void initial_processing          (FolderItem *item, gpointer data);
169 static void quit_signal_handler         (int sig);
170 static void install_basic_sighandlers   (void);
171 static void exit_sylpheed               (MainWindow *mainwin);
172
173 #define MAKE_DIR_IF_NOT_EXIST(dir) \
174 { \
175         if (!is_dir_exist(dir)) { \
176                 if (is_file_exist(dir)) { \
177                         alertpanel_warning \
178                                 (_("File '%s' already exists.\n" \
179                                    "Can't create folder."), \
180                                  dir); \
181                         return 1; \
182                 } \
183                 if (make_dir(dir) < 0) \
184                         return 1; \
185         } \
186 }
187
188 static MainWindow *static_mainwindow;
189 static gboolean emergency_exit = FALSE;
190
191 #ifdef HAVE_STARTUP_NOTIFICATION
192 static void sn_error_trap_push(SnDisplay *display, Display *xdisplay)
193 {
194         gdk_error_trap_push();
195 }
196
197 static void sn_error_trap_pop(SnDisplay *display, Display *xdisplay)
198 {
199         gdk_error_trap_pop();
200 }
201
202 static void startup_notification_complete(gboolean with_window)
203 {
204         Display *xdisplay;
205         GtkWidget *hack = NULL;
206
207         if (with_window) {
208                 /* this is needed to make the startup notification leave,
209                  * if we have been launched from a menu.
210                  * We have to display a window, so let it be very little */
211                 hack = gtk_window_new(GTK_WINDOW_POPUP);
212                 gtk_widget_set_uposition(hack, 0, 0);
213                 gtk_widget_set_size_request(hack, 1, 1);
214                 gtk_widget_show(hack);
215         }
216
217         xdisplay = GDK_DISPLAY();
218         sn_display = sn_display_new(xdisplay,
219                                 sn_error_trap_push,
220                                 sn_error_trap_pop);
221         sn_context = sn_launchee_context_new_from_environment(sn_display,
222                                                  DefaultScreen(xdisplay));
223
224         if (sn_context != NULL) {
225                 sn_launchee_context_complete(sn_context);
226                 sn_launchee_context_unref(sn_context);
227                 sn_display_unref(sn_display);
228         }
229         if (with_window) {
230                 gtk_widget_destroy(hack);
231         }
232 }
233 #endif /* HAVE_STARTUP_NOTIFICATION */
234
235 void sylpheed_gtk_idle(void) 
236 {
237         while(gtk_events_pending()) {
238                 gtk_main_iteration();
239         }
240         g_usleep(50000);
241 }
242
243 gboolean defer_check_all(void *data)
244 {
245         gboolean autochk = GPOINTER_TO_INT(data);
246
247         inc_all_account_mail(static_mainwindow, autochk, 
248                         prefs_common.newmail_notify_manu);
249
250         return FALSE;
251 }
252
253 gboolean defer_check(void *data)
254 {
255         inc_mail(static_mainwindow, prefs_common.newmail_notify_manu);
256
257         return FALSE;
258 }
259
260 static gboolean defer_jump(void *data)
261 {
262         mainwindow_jump_to(data);
263         return FALSE;
264 }
265
266 static gboolean migrate_old_config(const gchar *old_cfg_dir, const gchar *new_cfg_dir)
267 {
268         gchar *message = g_strdup_printf(_("Configuration for Sylpheed-Claws %s found.\n"
269                          "Do you want to migrate this configuration?"),
270                          !strcmp(old_cfg_dir, OLD_GTK1_RC_DIR)?
271                                 _("1.0.5 or previous"):_("1.9.15 or previous"));
272         gint r = 0;
273         GtkWidget *window = NULL;
274         if (alertpanel(_("Migration of configuration"),
275                        message,
276                        GTK_STOCK_NO, GTK_STOCK_YES, NULL) != G_ALERTALTERNATE) {
277                 return FALSE;
278         }
279         
280         window = label_window_create(_("Copying configuration..."));
281         GTK_EVENTS_FLUSH();
282         r = copy_dir(old_cfg_dir, new_cfg_dir);
283         gtk_widget_destroy(window);
284         if (r != 0) {
285                 alertpanel_error(_("Migration failed!"));
286         }
287         return (r == 0);
288 }
289
290 #ifdef HAVE_LIBSM
291 static void
292 sc_client_set_value (MainWindow *mainwin,
293                   gchar       *name,
294                   char        *type,
295                   int          num_vals,
296                   SmPropValue *vals)
297 {
298         SmProp *proplist[1];
299         SmProp prop;
300
301         prop.name = name;
302         prop.type = type;
303         prop.num_vals = num_vals;
304         prop.vals = vals;
305
306         proplist[0]= &prop;
307         if (mainwin->smc_conn)
308                 SmcSetProperties ((SmcConn) mainwin->smc_conn, 1, proplist);
309 }
310
311 static void sc_die_callback (SmcConn smc_conn, SmPointer client_data)
312 {
313         clean_quit(NULL);
314 }
315
316 static void sc_save_complete_callback(SmcConn smc_conn, SmPointer client_data)
317 {
318 }
319
320 static void sc_shutdown_cancelled_callback (SmcConn smc_conn, SmPointer client_data)
321 {
322         MainWindow *mainwin = (MainWindow *)client_data;
323         if (mainwin->smc_conn)
324                 SmcSaveYourselfDone ((SmcConn) mainwin->smc_conn, TRUE);
325 }
326
327 static void sc_save_yourself_callback (SmcConn   smc_conn,
328                                SmPointer client_data,
329                                int       save_style,
330                                gboolean  shutdown,
331                                int       interact_style,
332                                gboolean  fast) {
333
334         MainWindow *mainwin = (MainWindow *)client_data;
335         if (mainwin->smc_conn)
336                 SmcSaveYourselfDone ((SmcConn) mainwin->smc_conn, TRUE);
337 }
338
339 static IceIOErrorHandler sc_ice_installed_handler;
340
341 static void sc_ice_io_error_handler (IceConn connection)
342 {
343         if (sc_ice_installed_handler)
344                 (*sc_ice_installed_handler) (connection);
345 }
346 static gboolean sc_process_ice_messages (GIOChannel   *source,
347                       GIOCondition  condition,
348                       gpointer      data)
349 {
350         IceConn connection = (IceConn) data;
351         IceProcessMessagesStatus status;
352
353         status = IceProcessMessages (connection, NULL, NULL);
354
355         if (status == IceProcessMessagesIOError) {
356                 IcePointer context = IceGetConnectionContext (connection);
357
358                 if (context && GTK_IS_OBJECT (context)) {
359                 guint disconnect_id = g_signal_lookup ("disconnect", G_OBJECT_TYPE (context));
360
361                 if (disconnect_id > 0)
362                         g_signal_emit (context, disconnect_id, 0);
363                 } else {
364                         IceSetShutdownNegotiation (connection, False);
365                         IceCloseConnection (connection);
366                 }
367         }
368
369         return TRUE;
370 }
371
372 static void new_ice_connection (IceConn connection, IcePointer client_data, Bool opening,
373                     IcePointer *watch_data)
374 {
375         guint input_id;
376
377         if (opening) {
378                 GIOChannel *channel;
379                 /* Make sure we don't pass on these file descriptors to any
380                 exec'ed children */
381                 fcntl(IceConnectionNumber(connection),F_SETFD,
382                 fcntl(IceConnectionNumber(connection),F_GETFD,0) | FD_CLOEXEC);
383
384                 channel = g_io_channel_unix_new (IceConnectionNumber (connection));
385                 input_id = g_io_add_watch (channel,
386                 G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_PRI,
387                 sc_process_ice_messages,
388                 connection);
389                 g_io_channel_unref (channel);
390
391                 *watch_data = (IcePointer) GUINT_TO_POINTER (input_id);
392         } else {
393                 input_id = GPOINTER_TO_UINT ((gpointer) *watch_data);
394                 g_source_remove (input_id);
395         }
396 }
397
398 static void sc_session_manager_connect(MainWindow *mainwin)
399 {
400         static gboolean connected = FALSE;
401         SmcCallbacks      callbacks;
402         gchar            *client_id;
403         IceIOErrorHandler default_handler;
404
405         if (connected)
406                 return;
407         connected = TRUE;
408
409
410         sc_ice_installed_handler = IceSetIOErrorHandler (NULL);
411         default_handler = IceSetIOErrorHandler (sc_ice_io_error_handler);
412
413         if (sc_ice_installed_handler == default_handler)
414                 sc_ice_installed_handler = NULL;
415
416         IceAddConnectionWatch (new_ice_connection, NULL);
417       
418       
419         callbacks.save_yourself.callback      = sc_save_yourself_callback;
420         callbacks.die.callback                = sc_die_callback;
421         callbacks.save_complete.callback      = sc_save_complete_callback;
422         callbacks.shutdown_cancelled.callback = sc_shutdown_cancelled_callback;
423
424         callbacks.save_yourself.client_data =
425                 callbacks.die.client_data =
426                 callbacks.save_complete.client_data =
427                 callbacks.shutdown_cancelled.client_data = (SmPointer) mainwin;
428         if (g_getenv ("SESSION_MANAGER")) {
429                 gchar error_string_ret[256] = "";
430
431                 mainwin->smc_conn = (gpointer)
432                         SmcOpenConnection (NULL, mainwin,
433                                 SmProtoMajor, SmProtoMinor,
434                                 SmcSaveYourselfProcMask | SmcDieProcMask |
435                                 SmcSaveCompleteProcMask |
436                                 SmcShutdownCancelledProcMask,
437                                 &callbacks,
438                                 NULL, &client_id,
439                                 256, error_string_ret);
440
441                 if (error_string_ret[0] || mainwin->smc_conn == NULL)
442                         g_warning ("While connecting to session manager:\n%s.",
443                                 error_string_ret);
444                 else {
445                         SmPropValue *vals;
446                         vals = g_new (SmPropValue, 1);
447                         vals[0].length = strlen(argv0);
448                         vals[0].value = argv0;
449                         sc_client_set_value (mainwin, SmCloneCommand, SmLISTofARRAY8, 1, vals);
450                         sc_client_set_value (mainwin, SmRestartCommand, SmLISTofARRAY8, 1, vals);
451                         sc_client_set_value (mainwin, SmProgram, SmARRAY8, 1, vals);
452
453                         vals[0].length = strlen(g_get_user_name()?g_get_user_name():"");
454                         vals[0].value = g_strdup(g_get_user_name()?g_get_user_name():"");
455                         sc_client_set_value (mainwin, SmUserID, SmARRAY8, 1, vals);
456                 }
457         }
458 }
459 #endif
460
461 int main(int argc, char *argv[])
462 {
463         gchar *userrc;
464         MainWindow *mainwin;
465         FolderView *folderview;
466         GdkPixbuf *icon;
467         gboolean crash_file_present = FALSE;
468         gint num_folder_class = 0;
469         if (!sylpheed_init(&argc, &argv)) {
470                 return 0;
471         }
472
473         prog_version = PROG_VERSION;
474         argv0 = g_strdup(argv[0]);
475
476         parse_cmd_opt(argc, argv);
477
478 #ifdef CRASH_DIALOG
479         if (cmd.crash) {
480                 gtk_set_locale();
481                 gtk_init(&argc, &argv);
482                 crash_main(cmd.crash_params);
483                 return 0;
484         }
485         crash_install_handlers();
486 #endif
487         install_basic_sighandlers();
488         sock_init();
489
490         /* check and create unix domain socket for remote operation */
491 #ifdef G_OS_UNIX
492         lock_socket = prohibit_duplicate_launch();
493         if (lock_socket < 0) {
494 #ifdef HAVE_STARTUP_NOTIFICATION
495                 if(gtk_init_check(&argc, &argv))
496                         startup_notification_complete(TRUE);
497 #endif
498                 return 0;
499         }
500
501         if (cmd.status || cmd.status_full) {
502                 puts("0 Sylpheed-Claws not running.");
503                 lock_socket_remove();
504                 return 0;
505         }
506         
507         if (cmd.exit)
508                 return 0;
509 #endif
510         if (!g_thread_supported())
511                 g_thread_init(NULL);
512
513         gtk_set_locale();
514         gtk_init(&argc, &argv);
515
516         gdk_rgb_init();
517         gtk_widget_set_default_colormap(gdk_rgb_get_colormap());
518         gtk_widget_set_default_visual(gdk_rgb_get_visual());
519
520         if (!g_thread_supported()) {
521                 g_error(_("g_thread is not supported by glib.\n"));
522         }
523
524         /* check that we're not on a too recent/old gtk+ */
525 #if GTK_CHECK_VERSION(2, 9, 0)
526         if (gtk_check_version(2, 9, 0) != NULL) {
527                 alertpanel_error(_("Sylpheed-Claws has been compiled with "
528                                    "a more recent GTK+ library than is "
529                                    "currently available. This will cause "
530                                    "crashes. You need to upgrade GTK+ or "
531                                    "recompile Sylpheed-Claws."));
532                 exit(1);
533         }
534 #else
535         if (gtk_check_version(2, 9, 0) == NULL) {
536                 alertpanel_error(_("Sylpheed-Claws has been compiled with "
537                                    "an older GTK+ library than is "
538                                    "currently available. This will cause "
539                                    "crashes. You need to recompile "
540                                    "Sylpheed-Claws."));
541                 exit(1);
542         }
543 #endif  
544         /* parse gtkrc files */
545         userrc = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".gtkrc-2.0",
546                              NULL);
547         gtk_rc_parse(userrc);
548         g_free(userrc);
549         userrc = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".gtk",
550                              G_DIR_SEPARATOR_S, "gtkrc-2.0", NULL);
551         gtk_rc_parse(userrc);
552         g_free(userrc);
553
554         CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
555         if (!is_dir_exist(RC_DIR)) {
556                 gboolean r = FALSE;
557                 if (is_dir_exist(OLD_GTK2_RC_DIR))
558                         r = migrate_old_config(OLD_GTK2_RC_DIR, RC_DIR);
559                 else if (is_dir_exist(OLD_GTK1_RC_DIR))
560                         r = migrate_old_config(OLD_GTK1_RC_DIR, RC_DIR);
561                 if (r == FALSE && !is_dir_exist(RC_DIR) && make_dir(RC_DIR) < 0)
562                         exit(1);
563         }
564
565         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, "gtkrc-2.0", NULL);
566         gtk_rc_parse(userrc);
567         g_free(userrc);
568
569         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
570         gtk_accel_map_load (userrc);
571         g_free(userrc);
572
573         gtk_settings_set_long_property(gtk_settings_get_default(), 
574                                        "gtk-can-change-accels",
575                                        (glong)TRUE, "XProperty");
576
577         CHDIR_RETURN_VAL_IF_FAIL(get_rc_dir(), 1);
578
579         MAKE_DIR_IF_NOT_EXIST(get_mail_base_dir());
580         MAKE_DIR_IF_NOT_EXIST(get_imap_cache_dir());
581         MAKE_DIR_IF_NOT_EXIST(get_news_cache_dir());
582         MAKE_DIR_IF_NOT_EXIST(get_mime_tmp_dir());
583         MAKE_DIR_IF_NOT_EXIST(get_tmp_dir());
584         MAKE_DIR_IF_NOT_EXIST(UIDL_DIR);
585
586         crash_file_present = is_file_exist(get_crashfile_name());
587         /* remove temporary files */
588         remove_all_files(get_tmp_dir());
589         remove_all_files(get_mime_tmp_dir());
590
591         if (is_file_exist("sylpheed.log")) {
592                 if (rename_force("sylpheed.log", "sylpheed.log.bak") < 0)
593                         FILE_OP_ERROR("sylpheed.log", "rename");
594         }
595         set_log_file("sylpheed.log");
596
597         CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
598
599         folder_system_init();
600         prefs_common_read_config();
601
602         prefs_themes_init();
603         prefs_fonts_init();
604         prefs_ext_prog_init();
605         prefs_wrapping_init();
606         prefs_compose_writing_init();
607         prefs_msg_colors_init();
608         image_viewer_init();
609         prefs_image_viewer_init();
610         prefs_quote_init();
611         prefs_summaries_init();
612         prefs_message_init();
613         prefs_other_init();
614         prefs_receive_init();
615         prefs_send_init();
616 #ifdef USE_ASPELL
617         gtkaspell_checkers_init();
618         prefs_spelling_init();
619 #endif
620         
621         sock_set_io_timeout(prefs_common.io_timeout_secs);
622 #ifdef HAVE_LIBETPAN
623         imap_main_set_timeout(prefs_common.io_timeout_secs);
624 #endif
625         prefs_actions_read_config();
626         prefs_display_header_read_config();
627         /* prefs_filtering_read_config(); */
628         addressbook_read_file();
629         renderer_read_config();
630
631         gtkut_widget_init();
632         stock_pixbuf_gdk(NULL, STOCK_PIXMAP_SYLPHEED_CLAWS_ICON, &icon);
633         gtk_window_set_default_icon(icon);
634
635         folderview_initialize();
636
637         mh_gtk_init();
638         imap_gtk_init();
639         news_gtk_init();
640                 
641         mainwin = main_window_create
642                 (prefs_common.sep_folder | prefs_common.sep_msg << 1);
643         manage_window_focus_in(mainwin->window, NULL, NULL);
644         folderview = mainwin->folderview;
645
646         gtk_clist_freeze(GTK_CLIST(mainwin->folderview->ctree));
647         folder_item_update_freeze();
648
649         /* register the callback of unix domain socket input */
650 #ifdef G_OS_UNIX
651         lock_socket_tag = gdk_input_add(lock_socket,
652                                         GDK_INPUT_READ | GDK_INPUT_EXCEPTION,
653                                         lock_socket_input_cb,
654                                         mainwin);
655 #endif
656
657         prefs_account_init();
658         account_read_config_all();
659
660         if (folder_read_list() < 0) {
661                 if (!run_wizard(mainwin, TRUE))
662                         exit(1);
663                 main_window_reflect_prefs_all_now();
664                 folder_write_list();
665         }
666
667         if (!account_get_list()) {
668                 if (!run_wizard(mainwin, FALSE))
669                         exit(1);
670                 account_read_config_all();
671                 if(!account_get_list())
672                         exit_sylpheed(mainwin);
673         }
674
675         
676         toolbar_main_set_sensitive(mainwin);
677         main_window_set_menu_sensitive(mainwin);
678
679         main_window_popup(mainwin);
680
681 #ifdef HAVE_LIBETPAN
682         imap_main_init(prefs_common.skip_ssl_cert_check);
683 #endif  
684         account_set_missing_folder();
685         folder_set_missing_folders();
686         folderview_set(folderview);
687
688         prefs_matcher_read_config();
689
690         /* make one all-folder processing before using sylpheed */
691         main_window_cursor_wait(mainwin);
692         folder_func_to_all_folders(initial_processing, (gpointer *)mainwin);
693
694         /* if Sylpheed crashed, rebuild caches */
695         if (!cmd.crash && crash_file_present) {
696                 GTK_EVENTS_FLUSH();
697                 debug_print("Sylpheed-Claws crashed, checking for new messages in local folders\n");
698                 folder_item_update_thaw();
699                 folderview_check_new(NULL);
700                 folder_clean_cache_memory_force();
701                 folder_item_update_freeze();
702         }
703         /* make the crash-indicator file */
704         str_write_to_file("foo", get_crashfile_name());
705
706         inc_autocheck_timer_init(mainwin);
707
708         /* ignore SIGPIPE signal for preventing sudden death of program */
709 #ifdef G_OS_UNIX
710         signal(SIGPIPE, SIG_IGN);
711 #endif
712         if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
713                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
714         }
715         if (cmd.online_mode == ONLINE_MODE_ONLINE) {
716                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
717         }
718
719         if (cmd.status_folders) {
720                 g_ptr_array_free(cmd.status_folders, TRUE);
721                 cmd.status_folders = NULL;
722         }
723         if (cmd.status_full_folders) {
724                 g_ptr_array_free(cmd.status_full_folders, TRUE);
725                 cmd.status_full_folders = NULL;
726         }
727
728         sylpheed_register_idle_function(sylpheed_gtk_idle);
729
730         prefs_toolbar_init();
731
732         num_folder_class = g_list_length(folder_get_list());
733
734         plugin_load_all("GTK2");
735
736         if (g_list_length(folder_get_list()) != num_folder_class) {
737                 debug_print("new folders loaded, reloading processing rules\n");
738                 prefs_matcher_read_config();
739         }
740         
741         if (plugin_get_unloaded_list() != NULL) {
742                 main_window_cursor_normal(mainwin);
743                 alertpanel_warning(_("Some plugin(s) failed to load. "
744                                      "Check the Plugins configuration "
745                                      "for more information."));
746                 main_window_cursor_wait(mainwin);
747         }
748
749         plugin_load_standard_plugins ();
750        
751         if (!folder_have_mailbox()) {
752                 main_window_cursor_normal(mainwin);
753                 alertpanel_error(_("Sylpheed-Claws has detected a configured "
754                                    "mailbox, but could not load it. It is "
755                                    "probably provided by an out-of-date "
756                                    "external plugin. Please reinstall the "
757                                    "plugin and try again."));
758                 exit(1);
759         }
760         
761         static_mainwindow = mainwin;
762
763 #ifdef HAVE_STARTUP_NOTIFICATION
764         startup_notification_complete(FALSE);
765 #endif
766 #ifdef HAVE_LIBSM
767         sc_session_manager_connect(mainwin);
768 #endif
769         folder_item_update_thaw();
770         gtk_clist_thaw(GTK_CLIST(mainwin->folderview->ctree));
771         main_window_cursor_normal(mainwin);
772
773         if (cmd.receive_all) {
774                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(FALSE));
775         } else if (prefs_common.chk_on_startup) {
776                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(TRUE));
777         } else if (cmd.receive) {
778                 g_timeout_add(1000, defer_check, NULL);
779         } else {
780                 gtk_widget_grab_focus(folderview->ctree);
781         }
782
783         if (cmd.compose) {
784                 open_compose_new(cmd.compose_mailto, cmd.attach_files);
785         }
786         if (cmd.attach_files) {
787                 ptr_array_free_strings(cmd.attach_files);
788                 g_ptr_array_free(cmd.attach_files, TRUE);
789                 cmd.attach_files = NULL;
790         }
791         if (cmd.subscribe) {
792                 folder_subscribe(cmd.subscribe_uri);
793         }
794
795         if (cmd.send) {
796                 send_queue();
797         }
798         
799         if (cmd.target) {
800                 g_timeout_add(500, defer_jump, (gpointer)cmd.target);
801         }
802
803         gtk_main();
804
805         exit_sylpheed(mainwin);
806
807         return 0;
808 }
809
810 static void save_all_caches(FolderItem *item, gpointer data)
811 {
812         if (!item->cache) {
813                 return;
814         }
815
816         if (item->opened)
817                 folder_item_close(item);
818         
819         folder_item_free_cache(item, TRUE);
820 }
821
822 static gboolean sc_exiting = FALSE;
823
824 static void exit_sylpheed(MainWindow *mainwin)
825 {
826         gchar *filename;
827
828         sc_exiting = TRUE;
829
830         debug_print("shutting down\n");
831         inc_autocheck_timer_remove();
832
833         if (prefs_common.clean_on_exit && !emergency_exit) {
834                 main_window_empty_trash(mainwin, prefs_common.ask_on_clean);
835         }
836
837         /* save prefs for opened folder */
838         if(mainwin->folderview->opened) {
839                 FolderItem *item;
840
841                 item = gtk_ctree_node_get_row_data(GTK_CTREE(mainwin->folderview->ctree), mainwin->folderview->opened);
842                 summary_save_prefs_to_folderitem(mainwin->folderview->summaryview, item);
843         }
844
845         /* save all state before exiting */
846         folder_write_list();
847         folder_func_to_all_folders(save_all_caches, NULL);
848
849         main_window_get_size(mainwin);
850         main_window_get_position(mainwin);
851         prefs_common_write_config();
852         account_write_config_all();
853         addressbook_export_to_file();
854
855         filename = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
856         gtk_accel_map_save(filename);
857         g_free(filename);
858
859         /* delete temporary files */
860         remove_all_files(get_tmp_dir());
861         remove_all_files(get_mime_tmp_dir());
862
863         close_log_file();
864
865 #ifdef HAVE_LIBETPAN
866         imap_main_done();
867 #endif
868         /* delete crashfile */
869         if (!cmd.crash)
870                 g_unlink(get_crashfile_name());
871
872         lock_socket_remove();
873
874 #ifdef HAVE_LIBSM
875         if (mainwin->smc_conn)
876                 SmcCloseConnection ((SmcConn)mainwin->smc_conn, 0, NULL);
877         mainwin->smc_conn = NULL;
878 #endif
879
880         main_window_destroy_all();
881         
882         plugin_unload_all("GTK2");
883
884         prefs_toolbar_done();
885
886         addressbook_destroy();
887
888         prefs_themes_done();
889         prefs_fonts_done();
890         prefs_ext_prog_done();
891         prefs_wrapping_done();
892         prefs_compose_writing_done();
893         prefs_msg_colors_done();
894         prefs_image_viewer_done();
895         image_viewer_done();
896         prefs_quote_done();
897         prefs_summaries_done();
898         prefs_message_done();
899         prefs_other_done();
900         prefs_receive_done();
901         prefs_send_done();
902 #ifdef USE_ASPELL       
903         prefs_spelling_done();
904         gtkaspell_checkers_quit();
905 #endif
906         sylpheed_done();
907 }
908
909 static void parse_cmd_opt(int argc, char *argv[])
910 {
911         gint i;
912
913         for (i = 1; i < argc; i++) {
914                 if (!strncmp(argv[i], "--receive-all", 13)) {
915                         cmd.receive_all = TRUE;
916                 } else if (!strncmp(argv[i], "--receive", 9)) {
917                         cmd.receive = TRUE;
918                 } else if (!strncmp(argv[i], "--compose", 9)) {
919                         const gchar *p = argv[i + 1];
920
921                         cmd.compose = TRUE;
922                         cmd.compose_mailto = NULL;
923                         if (p && *p != '\0' && *p != '-') {
924                                 if (!strncmp(p, "mailto:", 7)) {
925                                         cmd.compose_mailto = p + 7;
926                                 } else {
927                                         cmd.compose_mailto = p;
928                                 }
929                                 i++;
930                         }
931                 } else if (!strncmp(argv[i], "--subscribe", 11)) {
932                         const gchar *p = argv[i + 1];
933                         if (p && *p != '\0' && *p != '-') {
934                                 cmd.subscribe = TRUE;
935                                 cmd.subscribe_uri = p;
936                         }
937                 } else if (!strncmp(argv[i], "--attach", 8)) {
938                         const gchar *p = argv[i + 1];
939                         gchar *file;
940
941                         while (p && *p != '\0' && *p != '-') {
942                                 if (!cmd.attach_files) {
943                                         cmd.attach_files = g_ptr_array_new();
944                                 }
945                                 if (*p != G_DIR_SEPARATOR) {
946                                         file = g_strconcat(sylpheed_get_startup_dir(),
947                                                            G_DIR_SEPARATOR_S,
948                                                            p, NULL);
949                                 } else {
950                                         file = g_strdup(p);
951                                 }
952                                 g_ptr_array_add(cmd.attach_files, file);
953                                 i++;
954                                 p = argv[i + 1];
955                         }
956                 } else if (!strncmp(argv[i], "--send", 6)) {
957                         cmd.send = TRUE;
958                 } else if (!strncmp(argv[i], "--version", 9)) {
959                         puts("Sylpheed-Claws version " VERSION);
960                         exit(0);
961                 } else if (!strncmp(argv[i], "--status-full", 13)) {
962                         const gchar *p = argv[i + 1];
963  
964                         cmd.status_full = TRUE;
965                         while (p && *p != '\0' && *p != '-') {
966                                 if (!cmd.status_full_folders) {
967                                         cmd.status_full_folders =
968                                                 g_ptr_array_new();
969                                 }
970                                 g_ptr_array_add(cmd.status_full_folders,
971                                                 g_strdup(p));
972                                 i++;
973                                 p = argv[i + 1];
974                         }
975                 } else if (!strncmp(argv[i], "--status", 8)) {
976                         const gchar *p = argv[i + 1];
977  
978                         cmd.status = TRUE;
979                         while (p && *p != '\0' && *p != '-') {
980                                 if (!cmd.status_folders)
981                                         cmd.status_folders = g_ptr_array_new();
982                                 g_ptr_array_add(cmd.status_folders,
983                                                 g_strdup(p));
984                                 i++;
985                                 p = argv[i + 1];
986                         }
987                 } else if (!strncmp(argv[i], "--online", 8)) {
988                         cmd.online_mode = ONLINE_MODE_ONLINE;
989                 } else if (!strncmp(argv[i], "--offline", 9)) {
990                         cmd.online_mode = ONLINE_MODE_OFFLINE;
991                 } else if (!strncmp(argv[i], "--help", 6)) {
992                         gchar *base = g_path_get_basename(argv[0]);
993                         g_print(_("Usage: %s [OPTION]...\n"), base);
994
995                         g_print("%s\n", _("  --compose [address]    open composition window"));
996                         g_print("%s\n", _("  --subscribe [uri]      subscribe to the given URI if possible"));
997                         g_print("%s\n", _("  --attach file1 [file2]...\n"
998                                   "                         open composition window with specified files\n"
999                                   "                         attached"));
1000                         g_print("%s\n", _("  --receive              receive new messages"));
1001                         g_print("%s\n", _("  --receive-all          receive new messages of all accounts"));
1002                         g_print("%s\n", _("  --send                 send all queued messages"));
1003                         g_print("%s\n", _("  --status [folder]...   show the total number of messages"));
1004                         g_print("%s\n", _("  --status-full [folder]...\n"
1005                                "                         show the status of each folder"));
1006                         g_print("%s\n", _("  --select folder[/msg]  jumps to the specified folder/message\n" 
1007                                           "                         folder is a folder id like '#mh/Mailbox/inbox'"));
1008                         g_print("%s\n", _("  --online               switch to online mode"));
1009                         g_print("%s\n", _("  --offline              switch to offline mode"));
1010                         g_print("%s\n", _("  --exit                 exit Sylpheed-Claws"));
1011                         g_print("%s\n", _("  --debug                debug mode"));
1012                         g_print("%s\n", _("  --help                 display this help and exit"));
1013                         g_print("%s\n", _("  --version              output version information and exit"));
1014                         g_print("%s\n", _("  --config-dir           output configuration directory"));
1015
1016                         g_free(base);
1017                         exit(1);
1018                 } else if (!strncmp(argv[i], "--crash", 7)) {
1019                         cmd.crash = TRUE;
1020                         cmd.crash_params = g_strdup(argv[i + 1]);
1021                         i++;
1022                 } else if (!strncmp(argv[i], "--config-dir", sizeof "--config-dir" - 1)) {
1023                         puts(RC_DIR);
1024                         exit(0);
1025                 } else if (!strncmp(argv[i], "--exit", 6)) {
1026                         cmd.exit = TRUE;
1027                 } else if (!strncmp(argv[i], "--select", 8) && i+1 < argc) {
1028                         cmd.target = argv[i+1];
1029                 } else if (i == 1 && argc == 2) {
1030                         /* only one parameter. Do something intelligent about it */
1031                         if (strstr(argv[i], "@") && !strstr(argv[i], "://")) {
1032                                 const gchar *p = argv[i];
1033
1034                                 cmd.compose = TRUE;
1035                                 cmd.compose_mailto = NULL;
1036                                 if (p && *p != '\0' && *p != '-') {
1037                                         if (!strncmp(p, "mailto:", 7)) {
1038                                                 cmd.compose_mailto = p + 7;
1039                                         } else {
1040                                                 cmd.compose_mailto = p;
1041                                         }
1042                                 }
1043                         } else if (strstr(argv[i], "://")) {
1044                                 const gchar *p = argv[i];
1045                                 if (p && *p != '\0' && *p != '-') {
1046                                         cmd.subscribe = TRUE;
1047                                         cmd.subscribe_uri = p;
1048                                 }
1049                         }
1050                 }
1051                 
1052         }
1053
1054         if (cmd.attach_files && cmd.compose == FALSE) {
1055                 cmd.compose = TRUE;
1056                 cmd.compose_mailto = NULL;
1057         }
1058 }
1059
1060 static gint get_queued_message_num(void)
1061 {
1062         FolderItem *queue;
1063
1064         queue = folder_get_default_queue();
1065         if (!queue) {
1066                 return -1;
1067         }
1068
1069         folder_item_scan(queue);
1070         return queue->total_msgs;
1071 }
1072
1073 static void initial_processing(FolderItem *item, gpointer data)
1074 {
1075         MainWindow *mainwin = (MainWindow *)data;
1076         gchar *buf;
1077
1078         g_return_if_fail(item);
1079         buf = g_strdup_printf(_("Processing (%s)..."), 
1080                               item->path 
1081                               ? item->path 
1082                               : _("top level folder"));
1083         debug_print("%s\n", buf);
1084         g_free(buf);
1085
1086         
1087         if (item->prefs->enable_processing) {
1088                 folder_item_apply_processing(item);
1089         }
1090
1091         debug_print("done.\n");
1092         STATUSBAR_POP(mainwin);
1093 }
1094
1095 static void draft_all_messages(void)
1096 {
1097         GList *compose_list = NULL;
1098         
1099         while ((compose_list = compose_get_compose_list()) != NULL) {
1100                 Compose *c = (Compose*)compose_list->data;
1101                 compose_draft(c);
1102         }       
1103 }
1104 gboolean clean_quit(gpointer data)
1105 {
1106         static gboolean firstrun = TRUE;
1107
1108         if (!firstrun) {
1109                 return FALSE;
1110         }
1111         firstrun = FALSE;
1112
1113         /*!< Good idea to have the main window stored in a 
1114          *   static variable so we can check that variable
1115          *   to see if we're really allowed to do things
1116          *   that actually the spawner is supposed to 
1117          *   do (like: sending mail, composing messages).
1118          *   Because, really, if we're the spawnee, and
1119          *   we touch GTK stuff, we're hosed. See the 
1120          *   next fixme. */
1121
1122         /* FIXME: Use something else to signal that we're
1123          * in the original spawner, and not in a spawned
1124          * child. */
1125         if (!static_mainwindow) {
1126                 return FALSE;
1127         }
1128                 
1129         draft_all_messages();
1130         emergency_exit = TRUE;
1131         exit_sylpheed(static_mainwindow);
1132         exit(0);
1133
1134         return FALSE;
1135 }
1136
1137 void app_will_exit(GtkWidget *widget, gpointer data)
1138 {
1139         MainWindow *mainwin = data;
1140         
1141         if (sc_exiting == TRUE) {
1142                 debug_print("exit pending\n");
1143                 return;
1144         }
1145         sc_exiting = TRUE;
1146         debug_print("exiting\n");
1147         if (compose_get_compose_list()) {
1148                 gint val = alertpanel(_("Really quit?"),
1149                                _("Composing message exists."),
1150                                _("_Save to Draft"), _("_Discard them"), _("Do_n't quit"));
1151                 switch (val) {
1152                         case G_ALERTOTHER:
1153                                 sc_exiting = FALSE;
1154                                 return;
1155                         case G_ALERTALTERNATE:
1156                                 break;
1157                         default:
1158                                 draft_all_messages();
1159                 }
1160
1161                 manage_window_focus_in(mainwin->window, NULL, NULL);
1162         }
1163
1164         if (prefs_common.warn_queued_on_exit && get_queued_message_num() > 0) {
1165                 if (alertpanel(_("Queued messages"),
1166                                _("Some unsent messages are queued. Exit now?"),
1167                                GTK_STOCK_CANCEL, GTK_STOCK_OK, NULL)
1168                     != G_ALERTALTERNATE) {
1169                         sc_exiting = FALSE;
1170                         return;
1171                 }
1172                 manage_window_focus_in(mainwin->window, NULL, NULL);
1173         }
1174
1175         sock_cleanup();
1176         if (folderview_get_selected_item(mainwin->folderview))
1177                 folder_item_close(folderview_get_selected_item(mainwin->folderview));
1178         gtk_main_quit();
1179 }
1180
1181 gboolean sylpheed_is_exiting(void)
1182 {
1183         return sc_exiting;
1184 }
1185
1186 /*
1187  * CLAWS: want this public so crash dialog can delete the
1188  * lock file too
1189  */
1190 #ifndef CLAWS
1191 static
1192 #endif
1193 gchar *get_socket_name(void)
1194 {
1195         static gchar *filename = NULL;
1196
1197         if (filename == NULL) {
1198                 filename = g_strdup_printf("%s%csylpheed-claws-%d",
1199                                            g_get_tmp_dir(), G_DIR_SEPARATOR,
1200 #if HAVE_GETUID
1201                                            getuid());
1202 #else
1203                                            0);                                          
1204 #endif
1205         }
1206
1207         return filename;
1208 }
1209
1210 static gchar *get_crashfile_name(void)
1211 {
1212         static gchar *filename = NULL;
1213
1214         if (filename == NULL) {
1215                 filename = g_strdup_printf("%s%csylpheed-crashed",
1216                                            get_tmp_dir(), G_DIR_SEPARATOR);
1217         }
1218
1219         return filename;
1220 }
1221
1222 static gint prohibit_duplicate_launch(void)
1223 {
1224         gint uxsock;
1225         gchar *path;
1226
1227         path = get_socket_name();
1228         uxsock = fd_connect_unix(path);
1229         if (uxsock < 0) {
1230                 g_unlink(path);
1231                 return fd_open_unix(path);
1232         }
1233
1234         /* remote command mode */
1235
1236         debug_print("another Sylpheed-Claws instance is already running.\n");
1237
1238         if (cmd.receive_all) {
1239                 fd_write_all(uxsock, "receive_all\n", 12);
1240         } else if (cmd.receive) {
1241                 fd_write_all(uxsock, "receive\n", 8);
1242         } else if (cmd.compose && cmd.attach_files) {
1243                 gchar *str, *compose_str;
1244                 gint i;
1245
1246                 if (cmd.compose_mailto) {
1247                         compose_str = g_strdup_printf("compose_attach %s\n",
1248                                                       cmd.compose_mailto);
1249                 } else {
1250                         compose_str = g_strdup("compose_attach\n");
1251                 }
1252
1253                 fd_write_all(uxsock, compose_str, strlen(compose_str));
1254                 g_free(compose_str);
1255
1256                 for (i = 0; i < cmd.attach_files->len; i++) {
1257                         str = g_ptr_array_index(cmd.attach_files, i);
1258                         fd_write_all(uxsock, str, strlen(str));
1259                         fd_write_all(uxsock, "\n", 1);
1260                 }
1261
1262                 fd_write_all(uxsock, ".\n", 2);
1263         } else if (cmd.compose) {
1264                 gchar *compose_str;
1265
1266                 if (cmd.compose_mailto) {
1267                         compose_str = g_strdup_printf
1268                                 ("compose %s\n", cmd.compose_mailto);
1269                 } else {
1270                         compose_str = g_strdup("compose\n");
1271                 }
1272
1273                 fd_write_all(uxsock, compose_str, strlen(compose_str));
1274                 g_free(compose_str);
1275         } else if (cmd.subscribe) {
1276                 gchar *str = g_strdup_printf("subscribe %s\n", cmd.subscribe_uri);
1277                 fd_write_all(uxsock, str, strlen(str));
1278                 g_free(str);
1279         } else if (cmd.send) {
1280                 fd_write_all(uxsock, "send\n", 5);
1281         } else if (cmd.online_mode == ONLINE_MODE_ONLINE) {
1282                 fd_write(uxsock, "online\n", 6);
1283         } else if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
1284                 fd_write(uxsock, "offline\n", 7);
1285         } else if (cmd.status || cmd.status_full) {
1286                 gchar buf[BUFFSIZE];
1287                 gint i;
1288                 const gchar *command;
1289                 GPtrArray *folders;
1290                 gchar *folder;
1291  
1292                 command = cmd.status_full ? "status-full\n" : "status\n";
1293                 folders = cmd.status_full ? cmd.status_full_folders :
1294                         cmd.status_folders;
1295  
1296                 fd_write_all(uxsock, command, strlen(command));
1297                 for (i = 0; folders && i < folders->len; ++i) {
1298                         folder = g_ptr_array_index(folders, i);
1299                         fd_write_all(uxsock, folder, strlen(folder));
1300                         fd_write_all(uxsock, "\n", 1);
1301                 }
1302                 fd_write_all(uxsock, ".\n", 2);
1303                 for (;;) {
1304                         fd_gets(uxsock, buf, sizeof(buf));
1305                         if (!strncmp(buf, ".\n", 2)) break;
1306                         fputs(buf, stdout);
1307                 }
1308         } else if (cmd.exit) {
1309                 fd_write_all(uxsock, "exit\n", 5);
1310         } else if (cmd.target) {
1311                 gchar *str = g_strdup_printf("select %s\n", cmd.target);
1312                 fd_write_all(uxsock, str, strlen(str));
1313                 g_free(str);
1314         } else
1315                 fd_write_all(uxsock, "popup\n", 6);
1316
1317         fd_close(uxsock);
1318         return -1;
1319 }
1320
1321 static gint lock_socket_remove(void)
1322 {
1323 #ifdef G_OS_UNIX
1324         gchar *filename;
1325
1326         if (lock_socket < 0) {
1327                 return -1;
1328         }
1329
1330         if (lock_socket_tag > 0) {
1331                 gdk_input_remove(lock_socket_tag);
1332         }
1333         fd_close(lock_socket);
1334         filename = get_socket_name();
1335         g_unlink(filename);
1336 #endif
1337
1338         return 0;
1339 }
1340
1341 static GPtrArray *get_folder_item_list(gint sock)
1342 {
1343         gchar buf[BUFFSIZE];
1344         FolderItem *item;
1345         GPtrArray *folders = NULL;
1346
1347         for (;;) {
1348                 fd_gets(sock, buf, sizeof(buf));
1349                 if (!strncmp(buf, ".\n", 2)) {
1350                         break;
1351                 }
1352                 strretchomp(buf);
1353                 if (!folders) {
1354                         folders = g_ptr_array_new();
1355                 }
1356                 item = folder_find_item_from_identifier(buf);
1357                 if (item) {
1358                         g_ptr_array_add(folders, item);
1359                 } else {
1360                         g_warning("no such folder: %s\n", buf);
1361                 }
1362         }
1363
1364         return folders;
1365 }
1366
1367 static void lock_socket_input_cb(gpointer data,
1368                                  gint source,
1369                                  GdkInputCondition condition)
1370 {
1371         MainWindow *mainwin = (MainWindow *)data;
1372         gint sock;
1373         gchar buf[BUFFSIZE];
1374
1375         sock = fd_accept(source);
1376         fd_gets(sock, buf, sizeof(buf));
1377
1378         if (!strncmp(buf, "popup", 5)) {
1379                 main_window_popup(mainwin);
1380         } else if (!strncmp(buf, "receive_all", 11)) {
1381                 inc_all_account_mail(mainwin, FALSE,
1382                                      prefs_common.newmail_notify_manu);
1383         } else if (!strncmp(buf, "receive", 7)) {
1384                 inc_mail(mainwin, prefs_common.newmail_notify_manu);
1385         } else if (!strncmp(buf, "compose_attach", 14)) {
1386                 GPtrArray *files;
1387                 gchar *mailto;
1388
1389                 mailto = g_strdup(buf + strlen("compose_attach") + 1);
1390                 files = g_ptr_array_new();
1391                 while (fd_gets(sock, buf, sizeof(buf)) > 0) {
1392                         if (buf[0] == '.' && buf[1] == '\n') {
1393                                 break;
1394                         }
1395                         strretchomp(buf);
1396                         g_ptr_array_add(files, g_strdup(buf));
1397                 }
1398                 open_compose_new(mailto, files);
1399                 ptr_array_free_strings(files);
1400                 g_ptr_array_free(files, TRUE);
1401                 g_free(mailto);
1402         } else if (!strncmp(buf, "compose", 7)) {
1403                 open_compose_new(buf + strlen("compose") + 1, NULL);
1404         } else if (!strncmp(buf, "subscribe", 9)) {
1405                 main_window_popup(mainwin);
1406                 folder_subscribe(buf + strlen("subscribe") + 1);
1407         } else if (!strncmp(buf, "send", 4)) {
1408                 send_queue();
1409         } else if (!strncmp(buf, "online", 6)) {
1410                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
1411         } else if (!strncmp(buf, "offline", 7)) {
1412                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
1413         } else if (!strncmp(buf, "status-full", 11) ||
1414                    !strncmp(buf, "status", 6)) {
1415                 gchar *status;
1416                 GPtrArray *folders;
1417  
1418                 folders = get_folder_item_list(sock);
1419                 status = folder_get_status
1420                         (folders, !strncmp(buf, "status-full", 11));
1421                 fd_write_all(sock, status, strlen(status));
1422                 fd_write_all(sock, ".\n", 2);
1423                 g_free(status);
1424                 if (folders) g_ptr_array_free(folders, TRUE);
1425         } else if (!strncmp(buf, "select ", 7)) {
1426                 const gchar *target = buf+7;
1427                 mainwindow_jump_to(target);
1428         } else if (!strncmp(buf, "exit", 4)) {
1429                 app_will_exit(NULL, mainwin);
1430         }
1431
1432         fd_close(sock);
1433 }
1434
1435 static void open_compose_new(const gchar *address, GPtrArray *attach_files)
1436 {
1437         gchar *addr = NULL;
1438
1439         if (address) {
1440                 Xstrdup_a(addr, address, return);
1441                 g_strstrip(addr);
1442         }
1443
1444         compose_new(NULL, addr, attach_files);
1445 }
1446
1447 static void send_queue(void)
1448 {
1449         GList *list;
1450         gchar *errstr = NULL;
1451         for (list = folder_get_list(); list != NULL; list = list->next) {
1452                 Folder *folder = list->data;
1453
1454                 if (folder->queue) {
1455                         gint res = procmsg_send_queue
1456                                 (folder->queue, prefs_common.savemsg,
1457                                 &errstr);
1458
1459                         if (res) {
1460                                 folder_item_scan(folder->queue);
1461                         }
1462                 }
1463         }
1464         if (errstr) {
1465                 gchar *tmp = g_strdup_printf(_("Some errors occurred "
1466                                 "while sending queued messages:\n%s"), errstr);
1467                 g_free(errstr);
1468                 alertpanel_error_log(tmp);
1469                 g_free(tmp);
1470         } else {
1471                 alertpanel_error_log("Some errors occurred "
1472                                 "while sending queued messages.");
1473         }
1474 }
1475
1476 static void quit_signal_handler(int sig)
1477 {
1478         debug_print("Quitting on signal %d\n", sig);
1479
1480         g_timeout_add(0, clean_quit, NULL);
1481 }
1482
1483 static void install_basic_sighandlers()
1484 {
1485 #ifndef G_OS_WIN32
1486         sigset_t    mask;
1487         struct sigaction act;
1488
1489         sigemptyset(&mask);
1490
1491 #ifdef SIGTERM
1492         sigaddset(&mask, SIGTERM);
1493 #endif
1494 #ifdef SIGINT
1495         sigaddset(&mask, SIGINT);
1496 #endif
1497 #ifdef SIGHUP
1498         sigaddset(&mask, SIGHUP);
1499 #endif
1500
1501         act.sa_handler = quit_signal_handler;
1502         act.sa_mask    = mask;
1503         act.sa_flags   = 0;
1504
1505 #ifdef SIGTERM
1506         sigaction(SIGTERM, &act, 0);
1507 #endif
1508 #ifdef SIGINT
1509         sigaction(SIGINT, &act, 0);
1510 #endif  
1511 #ifdef SIGHUP
1512         sigaction(SIGHUP, &act, 0);
1513 #endif  
1514
1515         sigprocmask(SIG_UNBLOCK, &mask, 0);
1516 #endif /* !G_OS_WIN32 */
1517 }