2007-07-20 [colin] 2.10.0cvs49
[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                         g_free(mount_path);
1103                         gnome_vfs_volume_unref(vol);
1104                         exit_claws(mainwin);
1105                         exit(1);
1106                 }
1107                 g_free(mount_path);
1108                 gnome_vfs_volume_unref(vol);
1109                 g_signal_connect(G_OBJECT(volmon), 
1110                                 "volume-mounted", G_CALLBACK(main_vol_mount_cb), mainwin);
1111                 g_signal_connect(G_OBJECT(volmon), 
1112                                 "volume-unmounted", G_CALLBACK(main_vol_unmount_cb), mainwin);
1113         }
1114 #endif
1115
1116 #ifdef HAVE_STARTUP_NOTIFICATION
1117         startup_notification_complete(FALSE);
1118 #endif
1119 #ifdef HAVE_LIBSM
1120         sc_session_manager_connect(mainwin);
1121 #endif
1122         folder_item_update_thaw();
1123         gtk_clist_thaw(GTK_CLIST(mainwin->folderview->ctree));
1124         main_window_cursor_normal(mainwin);
1125
1126         if (!cmd.target && prefs_common.goto_last_folder_on_startup &&
1127             folder_find_item_from_identifier(prefs_common.last_opened_folder) != NULL &&
1128             !claws_crashed()) {
1129                 cmd.target = prefs_common.last_opened_folder;
1130         }
1131
1132         if (cmd.receive_all && !cmd.target) {
1133                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(FALSE));
1134         } else if (prefs_common.chk_on_startup && !cmd.target) {
1135                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(TRUE));
1136         } else if (cmd.receive && !cmd.target) {
1137                 g_timeout_add(1000, defer_check, NULL);
1138         } else {
1139                 gtk_widget_grab_focus(folderview->ctree);
1140         }
1141
1142         if (cmd.compose) {
1143                 open_compose_new(cmd.compose_mailto, cmd.attach_files);
1144         }
1145         if (cmd.attach_files) {
1146                 ptr_array_free_strings(cmd.attach_files);
1147                 g_ptr_array_free(cmd.attach_files, TRUE);
1148                 cmd.attach_files = NULL;
1149         }
1150         if (cmd.subscribe) {
1151                 folder_subscribe(cmd.subscribe_uri);
1152         }
1153
1154         if (cmd.send) {
1155                 send_queue();
1156         }
1157         
1158         if (cmd.target) {
1159                 g_timeout_add(500, defer_jump, (gpointer)cmd.target);
1160         }
1161
1162         prefs_destroy_cache();
1163         
1164         compose_reopen_exit_drafts();
1165
1166         sc_starting = FALSE;
1167         END_TIMING();
1168
1169         gtk_main();
1170
1171 #ifdef MAEMO
1172         osso_deinitialize(osso_context);
1173 #endif
1174         exit_claws(mainwin);
1175
1176         return 0;
1177 }
1178
1179 static void save_all_caches(FolderItem *item, gpointer data)
1180 {
1181         if (!item->cache) {
1182                 return;
1183         }
1184
1185         if (item->opened) {
1186                 folder_item_close(item);
1187         }
1188
1189         folder_item_free_cache(item, TRUE);
1190 }
1191
1192 static void exit_claws(MainWindow *mainwin)
1193 {
1194         gchar *filename;
1195
1196         sc_exiting = TRUE;
1197
1198         debug_print("shutting down\n");
1199         inc_autocheck_timer_remove();
1200
1201         if (prefs_common.clean_on_exit && !emergency_exit) {
1202                 main_window_empty_trash(mainwin, prefs_common.ask_on_clean);
1203         }
1204
1205         /* save prefs for opened folder */
1206         if(mainwin->folderview->opened) {
1207                 FolderItem *item;
1208
1209                 item = gtk_ctree_node_get_row_data(GTK_CTREE(mainwin->folderview->ctree), mainwin->folderview->opened);
1210                 summary_save_prefs_to_folderitem(mainwin->folderview->summaryview, item);
1211                 prefs_common.last_opened_folder = folder_item_get_identifier(item);
1212         }
1213
1214         /* save all state before exiting */
1215         folder_func_to_all_folders(save_all_caches, NULL);
1216         folder_write_list();
1217
1218         main_window_get_size(mainwin);
1219         main_window_get_position(mainwin);
1220
1221         prefs_common_write_config();
1222         account_write_config_all();
1223         addressbook_export_to_file();
1224
1225         filename = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
1226         gtk_accel_map_save(filename);
1227         g_free(filename);
1228
1229         /* delete temporary files */
1230         remove_all_files(get_tmp_dir());
1231         remove_all_files(get_mime_tmp_dir());
1232
1233         close_log_file(LOG_PROTOCOL);
1234         close_log_file(LOG_DEBUG_FILTERING);
1235
1236 #ifdef HAVE_LIBETPAN
1237         imap_main_done();
1238 #endif
1239         /* delete crashfile */
1240         if (!cmd.crash)
1241                 g_unlink(get_crashfile_name());
1242
1243         lock_socket_remove();
1244
1245 #ifdef HAVE_LIBSM
1246         if (mainwin->smc_conn)
1247                 SmcCloseConnection ((SmcConn)mainwin->smc_conn, 0, NULL);
1248         mainwin->smc_conn = NULL;
1249 #endif
1250
1251         main_window_destroy_all();
1252         
1253         plugin_unload_all("GTK2");
1254
1255         prefs_toolbar_done();
1256
1257         addressbook_destroy();
1258
1259         prefs_themes_done();
1260         prefs_fonts_done();
1261         prefs_ext_prog_done();
1262         prefs_wrapping_done();
1263         prefs_compose_writing_done();
1264         prefs_msg_colors_done();
1265         prefs_image_viewer_done();
1266         image_viewer_done();
1267         prefs_quote_done();
1268         prefs_summaries_done();
1269         prefs_message_done();
1270         prefs_other_done();
1271         prefs_receive_done();
1272         prefs_send_done();
1273         tags_write_tags();
1274 #ifdef USE_ASPELL       
1275         prefs_spelling_done();
1276         gtkaspell_checkers_quit();
1277 #endif
1278         plugin_unload_all("Common");
1279         claws_done();
1280 }
1281
1282 static void parse_cmd_opt(int argc, char *argv[])
1283 {
1284         gint i;
1285
1286         for (i = 1; i < argc; i++) {
1287                 if (!strncmp(argv[i], "--receive-all", 13)) {
1288                         cmd.receive_all = TRUE;
1289                 } else if (!strncmp(argv[i], "--receive", 9)) {
1290                         cmd.receive = TRUE;
1291                 } else if (!strncmp(argv[i], "--compose", 9)) {
1292                         const gchar *p = argv[i + 1];
1293
1294                         cmd.compose = TRUE;
1295                         cmd.compose_mailto = NULL;
1296                         if (p && *p != '\0' && *p != '-') {
1297                                 if (!strncmp(p, "mailto:", 7)) {
1298                                         cmd.compose_mailto = p + 7;
1299                                 } else {
1300                                         cmd.compose_mailto = p;
1301                                 }
1302                                 i++;
1303                         }
1304                 } else if (!strncmp(argv[i], "--subscribe", 11)) {
1305                         const gchar *p = argv[i + 1];
1306                         if (p && *p != '\0' && *p != '-') {
1307                                 cmd.subscribe = TRUE;
1308                                 cmd.subscribe_uri = p;
1309                         }
1310                 } else if (!strncmp(argv[i], "--attach", 8)) {
1311                         const gchar *p = argv[i + 1];
1312                         gchar *file = NULL;
1313
1314                         while (p && *p != '\0' && *p != '-') {
1315                                 if (!cmd.attach_files) {
1316                                         cmd.attach_files = g_ptr_array_new();
1317                                 }
1318                                 if ((file = g_filename_from_uri(p, NULL, NULL)) != NULL) {
1319                                         if (!is_file_exist(file)) {
1320                                                 g_free(file);
1321                                                 file = NULL;
1322                                         }
1323                                 }
1324                                 if (file == NULL && *p != G_DIR_SEPARATOR) {
1325                                         file = g_strconcat(claws_get_startup_dir(),
1326                                                            G_DIR_SEPARATOR_S,
1327                                                            p, NULL);
1328                                 } else if (file == NULL) {
1329                                         file = g_strdup(p);
1330                                 }
1331                                 g_ptr_array_add(cmd.attach_files, file);
1332                                 i++;
1333                                 p = argv[i + 1];
1334                         }
1335                 } else if (!strncmp(argv[i], "--send", 6)) {
1336                         cmd.send = TRUE;
1337                 } else if (!strncmp(argv[i], "--version", 9) ||
1338                            !strncmp(argv[i], "-v", 2)) {
1339                         puts("Claws Mail version " VERSION);
1340                         exit(0);
1341                 } else if (!strncmp(argv[i], "--status-full", 13)) {
1342                         const gchar *p = argv[i + 1];
1343  
1344                         cmd.status_full = TRUE;
1345                         while (p && *p != '\0' && *p != '-') {
1346                                 if (!cmd.status_full_folders) {
1347                                         cmd.status_full_folders =
1348                                                 g_ptr_array_new();
1349                                 }
1350                                 g_ptr_array_add(cmd.status_full_folders,
1351                                                 g_strdup(p));
1352                                 i++;
1353                                 p = argv[i + 1];
1354                         }
1355                 } else if (!strncmp(argv[i], "--status", 8)) {
1356                         const gchar *p = argv[i + 1];
1357  
1358                         cmd.status = TRUE;
1359                         while (p && *p != '\0' && *p != '-') {
1360                                 if (!cmd.status_folders)
1361                                         cmd.status_folders = g_ptr_array_new();
1362                                 g_ptr_array_add(cmd.status_folders,
1363                                                 g_strdup(p));
1364                                 i++;
1365                                 p = argv[i + 1];
1366                         }
1367                 } else if (!strncmp(argv[i], "--online", 8)) {
1368                         cmd.online_mode = ONLINE_MODE_ONLINE;
1369                 } else if (!strncmp(argv[i], "--offline", 9)) {
1370                         cmd.online_mode = ONLINE_MODE_OFFLINE;
1371                 } else if (!strncmp(argv[i], "--help", 6) ||
1372                            !strncmp(argv[i], "-h", 2)) {
1373                         gchar *base = g_path_get_basename(argv[0]);
1374                         g_print(_("Usage: %s [OPTION]...\n"), base);
1375
1376                         g_print("%s\n", _("  --compose [address]    open composition window"));
1377                         g_print("%s\n", _("  --subscribe [uri]      subscribe to the given URI if possible"));
1378                         g_print("%s\n", _("  --attach file1 [file2]...\n"
1379                                   "                         open composition window with specified files\n"
1380                                   "                         attached"));
1381                         g_print("%s\n", _("  --receive              receive new messages"));
1382                         g_print("%s\n", _("  --receive-all          receive new messages of all accounts"));
1383                         g_print("%s\n", _("  --send                 send all queued messages"));
1384                         g_print("%s\n", _("  --status [folder]...   show the total number of messages"));
1385                         g_print("%s\n", _("  --status-full [folder]...\n"
1386                                "                         show the status of each folder"));
1387                         g_print("%s\n", _("  --select folder[/msg]  jumps to the specified folder/message\n" 
1388                                           "                         folder is a folder id like 'folder/sub_folder'"));
1389                         g_print("%s\n", _("  --online               switch to online mode"));
1390                         g_print("%s\n", _("  --offline              switch to offline mode"));
1391                         g_print("%s\n", _("  --exit --quit -q       exit Claws Mail"));
1392                         g_print("%s\n", _("  --debug                debug mode"));
1393                         g_print("%s\n", _("  --help -h              display this help and exit"));
1394                         g_print("%s\n", _("  --version -v           output version information and exit"));
1395                         g_print("%s\n", _("  --config-dir           output configuration directory"));
1396
1397                         g_free(base);
1398                         exit(1);
1399                 } else if (!strncmp(argv[i], "--crash", 7)) {
1400                         cmd.crash = TRUE;
1401                         cmd.crash_params = g_strdup(argv[i + 1]);
1402                         i++;
1403                 } else if (!strncmp(argv[i], "--config-dir", sizeof "--config-dir" - 1)) {
1404                         puts(RC_DIR);
1405                         exit(0);
1406                 } else if (!strncmp(argv[i], "--exit", 6) ||
1407                            !strncmp(argv[i], "--quit", 6) ||
1408                            !strncmp(argv[i], "-q", 2)) {
1409                         cmd.exit = TRUE;
1410                 } else if (!strncmp(argv[i], "--select", 8) && i+1 < argc) {
1411                         cmd.target = argv[i+1];
1412                 } else if (i == 1 && argc == 2) {
1413                         /* only one parameter. Do something intelligent about it */
1414                         if (strstr(argv[i], "@") && !strstr(argv[i], "://")) {
1415                                 const gchar *p = argv[i];
1416
1417                                 cmd.compose = TRUE;
1418                                 cmd.compose_mailto = NULL;
1419                                 if (p && *p != '\0' && *p != '-') {
1420                                         if (!strncmp(p, "mailto:", 7)) {
1421                                                 cmd.compose_mailto = p + 7;
1422                                         } else {
1423                                                 cmd.compose_mailto = p;
1424                                         }
1425                                 }
1426                         } else if (strstr(argv[i], "://")) {
1427                                 const gchar *p = argv[i];
1428                                 if (p && *p != '\0' && *p != '-') {
1429                                         cmd.subscribe = TRUE;
1430                                         cmd.subscribe_uri = p;
1431                                 }
1432                         } else if (!strcmp(argv[i], "--sync")) {
1433                                 /* gtk debug */
1434                         } else {
1435                                 g_print(_("Unknown option\n"));
1436                                 exit(1);
1437                         }
1438                 }
1439         }
1440
1441         if (cmd.attach_files && cmd.compose == FALSE) {
1442                 cmd.compose = TRUE;
1443                 cmd.compose_mailto = NULL;
1444         }
1445 }
1446
1447 static void initial_processing(FolderItem *item, gpointer data)
1448 {
1449         MainWindow *mainwin = (MainWindow *)data;
1450         gchar *buf;
1451
1452         g_return_if_fail(item);
1453         buf = g_strdup_printf(_("Processing (%s)..."), 
1454                               item->path 
1455                               ? item->path 
1456                               : _("top level folder"));
1457         g_free(buf);
1458
1459         
1460         if (item->prefs->enable_processing) {
1461                 folder_item_apply_processing(item);
1462         }
1463
1464         STATUSBAR_POP(mainwin);
1465 }
1466
1467 static gboolean draft_all_messages(void)
1468 {
1469         GList *compose_list = NULL;
1470         
1471         compose_clear_exit_drafts();
1472         compose_list = compose_get_compose_list();
1473         while (compose_list != NULL) {
1474                 Compose *c = (Compose*)compose_list->data;
1475                 if (!compose_draft(c, COMPOSE_DRAFT_FOR_EXIT))
1476                         return FALSE;
1477                 compose_list = compose_get_compose_list();
1478         }
1479         return TRUE;
1480 }
1481 gboolean clean_quit(gpointer data)
1482 {
1483         static gboolean firstrun = TRUE;
1484
1485         if (!firstrun) {
1486                 return FALSE;
1487         }
1488         firstrun = FALSE;
1489
1490         /*!< Good idea to have the main window stored in a 
1491          *   static variable so we can check that variable
1492          *   to see if we're really allowed to do things
1493          *   that actually the spawner is supposed to 
1494          *   do (like: sending mail, composing messages).
1495          *   Because, really, if we're the spawnee, and
1496          *   we touch GTK stuff, we're hosed. See the 
1497          *   next fixme. */
1498
1499         /* FIXME: Use something else to signal that we're
1500          * in the original spawner, and not in a spawned
1501          * child. */
1502         if (!static_mainwindow) {
1503                 return FALSE;
1504         }
1505                 
1506         draft_all_messages();
1507         emergency_exit = TRUE;
1508         exit_claws(static_mainwindow);
1509         exit(0);
1510
1511         return FALSE;
1512 }
1513
1514 void app_will_exit(GtkWidget *widget, gpointer data)
1515 {
1516         MainWindow *mainwin = data;
1517         
1518         if (sc_exiting == TRUE) {
1519                 debug_print("exit pending\n");
1520                 return;
1521         }
1522         sc_exiting = TRUE;
1523         debug_print("exiting\n");
1524         if (compose_get_compose_list()) {
1525                 if (!draft_all_messages()) {
1526                         main_window_popup(mainwin);
1527                         sc_exiting = FALSE;
1528                         return;
1529                 }
1530         }
1531
1532         if (prefs_common.warn_queued_on_exit && procmsg_have_queued_mails_fast()) {
1533                 if (alertpanel(_("Queued messages"),
1534                                _("Some unsent messages are queued. Exit now?"),
1535                                GTK_STOCK_CANCEL, GTK_STOCK_OK, NULL)
1536                     != G_ALERTALTERNATE) {
1537                         main_window_popup(mainwin);
1538                         sc_exiting = FALSE;
1539                         return;
1540                 }
1541                 manage_window_focus_in(mainwin->window, NULL, NULL);
1542         }
1543
1544         sock_cleanup();
1545 #ifdef HAVE_VALGRIND
1546         if (RUNNING_ON_VALGRIND) {
1547                 summary_clear_list(mainwin->summaryview);
1548         }
1549 #endif
1550         if (folderview_get_selected_item(mainwin->folderview))
1551                 folder_item_close(folderview_get_selected_item(mainwin->folderview));
1552         gtk_main_quit();
1553 }
1554
1555 gboolean claws_is_exiting(void)
1556 {
1557         return sc_exiting;
1558 }
1559
1560 gboolean claws_is_starting(void)
1561 {
1562         return sc_starting;
1563 }
1564
1565 /*
1566  * CLAWS: want this public so crash dialog can delete the
1567  * lock file too
1568  */
1569 gchar *claws_get_socket_name(void)
1570 {
1571         static gchar *filename = NULL;
1572
1573         if (filename == NULL) {
1574                 filename = g_strdup_printf("%s%cclaws-mail-%d",
1575                                            g_get_tmp_dir(), G_DIR_SEPARATOR,
1576 #if HAVE_GETUID
1577                                            getuid());
1578 #else
1579                                            0);                                          
1580 #endif
1581         }
1582
1583         return filename;
1584 }
1585
1586 static gchar *get_crashfile_name(void)
1587 {
1588         static gchar *filename = NULL;
1589
1590         if (filename == NULL) {
1591                 filename = g_strdup_printf("%s%cclaws-crashed",
1592                                            get_tmp_dir(), G_DIR_SEPARATOR);
1593         }
1594
1595         return filename;
1596 }
1597
1598 static gint prohibit_duplicate_launch(void)
1599 {
1600         gint uxsock;
1601         gchar *path;
1602
1603         path = claws_get_socket_name();
1604         uxsock = fd_connect_unix(path);
1605         
1606         if (x_display == NULL)
1607                 x_display = g_strdup(g_getenv("DISPLAY"));
1608
1609         if (uxsock < 0) {
1610                 g_unlink(path);
1611                 return fd_open_unix(path);
1612         }
1613
1614         /* remote command mode */
1615
1616         debug_print("another Claws Mail instance is already running.\n");
1617
1618         if (cmd.receive_all) {
1619                 fd_write_all(uxsock, "receive_all\n", 12);
1620         } else if (cmd.receive) {
1621                 fd_write_all(uxsock, "receive\n", 8);
1622         } else if (cmd.compose && cmd.attach_files) {
1623                 gchar *str, *compose_str;
1624                 gint i;
1625
1626                 if (cmd.compose_mailto) {
1627                         compose_str = g_strdup_printf("compose_attach %s\n",
1628                                                       cmd.compose_mailto);
1629                 } else {
1630                         compose_str = g_strdup("compose_attach\n");
1631                 }
1632
1633                 fd_write_all(uxsock, compose_str, strlen(compose_str));
1634                 g_free(compose_str);
1635
1636                 for (i = 0; i < cmd.attach_files->len; i++) {
1637                         str = g_ptr_array_index(cmd.attach_files, i);
1638                         fd_write_all(uxsock, str, strlen(str));
1639                         fd_write_all(uxsock, "\n", 1);
1640                 }
1641
1642                 fd_write_all(uxsock, ".\n", 2);
1643         } else if (cmd.compose) {
1644                 gchar *compose_str;
1645
1646                 if (cmd.compose_mailto) {
1647                         compose_str = g_strdup_printf
1648                                 ("compose %s\n", cmd.compose_mailto);
1649                 } else {
1650                         compose_str = g_strdup("compose\n");
1651                 }
1652
1653                 fd_write_all(uxsock, compose_str, strlen(compose_str));
1654                 g_free(compose_str);
1655         } else if (cmd.subscribe) {
1656                 gchar *str = g_strdup_printf("subscribe %s\n", cmd.subscribe_uri);
1657                 fd_write_all(uxsock, str, strlen(str));
1658                 g_free(str);
1659         } else if (cmd.send) {
1660                 fd_write_all(uxsock, "send\n", 5);
1661         } else if (cmd.online_mode == ONLINE_MODE_ONLINE) {
1662                 fd_write(uxsock, "online\n", 6);
1663         } else if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
1664                 fd_write(uxsock, "offline\n", 7);
1665         } else if (cmd.status || cmd.status_full) {
1666                 gchar buf[BUFFSIZE];
1667                 gint i;
1668                 const gchar *command;
1669                 GPtrArray *folders;
1670                 gchar *folder;
1671  
1672                 command = cmd.status_full ? "status-full\n" : "status\n";
1673                 folders = cmd.status_full ? cmd.status_full_folders :
1674                         cmd.status_folders;
1675  
1676                 fd_write_all(uxsock, command, strlen(command));
1677                 for (i = 0; folders && i < folders->len; ++i) {
1678                         folder = g_ptr_array_index(folders, i);
1679                         fd_write_all(uxsock, folder, strlen(folder));
1680                         fd_write_all(uxsock, "\n", 1);
1681                 }
1682                 fd_write_all(uxsock, ".\n", 2);
1683                 for (;;) {
1684                         fd_gets(uxsock, buf, sizeof(buf));
1685                         if (!strncmp(buf, ".\n", 2)) break;
1686                         fputs(buf, stdout);
1687                 }
1688         } else if (cmd.exit) {
1689                 fd_write_all(uxsock, "exit\n", 5);
1690         } else if (cmd.target) {
1691                 gchar *str = g_strdup_printf("select %s\n", cmd.target);
1692                 fd_write_all(uxsock, str, strlen(str));
1693                 g_free(str);
1694         } else {
1695                 gchar buf[BUFSIZ];
1696                 fd_write_all(uxsock, "get_display\n", 12);
1697                 memset(buf, 0, sizeof(buf));
1698                 fd_gets(uxsock, buf, sizeof(buf));
1699                 if (strcmp2(buf, x_display)) {
1700                         printf("Claws Mail is already running on display %s.\n",
1701                                 buf);
1702                 } else {
1703                         fd_close(uxsock);
1704                         uxsock = fd_connect_unix(path);
1705                         fd_write_all(uxsock, "popup\n", 6);
1706                 }
1707         }
1708
1709         fd_close(uxsock);
1710         return -1;
1711 }
1712
1713 static gint lock_socket_remove(void)
1714 {
1715 #ifdef G_OS_UNIX
1716         gchar *filename;
1717
1718         if (lock_socket < 0) {
1719                 return -1;
1720         }
1721
1722         if (lock_socket_tag > 0) {
1723                 gdk_input_remove(lock_socket_tag);
1724         }
1725         fd_close(lock_socket);
1726         filename = claws_get_socket_name();
1727         g_unlink(filename);
1728 #endif
1729
1730         return 0;
1731 }
1732
1733 static GPtrArray *get_folder_item_list(gint sock)
1734 {
1735         gchar buf[BUFFSIZE];
1736         FolderItem *item;
1737         GPtrArray *folders = NULL;
1738
1739         for (;;) {
1740                 fd_gets(sock, buf, sizeof(buf));
1741                 if (!strncmp(buf, ".\n", 2)) {
1742                         break;
1743                 }
1744                 strretchomp(buf);
1745                 if (!folders) {
1746                         folders = g_ptr_array_new();
1747                 }
1748                 item = folder_find_item_from_identifier(buf);
1749                 if (item) {
1750                         g_ptr_array_add(folders, item);
1751                 } else {
1752                         g_warning("no such folder: %s\n", buf);
1753                 }
1754         }
1755
1756         return folders;
1757 }
1758
1759 static void lock_socket_input_cb(gpointer data,
1760                                  gint source,
1761                                  GdkInputCondition condition)
1762 {
1763         MainWindow *mainwin = (MainWindow *)data;
1764         gint sock;
1765         gchar buf[BUFFSIZE];
1766
1767         sock = fd_accept(source);
1768         fd_gets(sock, buf, sizeof(buf));
1769
1770         if (!strncmp(buf, "popup", 5)) {
1771                 main_window_popup(mainwin);
1772         } else if (!strncmp(buf, "get_display", 11)) {
1773                 fd_write_all(sock, x_display, strlen(x_display));
1774         } else if (!strncmp(buf, "receive_all", 11)) {
1775                 inc_all_account_mail(mainwin, FALSE,
1776                                      prefs_common.newmail_notify_manu);
1777         } else if (!strncmp(buf, "receive", 7)) {
1778                 inc_mail(mainwin, prefs_common.newmail_notify_manu);
1779         } else if (!strncmp(buf, "compose_attach", 14)) {
1780                 GPtrArray *files;
1781                 gchar *mailto;
1782
1783                 mailto = g_strdup(buf + strlen("compose_attach") + 1);
1784                 files = g_ptr_array_new();
1785                 while (fd_gets(sock, buf, sizeof(buf)) > 0) {
1786                         if (buf[0] == '.' && buf[1] == '\n') {
1787                                 break;
1788                         }
1789                         strretchomp(buf);
1790                         g_ptr_array_add(files, g_strdup(buf));
1791                 }
1792                 open_compose_new(mailto, files);
1793                 ptr_array_free_strings(files);
1794                 g_ptr_array_free(files, TRUE);
1795                 g_free(mailto);
1796         } else if (!strncmp(buf, "compose", 7)) {
1797                 open_compose_new(buf + strlen("compose") + 1, NULL);
1798         } else if (!strncmp(buf, "subscribe", 9)) {
1799                 main_window_popup(mainwin);
1800                 folder_subscribe(buf + strlen("subscribe") + 1);
1801         } else if (!strncmp(buf, "send", 4)) {
1802                 send_queue();
1803         } else if (!strncmp(buf, "online", 6)) {
1804                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
1805         } else if (!strncmp(buf, "offline", 7)) {
1806                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
1807         } else if (!strncmp(buf, "status-full", 11) ||
1808                    !strncmp(buf, "status", 6)) {
1809                 gchar *status;
1810                 GPtrArray *folders;
1811  
1812                 folders = get_folder_item_list(sock);
1813                 status = folder_get_status
1814                         (folders, !strncmp(buf, "status-full", 11));
1815                 fd_write_all(sock, status, strlen(status));
1816                 fd_write_all(sock, ".\n", 2);
1817                 g_free(status);
1818                 if (folders) g_ptr_array_free(folders, TRUE);
1819         } else if (!strncmp(buf, "select ", 7)) {
1820                 const gchar *target = buf+7;
1821                 mainwindow_jump_to(target, TRUE);
1822         } else if (!strncmp(buf, "exit", 4)) {
1823                 app_will_exit(NULL, mainwin);
1824         }
1825
1826         fd_close(sock);
1827 }
1828
1829 static void open_compose_new(const gchar *address, GPtrArray *attach_files)
1830 {
1831         gchar *addr = NULL;
1832
1833         if (address) {
1834                 Xstrdup_a(addr, address, return);
1835                 g_strstrip(addr);
1836         }
1837
1838         compose_new(NULL, addr, attach_files);
1839 }
1840
1841 static void send_queue(void)
1842 {
1843         GList *list;
1844         gchar *errstr = NULL;
1845         gboolean error = FALSE;
1846         for (list = folder_get_list(); list != NULL; list = list->next) {
1847                 Folder *folder = list->data;
1848
1849                 if (folder->queue) {
1850                         gint res = procmsg_send_queue
1851                                 (folder->queue, prefs_common.savemsg,
1852                                 &errstr);
1853
1854                         if (res) {
1855                                 folder_item_scan(folder->queue);
1856                         }
1857                         
1858                         if (res < 0)
1859                                 error = TRUE;
1860                 }
1861         }
1862         if (errstr) {
1863                 gchar *tmp = g_strdup_printf(_("Some errors occurred "
1864                                 "while sending queued messages:\n%s"), errstr);
1865                 g_free(errstr);
1866                 alertpanel_error_log(tmp);
1867                 g_free(tmp);
1868         } else if (error) {
1869                 alertpanel_error_log("Some errors occurred "
1870                                 "while sending queued messages.");
1871         }
1872 }
1873
1874 static void quit_signal_handler(int sig)
1875 {
1876         debug_print("Quitting on signal %d\n", sig);
1877
1878         g_timeout_add(0, clean_quit, NULL);
1879 }
1880
1881 static void install_basic_sighandlers()
1882 {
1883 #ifndef G_OS_WIN32
1884         sigset_t    mask;
1885         struct sigaction act;
1886
1887         sigemptyset(&mask);
1888
1889 #ifdef SIGTERM
1890         sigaddset(&mask, SIGTERM);
1891 #endif
1892 #ifdef SIGINT
1893         sigaddset(&mask, SIGINT);
1894 #endif
1895 #ifdef SIGHUP
1896         sigaddset(&mask, SIGHUP);
1897 #endif
1898
1899         act.sa_handler = quit_signal_handler;
1900         act.sa_mask    = mask;
1901         act.sa_flags   = 0;
1902
1903 #ifdef SIGTERM
1904         sigaction(SIGTERM, &act, 0);
1905 #endif
1906 #ifdef SIGINT
1907         sigaction(SIGINT, &act, 0);
1908 #endif  
1909 #ifdef SIGHUP
1910         sigaction(SIGHUP, &act, 0);
1911 #endif  
1912
1913         sigprocmask(SIG_UNBLOCK, &mask, 0);
1914 #endif /* !G_OS_WIN32 */
1915 }
1916
1917 #ifdef MAEMO
1918 HildonProgram *hildon_program(void)
1919 {
1920         return static_hildonprogram;
1921 }
1922 osso_context_t *get_osso_context(void)
1923 {
1924         return static_osso_context;
1925 }
1926 #endif