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