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