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