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