5459f794d77ed4d9b4167eb553f21a392ec1b41d
[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 3 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, see <http://www.gnu.org/licenses/>.
17  * 
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_logging.h"
75 #include "prefs_send.h"
76 #include "prefs_wrapping.h"
77 #include "prefs_compose_writing.h"
78 #include "prefs_display_header.h"
79 #include "account.h"
80 #include "procmsg.h"
81 #include "inc.h"
82 #include "import.h"
83 #include "manage_window.h"
84 #include "alertpanel.h"
85 #include "statusbar.h"
86 #include "addressbook.h"
87 #include "compose.h"
88 #include "folder.h"
89 #include "setup.h"
90 #include "utils.h"
91 #include "gtkutils.h"
92 #include "socket.h"
93 #include "log.h"
94 #include "prefs_toolbar.h"
95 #include "plugin.h"
96 #include "mh_gtk.h"
97 #include "imap_gtk.h"
98 #include "news_gtk.h"
99 #include "matcher.h"
100 #include "tags.h"
101 #ifdef HAVE_LIBETPAN
102 #include "imap-thread.h"
103 #endif
104 #include "stock_pixmap.h"
105 #ifdef HAVE_VALGRIND
106 #include "valgrind.h"
107 #endif
108 #if USE_OPENSSL
109 #  include "ssl.h"
110 #endif
111
112 #include "version.h"
113
114 #include "crash.h"
115
116 #include "timing.h"
117
118 #ifdef MAEMO
119 #include <hildon-widgets/hildon-banner.h>
120 #include <hildon-widgets/hildon-program.h>
121 #include <gtk/gtkmain.h>
122 #include <libosso.h>
123 #include <libgnomevfs/gnome-vfs-volume.h>
124 #include <libgnomevfs/gnome-vfs-volume-monitor.h>
125 #include <libgnomevfs/gnome-vfs-utils.h>
126
127 #define OSSO_NAME    "claws_mail"
128 #define OSSO_SERVICE "com.nokia."OSSO_NAME
129 #define OSSO_OBJECT  "/com/nokia/"OSSO_NAME
130 #define OSSO_IFACE   "com.nokia."OSSO_NAME
131
132 typedef struct _AppData AppData;
133 struct _AppData {
134     HildonProgram *program;
135     HildonWindow *window;
136     osso_context_t *osso_context;
137 };
138
139 static GnomeVFSVolumeMonitor *volmon;
140 #endif
141
142 gchar *prog_version;
143 gchar *argv0;
144
145 #ifdef HAVE_STARTUP_NOTIFICATION
146 static SnLauncheeContext *sn_context = NULL;
147 static SnDisplay *sn_display = NULL;
148 #endif
149
150 static gint lock_socket = -1;
151 static gint lock_socket_tag = 0;
152 static gchar *x_display = NULL;
153 typedef enum 
154 {
155         ONLINE_MODE_DONT_CHANGE,
156         ONLINE_MODE_ONLINE,
157         ONLINE_MODE_OFFLINE
158 } OnlineMode;
159
160 static struct RemoteCmd {
161         gboolean receive;
162         gboolean receive_all;
163         gboolean compose;
164         const gchar *compose_mailto;
165         GPtrArray *attach_files;
166         gboolean status;
167         gboolean status_full;
168         GPtrArray *status_folders;
169         GPtrArray *status_full_folders;
170         gboolean send;
171         gboolean crash;
172         int online_mode;
173         gchar   *crash_params;
174         gboolean exit;
175         gboolean subscribe;
176         const gchar *subscribe_uri;
177         const gchar *target;
178 } cmd;
179
180 static void parse_cmd_opt(int argc, char *argv[]);
181
182 static gint prohibit_duplicate_launch   (void);
183 static gchar * get_crashfile_name       (void);
184 static gint lock_socket_remove          (void);
185 static void lock_socket_input_cb        (gpointer          data,
186                                          gint              source,
187                                          GdkInputCondition condition);
188
189 static void open_compose_new            (const gchar    *address,
190                                          GPtrArray      *attach_files);
191
192 static void send_queue                  (void);
193 static void initial_processing          (FolderItem *item, gpointer data);
194 static void quit_signal_handler         (int sig);
195 static void install_basic_sighandlers   (void);
196 static void exit_claws                  (MainWindow *mainwin);
197
198 #define MAKE_DIR_IF_NOT_EXIST(dir) \
199 { \
200         if (!is_dir_exist(dir)) { \
201                 if (is_file_exist(dir)) { \
202                         alertpanel_warning \
203                                 (_("File '%s' already exists.\n" \
204                                    "Can't create folder."), \
205                                  dir); \
206                         return 1; \
207                 } \
208                 if (make_dir(dir) < 0) \
209                         return 1; \
210         } \
211 }
212
213 static MainWindow *static_mainwindow;
214
215 #ifdef MAEMO
216 static HildonProgram *static_hildonprogram;
217 static osso_context_t *static_osso_context;
218
219 void exit_event_handler(gboolean die_now, gpointer data)
220 {
221         AppData *appdata;
222         appdata = (AppData *) data;
223         /* Do whatever application needs to do before exiting */
224         exit_claws(static_mainwindow);
225         hildon_banner_show_information(GTK_WIDGET(appdata->window), NULL,
226                                    _("Exiting..."));
227
228 }
229
230 /* Callback for normal D-BUS messages */
231 gint dbus_req_handler(const gchar * interface, const gchar * method,
232                       GArray * arguments, gpointer data,
233                       osso_rpc_t * retval)
234 {
235     AppData *appdata;
236     appdata = (AppData *) data;
237
238     if (!strcmp(method, "top_application")) {
239             osso_rpc_free_val(retval);
240             return OSSO_OK;
241     }
242     osso_system_note_infoprint(appdata->osso_context, method, retval);
243     osso_rpc_free_val(retval);
244
245     return OSSO_OK;
246 }
247 #endif
248 static gboolean emergency_exit = FALSE;
249
250 #ifdef HAVE_STARTUP_NOTIFICATION
251 static void sn_error_trap_push(SnDisplay *display, Display *xdisplay)
252 {
253         gdk_error_trap_push();
254 }
255
256 static void sn_error_trap_pop(SnDisplay *display, Display *xdisplay)
257 {
258         gdk_error_trap_pop();
259 }
260
261 static void startup_notification_complete(gboolean with_window)
262 {
263         Display *xdisplay;
264         GtkWidget *hack = NULL;
265
266         if (with_window) {
267                 /* this is needed to make the startup notification leave,
268                  * if we have been launched from a menu.
269                  * We have to display a window, so let it be very little */
270                 hack = gtk_window_new(GTK_WINDOW_POPUP);
271                 gtk_widget_set_uposition(hack, 0, 0);
272                 gtk_widget_set_size_request(hack, 1, 1);
273                 gtk_widget_show(hack);
274         }
275
276         xdisplay = GDK_DISPLAY();
277         sn_display = sn_display_new(xdisplay,
278                                 sn_error_trap_push,
279                                 sn_error_trap_pop);
280         sn_context = sn_launchee_context_new_from_environment(sn_display,
281                                                  DefaultScreen(xdisplay));
282
283         if (sn_context != NULL) {
284                 sn_launchee_context_complete(sn_context);
285                 sn_launchee_context_unref(sn_context);
286                 sn_display_unref(sn_display);
287         }
288         if (with_window) {
289                 gtk_widget_destroy(hack);
290         }
291 }
292 #endif /* HAVE_STARTUP_NOTIFICATION */
293
294 static void claws_gtk_idle(void) 
295 {
296         while(gtk_events_pending()) {
297                 gtk_main_iteration();
298         }
299         g_usleep(50000);
300 }
301
302 static gboolean sc_starting = FALSE;
303
304 static gboolean defer_check_all(void *data)
305 {
306         gboolean autochk = GPOINTER_TO_INT(data);
307
308         inc_all_account_mail(static_mainwindow, autochk, 
309                         prefs_common.newmail_notify_manu);
310
311         if (sc_starting) {
312                 sc_starting = FALSE;
313                 main_window_set_menu_sensitive(static_mainwindow);
314                 toolbar_main_set_sensitive(static_mainwindow);
315         }
316         return FALSE;
317 }
318
319 static gboolean defer_check(void *data)
320 {
321         inc_mail(static_mainwindow, prefs_common.newmail_notify_manu);
322
323         if (sc_starting) {
324                 sc_starting = FALSE;
325                 main_window_set_menu_sensitive(static_mainwindow);
326                 toolbar_main_set_sensitive(static_mainwindow);
327         }
328         return FALSE;
329 }
330
331 static gboolean defer_jump(void *data)
332 {
333         if (cmd.receive_all) {
334                 defer_check_all(GINT_TO_POINTER(FALSE));
335         } else if (prefs_common.chk_on_startup) {
336                 defer_check_all(GINT_TO_POINTER(TRUE));
337         } else if (cmd.receive) {
338                 defer_check(NULL);
339         } 
340         mainwindow_jump_to(data, FALSE);
341         if (sc_starting) {
342                 sc_starting = FALSE;
343                 main_window_set_menu_sensitive(static_mainwindow);
344                 toolbar_main_set_sensitive(static_mainwindow);
345         }
346         return FALSE;
347 }
348
349 static void chk_update_val(GtkWidget *widget, gpointer data)
350 {
351         gboolean *val = (gboolean *)data;
352         *val = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget));
353 }
354
355 static gboolean migrate_old_config(const gchar *old_cfg_dir, const gchar *new_cfg_dir, const gchar *oldversion)
356 {
357         gchar *message = g_strdup_printf(_("Configuration for %s found.\n"
358                          "Do you want to migrate this configuration?"), oldversion);
359         gchar *message2 = g_strdup_printf(_("\n\nYour Sylpheed filtering rules can be converted by a\n"
360                              "script available at %s."), TOOLS_URI);
361
362         if (!strcmp(oldversion, "Sylpheed"))
363                 message = g_strconcat(message, message2, NULL);
364         g_free(message2);
365
366         gint r = 0;
367         GtkWidget *window = NULL;
368         GtkWidget *keep_backup_chk;
369         GtkTooltips *tips = gtk_tooltips_new();
370         gboolean backup = TRUE;
371
372         keep_backup_chk = gtk_check_button_new_with_label (_("Keep old configuration"));
373         gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(keep_backup_chk), TRUE);
374         gtk_tooltips_set_tip(GTK_TOOLTIPS(tips), keep_backup_chk,
375                              _("Keeping a backup will allow you to go back to an "
376                                "older version, but may take a while if you have "
377                                "cached IMAP or News data, and will take some extra "
378                                "room on your disk."),
379                              NULL);
380
381         g_signal_connect(G_OBJECT(keep_backup_chk), "toggled", 
382                         G_CALLBACK(chk_update_val), &backup);
383
384         if (alertpanel_full(_("Migration of configuration"), message,
385                         GTK_STOCK_NO, "+" GTK_STOCK_YES, NULL, FALSE,
386                         keep_backup_chk, ALERT_QUESTION, G_ALERTDEFAULT) != G_ALERTALTERNATE) {
387                 return FALSE;
388         }
389         
390         /* we can either do a fast migration requiring not any extra disk
391          * space, or a slow one that copies the old configuration and leaves
392          * it in place. */
393         if (backup) {
394 backup_mode:
395                 window = label_window_create(_("Copying configuration... This may take a while..."));
396                 GTK_EVENTS_FLUSH();
397                 
398                 r = copy_dir(old_cfg_dir, new_cfg_dir);
399                 label_window_destroy(window);
400                 
401                 /* if copy failed, we'll remove the partially copied
402                  * new directory */
403                 if (r != 0) {
404                         alertpanel_error(_("Migration failed!"));
405                         remove_dir_recursive(new_cfg_dir);
406                 } else {
407                         if (!backup) {
408                                 /* fast mode failed, but we don't want backup */
409                                 remove_dir_recursive(old_cfg_dir);
410                         }
411                 }
412         } else {
413                 window = label_window_create(_("Migrating configuration..."));
414                 GTK_EVENTS_FLUSH();
415                 
416                 r = g_rename(old_cfg_dir, new_cfg_dir);
417                 label_window_destroy(window);
418                 
419                 /* if g_rename failed, we'll try to copy */
420                 if (r != 0) {
421                         FILE_OP_ERROR(new_cfg_dir, "g_rename failed, trying copy\n");
422                         goto backup_mode;
423                 }
424         }
425         return (r == 0);
426 }
427
428 static int migrate_common_rc(const gchar *old_rc, const gchar *new_rc)
429 {
430         FILE *oldfp, *newfp;
431         gchar *plugin_path, *old_plugin_path, *new_plugin_path;
432         gchar buf[BUFFSIZE];
433         gboolean err = FALSE;
434
435         oldfp = g_fopen(old_rc, "r");
436         if (!oldfp)
437                 return -1;
438         newfp = g_fopen(new_rc, "w");
439         if (!newfp) {
440                 fclose(oldfp);
441                 return -1;
442         }
443         
444         plugin_path = g_strdup(get_plugin_dir());
445         new_plugin_path = g_strdup(plugin_path);
446         
447         if (strstr(plugin_path, "/claws-mail/")) {
448                 gchar *end = g_strdup(strstr(plugin_path, "/claws-mail/")+strlen("/claws-mail/"));
449                 *(strstr(plugin_path, "/claws-mail/")) = '\0';
450                 old_plugin_path = g_strconcat(plugin_path, "/sylpheed-claws/", end, NULL);
451                 g_free(end);
452         } else {
453                 old_plugin_path = g_strdup(new_plugin_path);
454         }
455         debug_print("replacing %s with %s\n", old_plugin_path, new_plugin_path);
456         while (fgets(buf, sizeof(buf), oldfp)) {
457                 if (strncmp(buf, old_plugin_path, strlen(old_plugin_path))) {
458                         err |= (fputs(buf, newfp) == EOF);
459                 } else {
460                         debug_print("->replacing %s", buf);
461                         debug_print("  with %s%s", new_plugin_path, buf+strlen(old_plugin_path));
462                         err |= (fputs(new_plugin_path, newfp) == EOF);
463                         err |= (fputs(buf+strlen(old_plugin_path), newfp) == EOF);
464                 }
465         }
466         g_free(plugin_path);
467         g_free(new_plugin_path);
468         g_free(old_plugin_path);
469         fclose(oldfp);
470         if (fclose(newfp) == EOF)
471                 err = TRUE;
472         
473         return (err ? -1:0);
474 }
475
476 #ifdef HAVE_LIBSM
477 static void
478 sc_client_set_value (MainWindow *mainwin,
479                   gchar       *name,
480                   char        *type,
481                   int          num_vals,
482                   SmPropValue *vals)
483 {
484         SmProp *proplist[1];
485         SmProp prop;
486
487         prop.name = name;
488         prop.type = type;
489         prop.num_vals = num_vals;
490         prop.vals = vals;
491
492         proplist[0]= &prop;
493         if (mainwin->smc_conn)
494                 SmcSetProperties ((SmcConn) mainwin->smc_conn, 1, proplist);
495 }
496
497 static void sc_die_callback (SmcConn smc_conn, SmPointer client_data)
498 {
499         clean_quit(NULL);
500 }
501
502 static void sc_save_complete_callback(SmcConn smc_conn, SmPointer client_data)
503 {
504 }
505
506 static void sc_shutdown_cancelled_callback (SmcConn smc_conn, SmPointer client_data)
507 {
508         MainWindow *mainwin = (MainWindow *)client_data;
509         if (mainwin->smc_conn)
510                 SmcSaveYourselfDone ((SmcConn) mainwin->smc_conn, TRUE);
511 }
512
513 static void sc_save_yourself_callback (SmcConn   smc_conn,
514                                SmPointer client_data,
515                                int       save_style,
516                                gboolean  shutdown,
517                                int       interact_style,
518                                gboolean  fast) {
519
520         MainWindow *mainwin = (MainWindow *)client_data;
521         if (mainwin->smc_conn)
522                 SmcSaveYourselfDone ((SmcConn) mainwin->smc_conn, TRUE);
523 }
524
525 static IceIOErrorHandler sc_ice_installed_handler;
526
527 static void sc_ice_io_error_handler (IceConn connection)
528 {
529         if (sc_ice_installed_handler)
530                 (*sc_ice_installed_handler) (connection);
531 }
532 static gboolean sc_process_ice_messages (GIOChannel   *source,
533                       GIOCondition  condition,
534                       gpointer      data)
535 {
536         IceConn connection = (IceConn) data;
537         IceProcessMessagesStatus status;
538
539         status = IceProcessMessages (connection, NULL, NULL);
540
541         if (status == IceProcessMessagesIOError) {
542                 IcePointer context = IceGetConnectionContext (connection);
543
544                 if (context && GTK_IS_OBJECT (context)) {
545                 guint disconnect_id = g_signal_lookup ("disconnect", G_OBJECT_TYPE (context));
546
547                 if (disconnect_id > 0)
548                         g_signal_emit (context, disconnect_id, 0);
549                 } else {
550                         IceSetShutdownNegotiation (connection, False);
551                         IceCloseConnection (connection);
552                 }
553         }
554
555         return TRUE;
556 }
557
558 static void new_ice_connection (IceConn connection, IcePointer client_data, Bool opening,
559                     IcePointer *watch_data)
560 {
561         guint input_id;
562
563         if (opening) {
564                 GIOChannel *channel;
565                 /* Make sure we don't pass on these file descriptors to any
566                 exec'ed children */
567                 fcntl(IceConnectionNumber(connection),F_SETFD,
568                 fcntl(IceConnectionNumber(connection),F_GETFD,0) | FD_CLOEXEC);
569
570                 channel = g_io_channel_unix_new (IceConnectionNumber (connection));
571                 input_id = g_io_add_watch (channel,
572                 G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_PRI,
573                 sc_process_ice_messages,
574                 connection);
575                 g_io_channel_unref (channel);
576
577                 *watch_data = (IcePointer) GUINT_TO_POINTER (input_id);
578         } else {
579                 input_id = GPOINTER_TO_UINT ((gpointer) *watch_data);
580                 g_source_remove (input_id);
581         }
582 }
583
584 static void sc_session_manager_connect(MainWindow *mainwin)
585 {
586         static gboolean connected = FALSE;
587         SmcCallbacks      callbacks;
588         gchar            *client_id;
589         IceIOErrorHandler default_handler;
590
591         if (connected)
592                 return;
593         connected = TRUE;
594
595
596         sc_ice_installed_handler = IceSetIOErrorHandler (NULL);
597         default_handler = IceSetIOErrorHandler (sc_ice_io_error_handler);
598
599         if (sc_ice_installed_handler == default_handler)
600                 sc_ice_installed_handler = NULL;
601
602         IceAddConnectionWatch (new_ice_connection, NULL);
603       
604       
605         callbacks.save_yourself.callback      = sc_save_yourself_callback;
606         callbacks.die.callback                = sc_die_callback;
607         callbacks.save_complete.callback      = sc_save_complete_callback;
608         callbacks.shutdown_cancelled.callback = sc_shutdown_cancelled_callback;
609
610         callbacks.save_yourself.client_data =
611                 callbacks.die.client_data =
612                 callbacks.save_complete.client_data =
613                 callbacks.shutdown_cancelled.client_data = (SmPointer) mainwin;
614         if (g_getenv ("SESSION_MANAGER")) {
615                 gchar error_string_ret[256] = "";
616
617                 mainwin->smc_conn = (gpointer)
618                         SmcOpenConnection (NULL, mainwin,
619                                 SmProtoMajor, SmProtoMinor,
620                                 SmcSaveYourselfProcMask | SmcDieProcMask |
621                                 SmcSaveCompleteProcMask |
622                                 SmcShutdownCancelledProcMask,
623                                 &callbacks,
624                                 NULL, &client_id,
625                                 256, error_string_ret);
626
627                 if (error_string_ret[0] || mainwin->smc_conn == NULL)
628                         g_warning ("While connecting to session manager:\n%s.",
629                                 error_string_ret);
630                 else {
631                         SmPropValue *vals;
632                         vals = g_new (SmPropValue, 1);
633                         vals[0].length = strlen(argv0);
634                         vals[0].value = argv0;
635                         sc_client_set_value (mainwin, SmCloneCommand, SmLISTofARRAY8, 1, vals);
636                         sc_client_set_value (mainwin, SmRestartCommand, SmLISTofARRAY8, 1, vals);
637                         sc_client_set_value (mainwin, SmProgram, SmARRAY8, 1, vals);
638
639                         vals[0].length = strlen(g_get_user_name()?g_get_user_name():"");
640                         vals[0].value = g_strdup(g_get_user_name()?g_get_user_name():"");
641                         sc_client_set_value (mainwin, SmUserID, SmARRAY8, 1, vals);
642                 }
643         }
644 }
645 #endif
646
647 static gboolean sc_exiting = FALSE;
648 static gboolean show_at_startup = TRUE;
649 static gboolean claws_crashed_bool = FALSE;
650
651 gboolean claws_crashed(void) {
652         return claws_crashed_bool;
653 }
654
655 void main_set_show_at_startup(gboolean show)
656 {
657         show_at_startup = show;
658 }
659
660 #ifdef MAEMO
661 static void main_vol_mount_cb(GnomeVFSVolumeMonitor *vfs, GnomeVFSVolume *vol, MainWindow *mainwin)
662 {
663         gchar *uri = gnome_vfs_volume_get_activation_uri (vol);
664         gchar *mount_path = uri?gnome_vfs_get_local_path_from_uri (uri):NULL;
665         g_free (uri);
666         if (mount_path) {
667                 if(!strcmp(mount_path, prefs_common.data_root)) {
668                         gtk_widget_set_sensitive(mainwin->window, TRUE);
669                         inc_unlock();
670                 }
671         }
672         g_free(mount_path);
673 }
674 static void main_vol_unmount_cb(GnomeVFSVolumeMonitor *vfs, GnomeVFSVolume *vol, MainWindow *mainwin)
675 {
676         gchar *uri = gnome_vfs_volume_get_activation_uri (vol);
677         gchar *mount_path = uri?gnome_vfs_get_local_path_from_uri (uri):NULL;
678         g_free (uri);
679         if (mount_path) {
680                 if(!strcmp(mount_path, prefs_common.data_root)) {
681                         gtk_widget_set_sensitive(mainwin->window, FALSE);
682                         inc_lock();
683                 }
684         }
685         g_free(mount_path);
686 }
687 #endif
688
689 #ifdef G_OS_WIN32
690 static FILE* win32_debug_fp=NULL;
691 static guint win32_log_handler_app_id;
692 static guint win32_log_handler_glib_id;
693 static guint win32_log_handler_gtk_id;
694
695 static void win32_print_stdout(const gchar *string)
696 {
697         if (win32_debug_fp) {
698                 fprintf(win32_debug_fp, string);
699                 fflush(win32_debug_fp);
700         }
701 }
702
703 static void win32_print_stderr(const gchar *string)
704 {
705         if (win32_debug_fp) {
706                 fprintf(win32_debug_fp, string);
707                 fflush(win32_debug_fp);
708         }
709 }
710
711 static void win32_log(const gchar *log_domain, GLogLevelFlags log_level, const gchar* message, gpointer user_data)
712 {
713         if (win32_debug_fp) {
714                 const gchar* type;
715
716                 switch(log_level & G_LOG_LEVEL_MASK)
717                 {
718                         case G_LOG_LEVEL_ERROR:
719                                 type="error";
720                                 break;
721                         case G_LOG_LEVEL_CRITICAL:
722                                 type="critical";
723                                 break;
724                         case G_LOG_LEVEL_WARNING:
725                                 type="warning";
726                                 break;
727                         case G_LOG_LEVEL_MESSAGE:
728                                 type="message";
729                                 break;
730                         case G_LOG_LEVEL_INFO:
731                                 type="info";
732                                 break;
733                         case G_LOG_LEVEL_DEBUG:
734                                 type="debug";
735                                 break;
736                         default:
737                                 type="N/A";
738                 }
739                 if (log_domain)
740                         fprintf(win32_debug_fp, "%s: %s: %s", log_domain, type, message);
741                 else
742                         fprintf(win32_debug_fp, "%s: %s", type, message);
743                 fflush(win32_debug_fp);
744         }
745 }
746
747 static void win32_open_log(void)
748 {
749         if (is_file_exist("claws-win32.log")) {
750                 if (rename_force("claws-win32.log", "claws-win32.log.bak") < 0)
751                         FILE_OP_ERROR("claws-win32.log", "rename");
752         }
753         win32_debug_fp = fopen("claws-win32.log", "w");
754         if (win32_debug_fp)
755         {
756                 g_set_print_handler(win32_print_stdout);
757                 g_set_printerr_handler(win32_print_stdout);
758                 win32_log_handler_app_id = g_log_set_handler(NULL, G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
759                      | G_LOG_FLAG_RECURSION, win32_log, NULL);
760                 win32_log_handler_glib_id = g_log_set_handler("GLib", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
761                      | G_LOG_FLAG_RECURSION, win32_log, NULL);
762                 win32_log_handler_gtk_id = g_log_set_handler("Gtk", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
763                      | G_LOG_FLAG_RECURSION, win32_log, NULL);
764         }
765 }
766
767 static void win32_close_log(void)
768 {
769         if (win32_debug_fp)
770         {
771                 g_log_remove_handler("", win32_log_handler_app_id);
772                 g_log_remove_handler("GLib", win32_log_handler_glib_id);
773                 g_log_remove_handler("Gtk", win32_log_handler_gtk_id);
774                 fclose(win32_debug_fp);
775                 win32_debug_fp=NULL;
776         }
777 }               
778 #endif
779
780 int main(int argc, char *argv[])
781 {
782 #ifdef MAEMO
783         osso_context_t *osso_context;
784         osso_return_t result;
785 #endif
786         gchar *userrc;
787         MainWindow *mainwin;
788         FolderView *folderview;
789         GdkPixbuf *icon;
790         gboolean crash_file_present = FALSE;
791         gint num_folder_class = 0;
792         gboolean asked_for_migration = FALSE;
793         gboolean start_done = TRUE;
794
795         START_TIMING("startup");
796         
797         sc_starting = TRUE;
798
799 #ifdef G_OS_WIN32
800         win32_open_log();
801 #endif
802         if (!claws_init(&argc, &argv)) {
803 #ifdef G_OS_WIN32
804                 win32_close_log();
805 #endif
806                 return 0;
807         }
808
809         prog_version = PROG_VERSION;
810         argv0 = g_strdup(argv[0]);
811
812         parse_cmd_opt(argc, argv);
813
814         prefs_prepare_cache();
815
816 #ifdef CRASH_DIALOG
817         if (cmd.crash) {
818                 gtk_set_locale();
819                 gtk_init(&argc, &argv);
820                 crash_main(cmd.crash_params);
821 #ifdef G_OS_WIN32
822                 win32_close_log();
823 #endif
824                 return 0;
825         }
826         crash_install_handlers();
827 #endif
828         install_basic_sighandlers();
829         sock_init();
830
831         /* check and create unix domain socket for remote operation */
832 #ifdef G_OS_UNIX
833         lock_socket = prohibit_duplicate_launch();
834         if (lock_socket < 0) {
835 #ifdef HAVE_STARTUP_NOTIFICATION
836                 if(gtk_init_check(&argc, &argv))
837                         startup_notification_complete(TRUE);
838 #endif
839                 return 0;
840         }
841
842         if (cmd.status || cmd.status_full) {
843                 puts("0 Claws Mail not running.");
844                 lock_socket_remove();
845                 return 0;
846         }
847         
848         if (cmd.exit)
849                 return 0;
850 #endif
851         if (!g_thread_supported())
852                 g_thread_init(NULL);
853
854         gtk_set_locale();
855         gtk_init(&argc, &argv);
856
857 #ifdef MAEMO
858         osso_context = osso_initialize(OSSO_SERVICE, "2.8.1", TRUE, NULL);
859         if (osso_context == NULL) {
860                 return OSSO_ERROR;
861         }
862         static_hildonprogram = HILDON_PROGRAM(hildon_program_get_instance());
863         static_osso_context = osso_context;
864 #endif  
865         gdk_rgb_init();
866         gtk_widget_set_default_colormap(gdk_rgb_get_colormap());
867         gtk_widget_set_default_visual(gdk_rgb_get_visual());
868
869         if (!g_thread_supported()) {
870                 g_error(_("g_thread is not supported by glib.\n"));
871         }
872
873         /* check that we're not on a too recent/old gtk+ */
874 #if GTK_CHECK_VERSION(2, 9, 0)
875         if (gtk_check_version(2, 9, 0) != NULL) {
876                 alertpanel_error(_("Claws Mail has been compiled with "
877                                    "a more recent GTK+ library than is "
878                                    "currently available. This will cause "
879                                    "crashes. You need to upgrade GTK+ or "
880                                    "recompile Claws Mail."));
881 #ifdef G_OS_WIN32
882                 win32_close_log();
883 #endif
884                 exit(1);
885         }
886 #else
887         if (gtk_check_version(2, 9, 0) == NULL) {
888                 alertpanel_error(_("Claws Mail has been compiled with "
889                                    "an older GTK+ library than is "
890                                    "currently available. This will cause "
891                                    "crashes. You need to recompile "
892                                    "Claws Mail."));
893 #ifdef G_OS_WIN32
894                 win32_close_log();
895 #endif
896                 exit(1);
897         }
898 #endif  
899         /* parse gtkrc files */
900         userrc = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".gtkrc-2.0",
901                              NULL);
902         gtk_rc_parse(userrc);
903         g_free(userrc);
904         userrc = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".gtk",
905                              G_DIR_SEPARATOR_S, "gtkrc-2.0", NULL);
906         gtk_rc_parse(userrc);
907         g_free(userrc);
908
909 #ifdef G_OS_WIN32
910         CHDIR_EXEC_CODE_RETURN_VAL_IF_FAIL(get_home_dir(), 1, win32_close_log(););
911 #else
912         CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
913 #endif
914         
915         /* no config dir exists. See if we can migrate an old config. */
916         if (!is_dir_exist(RC_DIR)) {
917                 prefs_destroy_cache();
918                 gboolean r = FALSE;
919                 
920                 /* if one of the old dirs exist, we'll ask if the user 
921                  * want to migrates, and r will be TRUE if he said yes
922                  * and migration succeeded, and FALSE otherwise.
923                  */
924                 if (is_dir_exist(OLD_GTK2_RC_DIR)) {
925                         r = migrate_old_config(OLD_GTK2_RC_DIR, RC_DIR, _("Sylpheed-Claws 2.6.0 (or older)"));
926                         asked_for_migration = TRUE;
927                 } else if (is_dir_exist(OLDER_GTK2_RC_DIR)) {
928                         r = migrate_old_config(OLDER_GTK2_RC_DIR, RC_DIR, _("Sylpheed-Claws 1.9.15 (or older)"));
929                         asked_for_migration = TRUE;
930                 } else if (is_dir_exist(OLD_GTK1_RC_DIR)) {
931                         r = migrate_old_config(OLD_GTK1_RC_DIR, RC_DIR, _("Sylpheed-Claws 1.0.5 (or older)"));
932                         asked_for_migration = TRUE;
933                 } else if (is_dir_exist(SYLPHEED_RC_DIR)) {
934                         r = migrate_old_config(SYLPHEED_RC_DIR, RC_DIR, "Sylpheed");
935                         asked_for_migration = TRUE;
936                 }
937                 
938                 /* If migration failed or the user didn't want to do it,
939                  * we create a new one (and we'll hit wizard later). 
940                  */
941                 if (r == FALSE && !is_dir_exist(RC_DIR) && make_dir(RC_DIR) < 0) {
942 #ifdef G_OS_WIN32
943                         win32_close_log();
944 #endif
945                         exit(1);
946         }
947         }
948         
949
950         if (!is_file_exist(RC_DIR G_DIR_SEPARATOR_S COMMON_RC) &&
951             is_file_exist(RC_DIR G_DIR_SEPARATOR_S OLD_COMMON_RC)) {
952                 /* post 2.6 name change */
953                 migrate_common_rc(RC_DIR G_DIR_SEPARATOR_S OLD_COMMON_RC,
954                           RC_DIR G_DIR_SEPARATOR_S COMMON_RC);
955         }
956
957         if (!cmd.exit)
958                 plugin_load_all("Common");
959
960         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, "gtkrc-2.0", NULL);
961         gtk_rc_parse(userrc);
962         g_free(userrc);
963
964         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
965         gtk_accel_map_load (userrc);
966         g_free(userrc);
967
968 #ifdef G_OS_WIN32
969         CHDIR_EXEC_CODE_RETURN_VAL_IF_FAIL(get_rc_dir(), 1, win32_close_log(););
970 #else
971         CHDIR_RETURN_VAL_IF_FAIL(get_rc_dir(), 1);
972 #endif
973
974         MAKE_DIR_IF_NOT_EXIST(get_mail_base_dir());
975         MAKE_DIR_IF_NOT_EXIST(get_imap_cache_dir());
976         MAKE_DIR_IF_NOT_EXIST(get_news_cache_dir());
977         MAKE_DIR_IF_NOT_EXIST(get_mime_tmp_dir());
978         MAKE_DIR_IF_NOT_EXIST(get_tmp_dir());
979         MAKE_DIR_IF_NOT_EXIST(UIDL_DIR);
980
981         crash_file_present = is_file_exist(get_crashfile_name());
982         /* remove temporary files */
983         remove_all_files(get_tmp_dir());
984         remove_all_files(get_mime_tmp_dir());
985
986         if (!cmd.crash && crash_file_present)
987                 claws_crashed_bool = TRUE;
988
989         if (is_file_exist("claws.log")) {
990                 if (rename_force("claws.log", "claws.log.bak") < 0)
991                         FILE_OP_ERROR("claws.log", "rename");
992         }
993         set_log_file(LOG_PROTOCOL, "claws.log");
994
995         if (is_file_exist("filtering.log")) {
996                 if (rename_force("filtering.log", "filtering.log.bak") < 0)
997                         FILE_OP_ERROR("filtering.log", "rename");
998         }
999         set_log_file(LOG_DEBUG_FILTERING, "filtering.log");
1000
1001 #ifdef G_OS_WIN32
1002         CHDIR_EXEC_CODE_RETURN_VAL_IF_FAIL(get_home_dir(), 1, win32_close_log(););
1003 #else
1004         CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
1005 #endif
1006
1007         folder_system_init();
1008         prefs_common_read_config();
1009
1010         prefs_themes_init();
1011         prefs_fonts_init();
1012         prefs_ext_prog_init();
1013         prefs_wrapping_init();
1014         prefs_compose_writing_init();
1015         prefs_msg_colors_init();
1016         image_viewer_init();
1017         prefs_image_viewer_init();
1018         prefs_quote_init();
1019         prefs_summaries_init();
1020         prefs_message_init();
1021         prefs_other_init();
1022         prefs_logging_init();
1023         prefs_receive_init();
1024         prefs_send_init();
1025         tags_read_tags();
1026 #ifdef USE_ASPELL
1027         gtkaspell_checkers_init();
1028         prefs_spelling_init();
1029 #endif
1030
1031         sock_set_io_timeout(prefs_common.io_timeout_secs);
1032         prefs_actions_read_config();
1033         prefs_display_header_read_config();
1034         /* prefs_filtering_read_config(); */
1035         addressbook_read_file();
1036         renderer_read_config();
1037
1038         gtkut_widget_init();
1039         stock_pixbuf_gdk(NULL, STOCK_PIXMAP_CLAWS_MAIL_ICON, &icon);
1040         gtk_window_set_default_icon(icon);
1041
1042         folderview_initialize();
1043
1044         mh_gtk_init();
1045         imap_gtk_init();
1046         news_gtk_init();
1047
1048         mainwin = main_window_create();
1049 #ifdef MAEMO
1050         AppData *appdata;
1051         appdata = g_new0(AppData, 1);
1052         appdata->program = static_hildonprogram;
1053         appdata->window = mainwin->window;
1054         appdata->osso_context = osso_context;
1055         result = osso_rpc_set_cb_f(appdata->osso_context, 
1056                 OSSO_SERVICE, 
1057                 OSSO_OBJECT, 
1058                 OSSO_IFACE,
1059                 dbus_req_handler, appdata);
1060         if (result != OSSO_OK) {
1061                 return OSSO_ERROR;
1062         }
1063
1064         /* Add handler for Exit D-BUS messages */
1065         result = osso_application_set_exit_cb(appdata->osso_context,
1066                                                 exit_event_handler,
1067                                                 (gpointer) appdata);
1068         if (result != OSSO_OK) {
1069                 return OSSO_ERROR;
1070         }
1071 #endif
1072         manage_window_focus_in(mainwin->window, NULL, NULL);
1073         folderview = mainwin->folderview;
1074
1075         gtk_clist_freeze(GTK_CLIST(mainwin->folderview->ctree));
1076         folder_item_update_freeze();
1077
1078         /* register the callback of unix domain socket input */
1079 #ifdef G_OS_UNIX
1080         lock_socket_tag = gdk_input_add(lock_socket,
1081                                         GDK_INPUT_READ | GDK_INPUT_EXCEPTION,
1082                                         lock_socket_input_cb,
1083                                         mainwin);
1084 #endif
1085
1086         prefs_account_init();
1087         account_read_config_all();
1088
1089         /* If we can't read a folder list or don't have accounts,
1090          * it means the configuration's not done. Either this is
1091          * a brand new install, either a failed/refused migration.
1092          * So we'll start the wizard.
1093          */
1094         if (folder_read_list() < 0) {
1095                 prefs_destroy_cache();
1096                 
1097                 /* if run_wizard returns FALSE it's because it's
1098                  * been cancelled. We can't do much but exit.
1099                  * however, if the user was asked for a migration,
1100                  * we remove the newly created directory so that
1101                  * he's asked again for migration on next launch.*/
1102                 if (!run_wizard(mainwin, TRUE)) {
1103                         if (asked_for_migration)
1104                                 remove_dir_recursive(RC_DIR);
1105 #ifdef G_OS_WIN32
1106                         win32_close_log();
1107 #endif
1108                         exit(1);
1109                 }
1110                 main_window_reflect_prefs_all_now();
1111                 folder_write_list();
1112         }
1113
1114         if (!account_get_list()) {
1115                 prefs_destroy_cache();
1116                 if (!run_wizard(mainwin, FALSE)) {
1117                         if (asked_for_migration)
1118                                 remove_dir_recursive(RC_DIR);
1119 #ifdef G_OS_WIN32
1120                         win32_close_log();
1121 #endif
1122                         exit(1);
1123                 }
1124                 if(!account_get_list()) {
1125                         exit_claws(mainwin);
1126 #ifdef G_OS_WIN32
1127                         win32_close_log();
1128 #endif
1129                         exit(1);
1130                 }
1131         }
1132
1133         
1134         toolbar_main_set_sensitive(mainwin);
1135         main_window_set_menu_sensitive(mainwin);
1136
1137         /* if crashed, show window early so that the user
1138          * sees what's happening */
1139         if (claws_crashed())
1140                 main_window_popup(mainwin);
1141
1142 #ifdef HAVE_LIBETPAN
1143         imap_main_init(prefs_common.skip_ssl_cert_check);
1144         imap_main_set_timeout(prefs_common.io_timeout_secs);
1145 #endif  
1146         account_set_missing_folder();
1147         folder_set_missing_folders();
1148         folderview_set(folderview);
1149
1150         prefs_matcher_read_config();
1151
1152         /* make one all-folder processing before using claws */
1153         main_window_cursor_wait(mainwin);
1154         folder_func_to_all_folders(initial_processing, (gpointer *)mainwin);
1155
1156         /* if claws crashed, rebuild caches */
1157         if (claws_crashed()) {
1158                 GTK_EVENTS_FLUSH();
1159                 debug_print("Claws Mail crashed, checking for new messages in local folders\n");
1160                 folder_item_update_thaw();
1161                 folderview_check_new(NULL);
1162                 folder_clean_cache_memory_force();
1163                 folder_item_update_freeze();
1164         }
1165         /* make the crash-indicator file */
1166         str_write_to_file("foo", get_crashfile_name());
1167
1168         inc_autocheck_timer_init(mainwin);
1169
1170         /* ignore SIGPIPE signal for preventing sudden death of program */
1171 #ifdef G_OS_UNIX
1172         signal(SIGPIPE, SIG_IGN);
1173 #endif
1174         if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
1175                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
1176         }
1177         if (cmd.online_mode == ONLINE_MODE_ONLINE) {
1178                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
1179         }
1180
1181         if (cmd.status_folders) {
1182                 g_ptr_array_free(cmd.status_folders, TRUE);
1183                 cmd.status_folders = NULL;
1184         }
1185         if (cmd.status_full_folders) {
1186                 g_ptr_array_free(cmd.status_full_folders, TRUE);
1187                 cmd.status_full_folders = NULL;
1188         }
1189
1190         claws_register_idle_function(claws_gtk_idle);
1191
1192         prefs_toolbar_init();
1193
1194         num_folder_class = g_list_length(folder_get_list());
1195
1196         plugin_load_all("GTK2");
1197
1198         if (g_list_length(folder_get_list()) != num_folder_class) {
1199                 debug_print("new folders loaded, reloading processing rules\n");
1200                 prefs_matcher_read_config();
1201         }
1202         
1203         if (plugin_get_unloaded_list() != NULL) {
1204                 main_window_cursor_normal(mainwin);
1205                 alertpanel_warning(_("Some plugin(s) failed to load. "
1206                                      "Check the Plugins configuration "
1207                                      "for more information."));
1208                 main_window_cursor_wait(mainwin);
1209         }
1210
1211         plugin_load_standard_plugins ();
1212       
1213         /* if not crashed, show window now */
1214         if (!claws_crashed()) {
1215                 /* apart if something told not to show */
1216                 if (show_at_startup)
1217                         main_window_popup(mainwin);
1218         }
1219         
1220         if (!folder_have_mailbox()) {
1221                 prefs_destroy_cache();
1222                 main_window_cursor_normal(mainwin);
1223                 if (folder_get_list() != NULL) {
1224                         alertpanel_error(_("Claws Mail has detected a configured "
1225                                    "mailbox, but it is incomplete. It is "
1226                                    "possibly due to a failing IMAP account. Use "
1227                                    "\"Rebuild folder tree\" on the mailbox parent "
1228                                    "folder's context menu to try to fix it."));
1229                 } else {
1230                         alertpanel_error(_("Claws Mail has detected a configured "
1231                                    "mailbox, but could not load it. It is "
1232                                    "probably provided by an out-of-date "
1233                                    "external plugin. Please reinstall the "
1234                                    "plugin and try again."));
1235                         exit_claws(mainwin);
1236 #ifdef G_OS_WIN32
1237                         win32_close_log();
1238 #endif
1239                         exit(1);
1240                 }
1241         }
1242         
1243         static_mainwindow = mainwin;
1244
1245 #ifdef MAEMO
1246         if (prefs_common.data_root != NULL && *prefs_common.data_root != '\0') {
1247                 GnomeVFSVolume *vol = NULL;
1248                 gchar *uri, *mount_path;
1249
1250                 volmon = gnome_vfs_get_volume_monitor();
1251                 vol = gnome_vfs_volume_monitor_get_volume_for_path(volmon, prefs_common.data_root);
1252
1253                 uri = gnome_vfs_volume_get_activation_uri (vol);
1254                 mount_path = uri?gnome_vfs_get_local_path_from_uri (uri):NULL;
1255                 g_free(uri);
1256
1257                 if (vol == NULL || !gnome_vfs_volume_is_mounted(vol) 
1258                     || strcmp(mount_path, prefs_common.data_root)) {
1259                         alertpanel_error(_("Claws Mail can not start without its data volume (%s)."), 
1260                                 prefs_common.data_root);
1261                         g_free(mount_path);
1262                         gnome_vfs_volume_unref(vol);
1263                         exit_claws(mainwin);
1264                         exit(1);
1265                 }
1266                 g_free(mount_path);
1267                 gnome_vfs_volume_unref(vol);
1268                 g_signal_connect(G_OBJECT(volmon), 
1269                                 "volume-mounted", G_CALLBACK(main_vol_mount_cb), mainwin);
1270                 g_signal_connect(G_OBJECT(volmon), 
1271                                 "volume-unmounted", G_CALLBACK(main_vol_unmount_cb), mainwin);
1272         }
1273 #endif
1274
1275 #ifdef HAVE_STARTUP_NOTIFICATION
1276         startup_notification_complete(FALSE);
1277 #endif
1278 #ifdef HAVE_LIBSM
1279         sc_session_manager_connect(mainwin);
1280 #endif
1281         folder_item_update_thaw();
1282         gtk_clist_thaw(GTK_CLIST(mainwin->folderview->ctree));
1283         main_window_cursor_normal(mainwin);
1284
1285         if (!cmd.target && prefs_common.goto_last_folder_on_startup &&
1286             folder_find_item_from_identifier(prefs_common.last_opened_folder) != NULL &&
1287             !claws_crashed()) {
1288                 cmd.target = prefs_common.last_opened_folder;
1289         }
1290
1291         if (cmd.receive_all && !cmd.target) {
1292                 start_done = FALSE;
1293                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(FALSE));
1294         } else if (prefs_common.chk_on_startup && !cmd.target) {
1295                 start_done = FALSE;
1296                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(TRUE));
1297         } else if (cmd.receive && !cmd.target) {
1298                 start_done = FALSE;
1299                 g_timeout_add(1000, defer_check, NULL);
1300         } else {
1301                 gtk_widget_grab_focus(folderview->ctree);
1302         }
1303
1304         if (cmd.compose) {
1305                 open_compose_new(cmd.compose_mailto, cmd.attach_files);
1306         }
1307         if (cmd.attach_files) {
1308                 ptr_array_free_strings(cmd.attach_files);
1309                 g_ptr_array_free(cmd.attach_files, TRUE);
1310                 cmd.attach_files = NULL;
1311         }
1312         if (cmd.subscribe) {
1313                 folder_subscribe(cmd.subscribe_uri);
1314         }
1315
1316         if (cmd.send) {
1317                 send_queue();
1318         }
1319         
1320         if (cmd.target) {
1321                 start_done = FALSE;
1322                 g_timeout_add(500, defer_jump, (gpointer)cmd.target);
1323         }
1324
1325         prefs_destroy_cache();
1326         
1327         compose_reopen_exit_drafts();
1328
1329         if (start_done) {
1330                 sc_starting = FALSE;
1331                 main_window_set_menu_sensitive(mainwin);
1332                 toolbar_main_set_sensitive(mainwin);
1333         }
1334         END_TIMING();
1335
1336         gtk_main();
1337
1338 #ifdef MAEMO
1339         osso_deinitialize(osso_context);
1340 #endif
1341 #ifdef G_OS_WIN32
1342         win32_close_log();
1343 #endif
1344         exit_claws(mainwin);
1345
1346         return 0;
1347 }
1348
1349 static void save_all_caches(FolderItem *item, gpointer data)
1350 {
1351         if (!item->cache) {
1352                 return;
1353         }
1354
1355         if (item->opened) {
1356                 folder_item_close(item);
1357         }
1358
1359         folder_item_free_cache(item, TRUE);
1360 }
1361
1362 static void exit_claws(MainWindow *mainwin)
1363 {
1364         gchar *filename;
1365
1366         sc_exiting = TRUE;
1367
1368         debug_print("shutting down\n");
1369         inc_autocheck_timer_remove();
1370
1371         if (prefs_common.clean_on_exit && !emergency_exit) {
1372                 main_window_empty_trash(mainwin, prefs_common.ask_on_clean);
1373         }
1374
1375         /* save prefs for opened folder */
1376         if(mainwin->folderview->opened) {
1377                 FolderItem *item;
1378
1379                 item = gtk_ctree_node_get_row_data(GTK_CTREE(mainwin->folderview->ctree), mainwin->folderview->opened);
1380                 summary_save_prefs_to_folderitem(mainwin->folderview->summaryview, item);
1381                 prefs_common.last_opened_folder = folder_item_get_identifier(item);
1382         }
1383
1384         /* save all state before exiting */
1385         folder_func_to_all_folders(save_all_caches, NULL);
1386         folder_write_list();
1387
1388         main_window_get_size(mainwin);
1389         main_window_get_position(mainwin);
1390
1391         prefs_common_write_config();
1392         account_write_config_all();
1393         addressbook_export_to_file();
1394
1395         filename = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
1396         gtk_accel_map_save(filename);
1397         g_free(filename);
1398
1399         /* delete temporary files */
1400         remove_all_files(get_tmp_dir());
1401         remove_all_files(get_mime_tmp_dir());
1402
1403         close_log_file(LOG_PROTOCOL);
1404         close_log_file(LOG_DEBUG_FILTERING);
1405
1406 #ifdef HAVE_LIBETPAN
1407         imap_main_done();
1408 #endif
1409         /* delete crashfile */
1410         if (!cmd.crash)
1411                 g_unlink(get_crashfile_name());
1412
1413         lock_socket_remove();
1414
1415 #ifdef HAVE_LIBSM
1416         if (mainwin->smc_conn)
1417                 SmcCloseConnection ((SmcConn)mainwin->smc_conn, 0, NULL);
1418         mainwin->smc_conn = NULL;
1419 #endif
1420
1421         main_window_destroy_all();
1422         
1423         plugin_unload_all("GTK2");
1424
1425         prefs_toolbar_done();
1426
1427         addressbook_destroy();
1428
1429         prefs_themes_done();
1430         prefs_fonts_done();
1431         prefs_ext_prog_done();
1432         prefs_wrapping_done();
1433         prefs_compose_writing_done();
1434         prefs_msg_colors_done();
1435         prefs_image_viewer_done();
1436         image_viewer_done();
1437         prefs_quote_done();
1438         prefs_summaries_done();
1439         prefs_message_done();
1440         prefs_other_done();
1441         prefs_receive_done();
1442         prefs_send_done();
1443         tags_write_tags();
1444 #ifdef USE_ASPELL       
1445         prefs_spelling_done();
1446         gtkaspell_checkers_quit();
1447 #endif
1448         plugin_unload_all("Common");
1449         claws_done();
1450 }
1451
1452 static void parse_cmd_opt(int argc, char *argv[])
1453 {
1454         gint i;
1455
1456         for (i = 1; i < argc; i++) {
1457                 if (!strncmp(argv[i], "--receive-all", 13)) {
1458                         cmd.receive_all = TRUE;
1459                 } else if (!strncmp(argv[i], "--receive", 9)) {
1460                         cmd.receive = TRUE;
1461                 } else if (!strncmp(argv[i], "--compose", 9)) {
1462                         const gchar *p = argv[i + 1];
1463
1464                         cmd.compose = TRUE;
1465                         cmd.compose_mailto = NULL;
1466                         if (p && *p != '\0' && *p != '-') {
1467                                 if (!strncmp(p, "mailto:", 7)) {
1468                                         cmd.compose_mailto = p + 7;
1469                                 } else {
1470                                         cmd.compose_mailto = p;
1471                                 }
1472                                 i++;
1473                         }
1474                 } else if (!strncmp(argv[i], "--subscribe", 11)) {
1475                         const gchar *p = argv[i + 1];
1476                         if (p && *p != '\0' && *p != '-') {
1477                                 cmd.subscribe = TRUE;
1478                                 cmd.subscribe_uri = p;
1479                         }
1480                 } else if (!strncmp(argv[i], "--attach", 8)) {
1481                         const gchar *p = argv[i + 1];
1482                         gchar *file = NULL;
1483
1484                         while (p && *p != '\0' && *p != '-') {
1485                                 if (!cmd.attach_files) {
1486                                         cmd.attach_files = g_ptr_array_new();
1487                                 }
1488                                 if ((file = g_filename_from_uri(p, NULL, NULL)) != NULL) {
1489                                         if (!is_file_exist(file)) {
1490                                                 g_free(file);
1491                                                 file = NULL;
1492                                         }
1493                                 }
1494                                 if (file == NULL && *p != G_DIR_SEPARATOR) {
1495                                         file = g_strconcat(claws_get_startup_dir(),
1496                                                            G_DIR_SEPARATOR_S,
1497                                                            p, NULL);
1498                                 } else if (file == NULL) {
1499                                         file = g_strdup(p);
1500                                 }
1501                                 g_ptr_array_add(cmd.attach_files, file);
1502                                 i++;
1503                                 p = argv[i + 1];
1504                         }
1505                 } else if (!strncmp(argv[i], "--send", 6)) {
1506                         cmd.send = TRUE;
1507                 } else if (!strncmp(argv[i], "--version", 9) ||
1508                            !strncmp(argv[i], "-v", 2)) {
1509                         g_print("Claws Mail version " VERSION "\n");
1510                         exit(0);
1511                 } else if (!strncmp(argv[i], "--status-full", 13)) {
1512                         const gchar *p = argv[i + 1];
1513  
1514                         cmd.status_full = TRUE;
1515                         while (p && *p != '\0' && *p != '-') {
1516                                 if (!cmd.status_full_folders) {
1517                                         cmd.status_full_folders =
1518                                                 g_ptr_array_new();
1519                                 }
1520                                 g_ptr_array_add(cmd.status_full_folders,
1521                                                 g_strdup(p));
1522                                 i++;
1523                                 p = argv[i + 1];
1524                         }
1525                 } else if (!strncmp(argv[i], "--status", 8)) {
1526                         const gchar *p = argv[i + 1];
1527  
1528                         cmd.status = TRUE;
1529                         while (p && *p != '\0' && *p != '-') {
1530                                 if (!cmd.status_folders)
1531                                         cmd.status_folders = g_ptr_array_new();
1532                                 g_ptr_array_add(cmd.status_folders,
1533                                                 g_strdup(p));
1534                                 i++;
1535                                 p = argv[i + 1];
1536                         }
1537                 } else if (!strncmp(argv[i], "--online", 8)) {
1538                         cmd.online_mode = ONLINE_MODE_ONLINE;
1539                 } else if (!strncmp(argv[i], "--offline", 9)) {
1540                         cmd.online_mode = ONLINE_MODE_OFFLINE;
1541                 } else if (!strncmp(argv[i], "--help", 6) ||
1542                            !strncmp(argv[i], "-h", 2)) {
1543                         gchar *base = g_path_get_basename(argv[0]);
1544                         g_print(_("Usage: %s [OPTION]...\n"), base);
1545
1546                         g_print("%s\n", _("  --compose [address]    open composition window"));
1547                         g_print("%s\n", _("  --subscribe [uri]      subscribe to the given URI if possible"));
1548                         g_print("%s\n", _("  --attach file1 [file2]...\n"
1549                                   "                         open composition window with specified files\n"
1550                                   "                         attached"));
1551                         g_print("%s\n", _("  --receive              receive new messages"));
1552                         g_print("%s\n", _("  --receive-all          receive new messages of all accounts"));
1553                         g_print("%s\n", _("  --send                 send all queued messages"));
1554                         g_print("%s\n", _("  --status [folder]...   show the total number of messages"));
1555                         g_print("%s\n", _("  --status-full [folder]...\n"
1556                                           "                         show the status of each folder"));
1557                         g_print("%s\n", _("  --select folder[/msg]  jumps to the specified folder/message\n" 
1558                                           "                         folder is a folder id like 'folder/sub_folder'"));
1559                         g_print("%s\n", _("  --online               switch to online mode"));
1560                         g_print("%s\n", _("  --offline              switch to offline mode"));
1561                         g_print("%s\n", _("  --exit --quit -q       exit Claws Mail"));
1562                         g_print("%s\n", _("  --debug                debug mode"));
1563                         g_print("%s\n", _("  --help -h              display this help and exit"));
1564                         g_print("%s\n", _("  --version -v           output version information and exit"));
1565                         g_print("%s\n", _("  --config-dir           output configuration directory"));
1566                         g_print("%s\n", _("  --alternate-config-dir [dir]\n"
1567                                           "                         use specified configuration directory"));
1568
1569                         g_free(base);
1570                         exit(1);
1571                 } else if (!strncmp(argv[i], "--crash", 7)) {
1572                         cmd.crash = TRUE;
1573                         cmd.crash_params = g_strdup(argv[i + 1]);
1574                         i++;
1575                 } else if (!strncmp(argv[i], "--config-dir", sizeof "--config-dir" - 1)) {
1576                         g_print(RC_DIR "\n");
1577                         exit(0);
1578                 } else if (!strncmp(argv[i], "--alternate-config-dir", sizeof "--alternate-config-dir" - 1) && i+1 < argc) {
1579                         set_rc_dir(argv[i+1]);
1580                 } else if (!strncmp(argv[i], "--exit", 6) ||
1581                            !strncmp(argv[i], "--quit", 6) ||
1582                            !strncmp(argv[i], "-q", 2)) {
1583                         cmd.exit = TRUE;
1584                 } else if (!strncmp(argv[i], "--select", 8) && i+1 < argc) {
1585                         cmd.target = argv[i+1];
1586                 } else if (i == 1 && argc == 2) {
1587                         /* only one parameter. Do something intelligent about it */
1588                         if (strstr(argv[i], "@") && !strstr(argv[i], "://")) {
1589                                 const gchar *p = argv[i];
1590
1591                                 cmd.compose = TRUE;
1592                                 cmd.compose_mailto = NULL;
1593                                 if (p && *p != '\0' && *p != '-') {
1594                                         if (!strncmp(p, "mailto:", 7)) {
1595                                                 cmd.compose_mailto = p + 7;
1596                                         } else {
1597                                                 cmd.compose_mailto = p;
1598                                         }
1599                                 }
1600                         } else if (strstr(argv[i], "://")) {
1601                                 const gchar *p = argv[i];
1602                                 if (p && *p != '\0' && *p != '-') {
1603                                         cmd.subscribe = TRUE;
1604                                         cmd.subscribe_uri = p;
1605                                 }
1606                         } else if (!strcmp(argv[i], "--sync")) {
1607                                 /* gtk debug */
1608                         } else {
1609                                 g_print(_("Unknown option\n"));
1610                                 exit(1);
1611                         }
1612                 }
1613         }
1614
1615         if (cmd.attach_files && cmd.compose == FALSE) {
1616                 cmd.compose = TRUE;
1617                 cmd.compose_mailto = NULL;
1618         }
1619 }
1620
1621 static void initial_processing(FolderItem *item, gpointer data)
1622 {
1623         MainWindow *mainwin = (MainWindow *)data;
1624         gchar *buf;
1625
1626         g_return_if_fail(item);
1627         buf = g_strdup_printf(_("Processing (%s)..."), 
1628                               item->path 
1629                               ? item->path 
1630                               : _("top level folder"));
1631         g_free(buf);
1632
1633         
1634         if (item->prefs->enable_processing) {
1635                 folder_item_apply_processing(item);
1636         }
1637
1638         STATUSBAR_POP(mainwin);
1639 }
1640
1641 static gboolean draft_all_messages(void)
1642 {
1643         GList *compose_list = NULL;
1644         
1645         compose_clear_exit_drafts();
1646         compose_list = compose_get_compose_list();
1647         while (compose_list != NULL) {
1648                 Compose *c = (Compose*)compose_list->data;
1649                 if (!compose_draft(c, COMPOSE_DRAFT_FOR_EXIT))
1650                         return FALSE;
1651                 compose_list = compose_get_compose_list();
1652         }
1653         return TRUE;
1654 }
1655 gboolean clean_quit(gpointer data)
1656 {
1657         static gboolean firstrun = TRUE;
1658
1659         if (!firstrun) {
1660                 return FALSE;
1661         }
1662         firstrun = FALSE;
1663
1664         /*!< Good idea to have the main window stored in a 
1665          *   static variable so we can check that variable
1666          *   to see if we're really allowed to do things
1667          *   that actually the spawner is supposed to 
1668          *   do (like: sending mail, composing messages).
1669          *   Because, really, if we're the spawnee, and
1670          *   we touch GTK stuff, we're hosed. See the 
1671          *   next fixme. */
1672
1673         /* FIXME: Use something else to signal that we're
1674          * in the original spawner, and not in a spawned
1675          * child. */
1676         if (!static_mainwindow) {
1677                 return FALSE;
1678         }
1679                 
1680         draft_all_messages();
1681         emergency_exit = TRUE;
1682         exit_claws(static_mainwindow);
1683         exit(0);
1684
1685         return FALSE;
1686 }
1687
1688 void app_will_exit(GtkWidget *widget, gpointer data)
1689 {
1690         MainWindow *mainwin = data;
1691         
1692         if (sc_exiting == TRUE) {
1693                 debug_print("exit pending\n");
1694                 return;
1695         }
1696         sc_exiting = TRUE;
1697         debug_print("exiting\n");
1698         if (compose_get_compose_list()) {
1699                 if (!draft_all_messages()) {
1700                         main_window_popup(mainwin);
1701                         sc_exiting = FALSE;
1702                         return;
1703                 }
1704         }
1705
1706         if (prefs_common.warn_queued_on_exit && procmsg_have_queued_mails_fast()) {
1707                 if (alertpanel(_("Queued messages"),
1708                                _("Some unsent messages are queued. Exit now?"),
1709                                GTK_STOCK_CANCEL, GTK_STOCK_OK, NULL)
1710                     != G_ALERTALTERNATE) {
1711                         main_window_popup(mainwin);
1712                         sc_exiting = FALSE;
1713                         return;
1714                 }
1715                 manage_window_focus_in(mainwin->window, NULL, NULL);
1716         }
1717
1718         sock_cleanup();
1719 #ifdef HAVE_VALGRIND
1720         if (RUNNING_ON_VALGRIND) {
1721                 summary_clear_list(mainwin->summaryview);
1722         }
1723 #endif
1724         if (folderview_get_selected_item(mainwin->folderview))
1725                 folder_item_close(folderview_get_selected_item(mainwin->folderview));
1726         gtk_main_quit();
1727 }
1728
1729 gboolean claws_is_exiting(void)
1730 {
1731         return sc_exiting;
1732 }
1733
1734 gboolean claws_is_starting(void)
1735 {
1736         return sc_starting;
1737 }
1738
1739 /*
1740  * CLAWS: want this public so crash dialog can delete the
1741  * lock file too
1742  */
1743 gchar *claws_get_socket_name(void)
1744 {
1745         static gchar *filename = NULL;
1746         const gchar *socket_dir = NULL;
1747         
1748         if (rc_dir_is_alt())
1749                 socket_dir = get_rc_dir();
1750         else
1751                 socket_dir = g_get_tmp_dir();
1752         if (filename == NULL) {
1753                 filename = g_strdup_printf("%s%cclaws-mail-%d",
1754                                            socket_dir, G_DIR_SEPARATOR,
1755 #if HAVE_GETUID
1756                                            getuid());
1757 #else
1758                                            0);                                          
1759 #endif
1760         }
1761
1762         return filename;
1763 }
1764
1765 static gchar *get_crashfile_name(void)
1766 {
1767         static gchar *filename = NULL;
1768
1769         if (filename == NULL) {
1770                 filename = g_strdup_printf("%s%cclaws-crashed",
1771                                            get_tmp_dir(), G_DIR_SEPARATOR);
1772         }
1773
1774         return filename;
1775 }
1776
1777 static gint prohibit_duplicate_launch(void)
1778 {
1779         gint uxsock;
1780         gchar *path;
1781
1782         path = claws_get_socket_name();
1783         uxsock = fd_connect_unix(path);
1784         
1785         if (x_display == NULL)
1786                 x_display = g_strdup(g_getenv("DISPLAY"));
1787
1788         if (uxsock < 0) {
1789                 g_unlink(path);
1790                 return fd_open_unix(path);
1791         }
1792
1793         /* remote command mode */
1794
1795         debug_print("another Claws Mail instance is already running.\n");
1796
1797         if (cmd.receive_all) {
1798                 fd_write_all(uxsock, "receive_all\n", 12);
1799         } else if (cmd.receive) {
1800                 fd_write_all(uxsock, "receive\n", 8);
1801         } else if (cmd.compose && cmd.attach_files) {
1802                 gchar *str, *compose_str;
1803                 gint i;
1804
1805                 if (cmd.compose_mailto) {
1806                         compose_str = g_strdup_printf("compose_attach %s\n",
1807                                                       cmd.compose_mailto);
1808                 } else {
1809                         compose_str = g_strdup("compose_attach\n");
1810                 }
1811
1812                 fd_write_all(uxsock, compose_str, strlen(compose_str));
1813                 g_free(compose_str);
1814
1815                 for (i = 0; i < cmd.attach_files->len; i++) {
1816                         str = g_ptr_array_index(cmd.attach_files, i);
1817                         fd_write_all(uxsock, str, strlen(str));
1818                         fd_write_all(uxsock, "\n", 1);
1819                 }
1820
1821                 fd_write_all(uxsock, ".\n", 2);
1822         } else if (cmd.compose) {
1823                 gchar *compose_str;
1824
1825                 if (cmd.compose_mailto) {
1826                         compose_str = g_strdup_printf
1827                                 ("compose %s\n", cmd.compose_mailto);
1828                 } else {
1829                         compose_str = g_strdup("compose\n");
1830                 }
1831
1832                 fd_write_all(uxsock, compose_str, strlen(compose_str));
1833                 g_free(compose_str);
1834         } else if (cmd.subscribe) {
1835                 gchar *str = g_strdup_printf("subscribe %s\n", cmd.subscribe_uri);
1836                 fd_write_all(uxsock, str, strlen(str));
1837                 g_free(str);
1838         } else if (cmd.send) {
1839                 fd_write_all(uxsock, "send\n", 5);
1840         } else if (cmd.online_mode == ONLINE_MODE_ONLINE) {
1841                 fd_write(uxsock, "online\n", 6);
1842         } else if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
1843                 fd_write(uxsock, "offline\n", 7);
1844         } else if (cmd.status || cmd.status_full) {
1845                 gchar buf[BUFFSIZE];
1846                 gint i;
1847                 const gchar *command;
1848                 GPtrArray *folders;
1849                 gchar *folder;
1850  
1851                 command = cmd.status_full ? "status-full\n" : "status\n";
1852                 folders = cmd.status_full ? cmd.status_full_folders :
1853                         cmd.status_folders;
1854  
1855                 fd_write_all(uxsock, command, strlen(command));
1856                 for (i = 0; folders && i < folders->len; ++i) {
1857                         folder = g_ptr_array_index(folders, i);
1858                         fd_write_all(uxsock, folder, strlen(folder));
1859                         fd_write_all(uxsock, "\n", 1);
1860                 }
1861                 fd_write_all(uxsock, ".\n", 2);
1862                 for (;;) {
1863                         fd_gets(uxsock, buf, sizeof(buf));
1864                         if (!strncmp(buf, ".\n", 2)) break;
1865                         fputs(buf, stdout);
1866                 }
1867         } else if (cmd.exit) {
1868                 fd_write_all(uxsock, "exit\n", 5);
1869         } else if (cmd.target) {
1870                 gchar *str = g_strdup_printf("select %s\n", cmd.target);
1871                 fd_write_all(uxsock, str, strlen(str));
1872                 g_free(str);
1873         } else {
1874                 gchar buf[BUFSIZ];
1875                 fd_write_all(uxsock, "get_display\n", 12);
1876                 memset(buf, 0, sizeof(buf));
1877                 fd_gets(uxsock, buf, sizeof(buf));
1878                 if (strcmp2(buf, x_display)) {
1879                         g_print("Claws Mail is already running on display %s.\n",
1880                                 buf);
1881                 } else {
1882                         fd_close(uxsock);
1883                         uxsock = fd_connect_unix(path);
1884                         fd_write_all(uxsock, "popup\n", 6);
1885                 }
1886         }
1887
1888         fd_close(uxsock);
1889         return -1;
1890 }
1891
1892 static gint lock_socket_remove(void)
1893 {
1894 #ifdef G_OS_UNIX
1895         gchar *filename;
1896
1897         if (lock_socket < 0) {
1898                 return -1;
1899         }
1900
1901         if (lock_socket_tag > 0) {
1902                 gdk_input_remove(lock_socket_tag);
1903         }
1904         fd_close(lock_socket);
1905         filename = claws_get_socket_name();
1906         g_unlink(filename);
1907 #endif
1908
1909         return 0;
1910 }
1911
1912 static GPtrArray *get_folder_item_list(gint sock)
1913 {
1914         gchar buf[BUFFSIZE];
1915         FolderItem *item;
1916         GPtrArray *folders = NULL;
1917
1918         for (;;) {
1919                 fd_gets(sock, buf, sizeof(buf));
1920                 if (!strncmp(buf, ".\n", 2)) {
1921                         break;
1922                 }
1923                 strretchomp(buf);
1924                 if (!folders) {
1925                         folders = g_ptr_array_new();
1926                 }
1927                 item = folder_find_item_from_identifier(buf);
1928                 if (item) {
1929                         g_ptr_array_add(folders, item);
1930                 } else {
1931                         g_warning("no such folder: %s\n", buf);
1932                 }
1933         }
1934
1935         return folders;
1936 }
1937
1938 static void lock_socket_input_cb(gpointer data,
1939                                  gint source,
1940                                  GdkInputCondition condition)
1941 {
1942         MainWindow *mainwin = (MainWindow *)data;
1943         gint sock;
1944         gchar buf[BUFFSIZE];
1945
1946         sock = fd_accept(source);
1947         fd_gets(sock, buf, sizeof(buf));
1948
1949         if (!strncmp(buf, "popup", 5)) {
1950                 main_window_popup(mainwin);
1951         } else if (!strncmp(buf, "get_display", 11)) {
1952                 fd_write_all(sock, x_display, strlen(x_display));
1953         } else if (!strncmp(buf, "receive_all", 11)) {
1954                 inc_all_account_mail(mainwin, FALSE,
1955                                      prefs_common.newmail_notify_manu);
1956         } else if (!strncmp(buf, "receive", 7)) {
1957                 inc_mail(mainwin, prefs_common.newmail_notify_manu);
1958         } else if (!strncmp(buf, "compose_attach", 14)) {
1959                 GPtrArray *files;
1960                 gchar *mailto;
1961
1962                 mailto = g_strdup(buf + strlen("compose_attach") + 1);
1963                 files = g_ptr_array_new();
1964                 while (fd_gets(sock, buf, sizeof(buf)) > 0) {
1965                         if (buf[0] == '.' && buf[1] == '\n') {
1966                                 break;
1967                         }
1968                         strretchomp(buf);
1969                         g_ptr_array_add(files, g_strdup(buf));
1970                 }
1971                 open_compose_new(mailto, files);
1972                 ptr_array_free_strings(files);
1973                 g_ptr_array_free(files, TRUE);
1974                 g_free(mailto);
1975         } else if (!strncmp(buf, "compose", 7)) {
1976                 open_compose_new(buf + strlen("compose") + 1, NULL);
1977         } else if (!strncmp(buf, "subscribe", 9)) {
1978                 main_window_popup(mainwin);
1979                 folder_subscribe(buf + strlen("subscribe") + 1);
1980         } else if (!strncmp(buf, "send", 4)) {
1981                 send_queue();
1982         } else if (!strncmp(buf, "online", 6)) {
1983                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
1984         } else if (!strncmp(buf, "offline", 7)) {
1985                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
1986         } else if (!strncmp(buf, "status-full", 11) ||
1987                    !strncmp(buf, "status", 6)) {
1988                 gchar *status;
1989                 GPtrArray *folders;
1990  
1991                 folders = get_folder_item_list(sock);
1992                 status = folder_get_status
1993                         (folders, !strncmp(buf, "status-full", 11));
1994                 fd_write_all(sock, status, strlen(status));
1995                 fd_write_all(sock, ".\n", 2);
1996                 g_free(status);
1997                 if (folders) g_ptr_array_free(folders, TRUE);
1998         } else if (!strncmp(buf, "select ", 7)) {
1999                 const gchar *target = buf+7;
2000                 mainwindow_jump_to(target, TRUE);
2001         } else if (!strncmp(buf, "exit", 4)) {
2002                 app_will_exit(NULL, mainwin);
2003         }
2004
2005         fd_close(sock);
2006 }
2007
2008 static void open_compose_new(const gchar *address, GPtrArray *attach_files)
2009 {
2010         gchar *addr = NULL;
2011
2012         if (address) {
2013                 Xstrdup_a(addr, address, return);
2014                 g_strstrip(addr);
2015         }
2016
2017         compose_new(NULL, addr, attach_files);
2018 }
2019
2020 static void send_queue(void)
2021 {
2022         GList *list;
2023         gchar *errstr = NULL;
2024         gboolean error = FALSE;
2025         for (list = folder_get_list(); list != NULL; list = list->next) {
2026                 Folder *folder = list->data;
2027
2028                 if (folder->queue) {
2029                         gint res = procmsg_send_queue
2030                                 (folder->queue, prefs_common.savemsg,
2031                                 &errstr);
2032
2033                         if (res) {
2034                                 folder_item_scan(folder->queue);
2035                         }
2036                         
2037                         if (res < 0)
2038                                 error = TRUE;
2039                 }
2040         }
2041         if (errstr) {
2042                 alertpanel_error_log(_("Some errors occurred "
2043                                 "while sending queued messages:\n%s"), errstr);
2044                 g_free(errstr);
2045         } else if (error) {
2046                 alertpanel_error_log("Some errors occurred "
2047                                 "while sending queued messages.");
2048         }
2049 }
2050
2051 static void quit_signal_handler(int sig)
2052 {
2053         debug_print("Quitting on signal %d\n", sig);
2054
2055         g_timeout_add(0, clean_quit, NULL);
2056 }
2057
2058 static void install_basic_sighandlers()
2059 {
2060 #ifndef G_OS_WIN32
2061         sigset_t    mask;
2062         struct sigaction act;
2063
2064         sigemptyset(&mask);
2065
2066 #ifdef SIGTERM
2067         sigaddset(&mask, SIGTERM);
2068 #endif
2069 #ifdef SIGINT
2070         sigaddset(&mask, SIGINT);
2071 #endif
2072 #ifdef SIGHUP
2073         sigaddset(&mask, SIGHUP);
2074 #endif
2075
2076         act.sa_handler = quit_signal_handler;
2077         act.sa_mask    = mask;
2078         act.sa_flags   = 0;
2079
2080 #ifdef SIGTERM
2081         sigaction(SIGTERM, &act, 0);
2082 #endif
2083 #ifdef SIGINT
2084         sigaction(SIGINT, &act, 0);
2085 #endif  
2086 #ifdef SIGHUP
2087         sigaction(SIGHUP, &act, 0);
2088 #endif  
2089
2090         sigprocmask(SIG_UNBLOCK, &mask, 0);
2091 #endif /* !G_OS_WIN32 */
2092 }
2093
2094 #ifdef MAEMO
2095 HildonProgram *hildon_program(void)
2096 {
2097         return static_hildonprogram;
2098 }
2099 osso_context_t *get_osso_context(void)
2100 {
2101         return static_osso_context;
2102 }
2103 #endif