2007-01-18 [paul] 2.7.1cvs22
[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                            !strncmp(argv[i], "-v", 2)) {
1035                         puts("Claws Mail version " VERSION);
1036                         exit(0);
1037                 } else if (!strncmp(argv[i], "--status-full", 13)) {
1038                         const gchar *p = argv[i + 1];
1039  
1040                         cmd.status_full = TRUE;
1041                         while (p && *p != '\0' && *p != '-') {
1042                                 if (!cmd.status_full_folders) {
1043                                         cmd.status_full_folders =
1044                                                 g_ptr_array_new();
1045                                 }
1046                                 g_ptr_array_add(cmd.status_full_folders,
1047                                                 g_strdup(p));
1048                                 i++;
1049                                 p = argv[i + 1];
1050                         }
1051                 } else if (!strncmp(argv[i], "--status", 8)) {
1052                         const gchar *p = argv[i + 1];
1053  
1054                         cmd.status = TRUE;
1055                         while (p && *p != '\0' && *p != '-') {
1056                                 if (!cmd.status_folders)
1057                                         cmd.status_folders = g_ptr_array_new();
1058                                 g_ptr_array_add(cmd.status_folders,
1059                                                 g_strdup(p));
1060                                 i++;
1061                                 p = argv[i + 1];
1062                         }
1063                 } else if (!strncmp(argv[i], "--online", 8)) {
1064                         cmd.online_mode = ONLINE_MODE_ONLINE;
1065                 } else if (!strncmp(argv[i], "--offline", 9)) {
1066                         cmd.online_mode = ONLINE_MODE_OFFLINE;
1067                 } else if (!strncmp(argv[i], "--help", 6) ||
1068                            !strncmp(argv[i], "-h", 2)) {
1069                         gchar *base = g_path_get_basename(argv[0]);
1070                         g_print(_("Usage: %s [OPTION]...\n"), base);
1071
1072                         g_print("%s\n", _("  --compose [address]    open composition window"));
1073                         g_print("%s\n", _("  --subscribe [uri]      subscribe to the given URI if possible"));
1074                         g_print("%s\n", _("  --attach file1 [file2]...\n"
1075                                   "                         open composition window with specified files\n"
1076                                   "                         attached"));
1077                         g_print("%s\n", _("  --receive              receive new messages"));
1078                         g_print("%s\n", _("  --receive-all          receive new messages of all accounts"));
1079                         g_print("%s\n", _("  --send                 send all queued messages"));
1080                         g_print("%s\n", _("  --status [folder]...   show the total number of messages"));
1081                         g_print("%s\n", _("  --status-full [folder]...\n"
1082                                "                         show the status of each folder"));
1083                         g_print("%s\n", _("  --select folder[/msg]  jumps to the specified folder/message\n" 
1084                                           "                         folder is a folder id like 'folder/sub_folder'"));
1085                         g_print("%s\n", _("  --online               switch to online mode"));
1086                         g_print("%s\n", _("  --offline              switch to offline mode"));
1087                         g_print("%s\n", _("  --exit --quit -q       exit Claws Mail"));
1088                         g_print("%s\n", _("  --debug                debug mode"));
1089                         g_print("%s\n", _("  --help -h              display this help and exit"));
1090                         g_print("%s\n", _("  --version -v           output version information and exit"));
1091                         g_print("%s\n", _("  --config-dir           output configuration directory"));
1092
1093                         g_free(base);
1094                         exit(1);
1095                 } else if (!strncmp(argv[i], "--crash", 7)) {
1096                         cmd.crash = TRUE;
1097                         cmd.crash_params = g_strdup(argv[i + 1]);
1098                         i++;
1099                 } else if (!strncmp(argv[i], "--config-dir", sizeof "--config-dir" - 1)) {
1100                         puts(RC_DIR);
1101                         exit(0);
1102                 } else if (!strncmp(argv[i], "--exit", 6) ||
1103                            !strncmp(argv[i], "--quit", 6) ||
1104                            !strncmp(argv[i], "-q", 2)) {
1105                         cmd.exit = TRUE;
1106                 } else if (!strncmp(argv[i], "--select", 8) && i+1 < argc) {
1107                         cmd.target = argv[i+1];
1108                 } else if (i == 1 && argc == 2) {
1109                         /* only one parameter. Do something intelligent about it */
1110                         if (strstr(argv[i], "@") && !strstr(argv[i], "://")) {
1111                                 const gchar *p = argv[i];
1112
1113                                 cmd.compose = TRUE;
1114                                 cmd.compose_mailto = NULL;
1115                                 if (p && *p != '\0' && *p != '-') {
1116                                         if (!strncmp(p, "mailto:", 7)) {
1117                                                 cmd.compose_mailto = p + 7;
1118                                         } else {
1119                                                 cmd.compose_mailto = p;
1120                                         }
1121                                 }
1122                         } else if (strstr(argv[i], "://")) {
1123                                 const gchar *p = argv[i];
1124                                 if (p && *p != '\0' && *p != '-') {
1125                                         cmd.subscribe = TRUE;
1126                                         cmd.subscribe_uri = p;
1127                                 }
1128                         } else {
1129                                 g_print(_("Unknown option\n"));
1130                                 exit(1);
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 gchar *get_socket_name(void)
1275 {
1276         static gchar *filename = NULL;
1277
1278         if (filename == NULL) {
1279                 filename = g_strdup_printf("%s%cclaws-mail-%d",
1280                                            g_get_tmp_dir(), G_DIR_SEPARATOR,
1281 #if HAVE_GETUID
1282                                            getuid());
1283 #else
1284                                            0);                                          
1285 #endif
1286         }
1287
1288         return filename;
1289 }
1290
1291 static gchar *get_crashfile_name(void)
1292 {
1293         static gchar *filename = NULL;
1294
1295         if (filename == NULL) {
1296                 filename = g_strdup_printf("%s%cclaws-crashed",
1297                                            get_tmp_dir(), G_DIR_SEPARATOR);
1298         }
1299
1300         return filename;
1301 }
1302
1303 static gint prohibit_duplicate_launch(void)
1304 {
1305         gint uxsock;
1306         gchar *path;
1307
1308         path = get_socket_name();
1309         uxsock = fd_connect_unix(path);
1310         if (uxsock < 0) {
1311                 g_unlink(path);
1312                 return fd_open_unix(path);
1313         }
1314
1315         /* remote command mode */
1316
1317         debug_print("another Claws Mail instance is already running.\n");
1318
1319         if (cmd.receive_all) {
1320                 fd_write_all(uxsock, "receive_all\n", 12);
1321         } else if (cmd.receive) {
1322                 fd_write_all(uxsock, "receive\n", 8);
1323         } else if (cmd.compose && cmd.attach_files) {
1324                 gchar *str, *compose_str;
1325                 gint i;
1326
1327                 if (cmd.compose_mailto) {
1328                         compose_str = g_strdup_printf("compose_attach %s\n",
1329                                                       cmd.compose_mailto);
1330                 } else {
1331                         compose_str = g_strdup("compose_attach\n");
1332                 }
1333
1334                 fd_write_all(uxsock, compose_str, strlen(compose_str));
1335                 g_free(compose_str);
1336
1337                 for (i = 0; i < cmd.attach_files->len; i++) {
1338                         str = g_ptr_array_index(cmd.attach_files, i);
1339                         fd_write_all(uxsock, str, strlen(str));
1340                         fd_write_all(uxsock, "\n", 1);
1341                 }
1342
1343                 fd_write_all(uxsock, ".\n", 2);
1344         } else if (cmd.compose) {
1345                 gchar *compose_str;
1346
1347                 if (cmd.compose_mailto) {
1348                         compose_str = g_strdup_printf
1349                                 ("compose %s\n", cmd.compose_mailto);
1350                 } else {
1351                         compose_str = g_strdup("compose\n");
1352                 }
1353
1354                 fd_write_all(uxsock, compose_str, strlen(compose_str));
1355                 g_free(compose_str);
1356         } else if (cmd.subscribe) {
1357                 gchar *str = g_strdup_printf("subscribe %s\n", cmd.subscribe_uri);
1358                 fd_write_all(uxsock, str, strlen(str));
1359                 g_free(str);
1360         } else if (cmd.send) {
1361                 fd_write_all(uxsock, "send\n", 5);
1362         } else if (cmd.online_mode == ONLINE_MODE_ONLINE) {
1363                 fd_write(uxsock, "online\n", 6);
1364         } else if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
1365                 fd_write(uxsock, "offline\n", 7);
1366         } else if (cmd.status || cmd.status_full) {
1367                 gchar buf[BUFFSIZE];
1368                 gint i;
1369                 const gchar *command;
1370                 GPtrArray *folders;
1371                 gchar *folder;
1372  
1373                 command = cmd.status_full ? "status-full\n" : "status\n";
1374                 folders = cmd.status_full ? cmd.status_full_folders :
1375                         cmd.status_folders;
1376  
1377                 fd_write_all(uxsock, command, strlen(command));
1378                 for (i = 0; folders && i < folders->len; ++i) {
1379                         folder = g_ptr_array_index(folders, i);
1380                         fd_write_all(uxsock, folder, strlen(folder));
1381                         fd_write_all(uxsock, "\n", 1);
1382                 }
1383                 fd_write_all(uxsock, ".\n", 2);
1384                 for (;;) {
1385                         fd_gets(uxsock, buf, sizeof(buf));
1386                         if (!strncmp(buf, ".\n", 2)) break;
1387                         fputs(buf, stdout);
1388                 }
1389         } else if (cmd.exit) {
1390                 fd_write_all(uxsock, "exit\n", 5);
1391         } else if (cmd.target) {
1392                 gchar *str = g_strdup_printf("select %s\n", cmd.target);
1393                 fd_write_all(uxsock, str, strlen(str));
1394                 g_free(str);
1395         } else
1396                 fd_write_all(uxsock, "popup\n", 6);
1397
1398         fd_close(uxsock);
1399         return -1;
1400 }
1401
1402 static gint lock_socket_remove(void)
1403 {
1404 #ifdef G_OS_UNIX
1405         gchar *filename;
1406
1407         if (lock_socket < 0) {
1408                 return -1;
1409         }
1410
1411         if (lock_socket_tag > 0) {
1412                 gdk_input_remove(lock_socket_tag);
1413         }
1414         fd_close(lock_socket);
1415         filename = get_socket_name();
1416         g_unlink(filename);
1417 #endif
1418
1419         return 0;
1420 }
1421
1422 static GPtrArray *get_folder_item_list(gint sock)
1423 {
1424         gchar buf[BUFFSIZE];
1425         FolderItem *item;
1426         GPtrArray *folders = NULL;
1427
1428         for (;;) {
1429                 fd_gets(sock, buf, sizeof(buf));
1430                 if (!strncmp(buf, ".\n", 2)) {
1431                         break;
1432                 }
1433                 strretchomp(buf);
1434                 if (!folders) {
1435                         folders = g_ptr_array_new();
1436                 }
1437                 item = folder_find_item_from_identifier(buf);
1438                 if (item) {
1439                         g_ptr_array_add(folders, item);
1440                 } else {
1441                         g_warning("no such folder: %s\n", buf);
1442                 }
1443         }
1444
1445         return folders;
1446 }
1447
1448 static void lock_socket_input_cb(gpointer data,
1449                                  gint source,
1450                                  GdkInputCondition condition)
1451 {
1452         MainWindow *mainwin = (MainWindow *)data;
1453         gint sock;
1454         gchar buf[BUFFSIZE];
1455
1456         sock = fd_accept(source);
1457         fd_gets(sock, buf, sizeof(buf));
1458
1459         if (!strncmp(buf, "popup", 5)) {
1460                 main_window_popup(mainwin);
1461         } else if (!strncmp(buf, "receive_all", 11)) {
1462                 inc_all_account_mail(mainwin, FALSE,
1463                                      prefs_common.newmail_notify_manu);
1464         } else if (!strncmp(buf, "receive", 7)) {
1465                 inc_mail(mainwin, prefs_common.newmail_notify_manu);
1466         } else if (!strncmp(buf, "compose_attach", 14)) {
1467                 GPtrArray *files;
1468                 gchar *mailto;
1469
1470                 mailto = g_strdup(buf + strlen("compose_attach") + 1);
1471                 files = g_ptr_array_new();
1472                 while (fd_gets(sock, buf, sizeof(buf)) > 0) {
1473                         if (buf[0] == '.' && buf[1] == '\n') {
1474                                 break;
1475                         }
1476                         strretchomp(buf);
1477                         g_ptr_array_add(files, g_strdup(buf));
1478                 }
1479                 open_compose_new(mailto, files);
1480                 ptr_array_free_strings(files);
1481                 g_ptr_array_free(files, TRUE);
1482                 g_free(mailto);
1483         } else if (!strncmp(buf, "compose", 7)) {
1484                 open_compose_new(buf + strlen("compose") + 1, NULL);
1485         } else if (!strncmp(buf, "subscribe", 9)) {
1486                 main_window_popup(mainwin);
1487                 folder_subscribe(buf + strlen("subscribe") + 1);
1488         } else if (!strncmp(buf, "send", 4)) {
1489                 send_queue();
1490         } else if (!strncmp(buf, "online", 6)) {
1491                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
1492         } else if (!strncmp(buf, "offline", 7)) {
1493                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
1494         } else if (!strncmp(buf, "status-full", 11) ||
1495                    !strncmp(buf, "status", 6)) {
1496                 gchar *status;
1497                 GPtrArray *folders;
1498  
1499                 folders = get_folder_item_list(sock);
1500                 status = folder_get_status
1501                         (folders, !strncmp(buf, "status-full", 11));
1502                 fd_write_all(sock, status, strlen(status));
1503                 fd_write_all(sock, ".\n", 2);
1504                 g_free(status);
1505                 if (folders) g_ptr_array_free(folders, TRUE);
1506         } else if (!strncmp(buf, "select ", 7)) {
1507                 const gchar *target = buf+7;
1508                 mainwindow_jump_to(target);
1509         } else if (!strncmp(buf, "exit", 4)) {
1510                 app_will_exit(NULL, mainwin);
1511         }
1512
1513         fd_close(sock);
1514 }
1515
1516 static void open_compose_new(const gchar *address, GPtrArray *attach_files)
1517 {
1518         gchar *addr = NULL;
1519
1520         if (address) {
1521                 Xstrdup_a(addr, address, return);
1522                 g_strstrip(addr);
1523         }
1524
1525         compose_new(NULL, addr, attach_files);
1526 }
1527
1528 static void send_queue(void)
1529 {
1530         GList *list;
1531         gchar *errstr = NULL;
1532         for (list = folder_get_list(); list != NULL; list = list->next) {
1533                 Folder *folder = list->data;
1534
1535                 if (folder->queue) {
1536                         gint res = procmsg_send_queue
1537                                 (folder->queue, prefs_common.savemsg,
1538                                 &errstr);
1539
1540                         if (res) {
1541                                 folder_item_scan(folder->queue);
1542                         }
1543                 }
1544         }
1545         if (errstr) {
1546                 gchar *tmp = g_strdup_printf(_("Some errors occurred "
1547                                 "while sending queued messages:\n%s"), errstr);
1548                 g_free(errstr);
1549                 alertpanel_error_log(tmp);
1550                 g_free(tmp);
1551         } else {
1552                 alertpanel_error_log("Some errors occurred "
1553                                 "while sending queued messages.");
1554         }
1555 }
1556
1557 static void quit_signal_handler(int sig)
1558 {
1559         debug_print("Quitting on signal %d\n", sig);
1560
1561         g_timeout_add(0, clean_quit, NULL);
1562 }
1563
1564 static void install_basic_sighandlers()
1565 {
1566 #ifndef G_OS_WIN32
1567         sigset_t    mask;
1568         struct sigaction act;
1569
1570         sigemptyset(&mask);
1571
1572 #ifdef SIGTERM
1573         sigaddset(&mask, SIGTERM);
1574 #endif
1575 #ifdef SIGINT
1576         sigaddset(&mask, SIGINT);
1577 #endif
1578 #ifdef SIGHUP
1579         sigaddset(&mask, SIGHUP);
1580 #endif
1581
1582         act.sa_handler = quit_signal_handler;
1583         act.sa_mask    = mask;
1584         act.sa_flags   = 0;
1585
1586 #ifdef SIGTERM
1587         sigaction(SIGTERM, &act, 0);
1588 #endif
1589 #ifdef SIGINT
1590         sigaction(SIGINT, &act, 0);
1591 #endif  
1592 #ifdef SIGHUP
1593         sigaction(SIGHUP, &act, 0);
1594 #endif  
1595
1596         sigprocmask(SIG_UNBLOCK, &mask, 0);
1597 #endif /* !G_OS_WIN32 */
1598 }