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