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