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