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