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