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