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