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