1f10d677f0d23bafd69dc191ec35252fa010ac83
[claws.git] / src / main.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2007 Hiroyuki Yamamoto and the Claws Mail team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  * 
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <glib.h>
27 #include <glib/gi18n.h>
28 #include <gtk/gtkmain.h>
29 #include <gtk/gtkrc.h>
30
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <ctype.h>
35 #include <unistd.h>
36 #include <time.h>
37 #include <sys/stat.h>
38 #include <sys/types.h>
39 #ifdef G_OS_UNIX
40 #  include <signal.h>
41 #  include <errno.h>
42 #  include <fcntl.h>
43 #endif
44 #ifdef HAVE_LIBSM
45 #include <X11/SM/SMlib.h>
46 #endif
47 #ifdef USE_GNUTLS
48 #include <pthread.h>
49 #include <gcrypt.h>
50 GCRY_THREAD_OPTION_PTHREAD_IMPL;
51 #endif
52
53 #include "wizard.h"
54 #ifdef HAVE_STARTUP_NOTIFICATION
55 # define SN_API_NOT_YET_FROZEN
56 # include <libsn/sn-launchee.h>
57 # include <gdk/gdkx.h>
58 #endif
59
60 #ifdef HAVE_DBUS_GLIB
61 #include <dbus/dbus-glib.h>
62 #endif
63 #ifdef HAVE_NETWORKMANAGER_SUPPORT
64 #include <NetworkManager.h>
65 #endif
66
67 #include "claws.h"
68 #include "main.h"
69 #include "mainwindow.h"
70 #include "folderview.h"
71 #include "image_viewer.h"
72 #include "summaryview.h"
73 #include "prefs_common.h"
74 #include "prefs_account.h"
75 #include "prefs_actions.h"
76 #include "prefs_ext_prog.h"
77 #include "prefs_fonts.h"
78 #include "prefs_image_viewer.h"
79 #include "prefs_message.h"
80 #include "prefs_receive.h"
81 #include "prefs_msg_colors.h"
82 #include "prefs_quote.h"
83 #include "prefs_spelling.h"
84 #include "prefs_summaries.h"
85 #include "prefs_themes.h"
86 #include "prefs_other.h"
87 #include "prefs_logging.h"
88 #include "prefs_send.h"
89 #include "prefs_wrapping.h"
90 #include "prefs_compose_writing.h"
91 #include "prefs_display_header.h"
92 #include "account.h"
93 #include "procmsg.h"
94 #include "inc.h"
95 #include "import.h"
96 #include "manage_window.h"
97 #include "alertpanel.h"
98 #include "statusbar.h"
99 #include "addressbook.h"
100 #include "compose.h"
101 #include "folder.h"
102 #include "setup.h"
103 #include "utils.h"
104 #include "gtkutils.h"
105 #include "socket.h"
106 #include "log.h"
107 #include "prefs_toolbar.h"
108 #include "plugin.h"
109 #include "mh_gtk.h"
110 #include "imap_gtk.h"
111 #include "news_gtk.h"
112 #include "matcher.h"
113 #include "tags.h"
114 #include "hooks.h"
115 #include "menu.h"
116
117 #ifdef HAVE_LIBETPAN
118 #include "imap-thread.h"
119 #include "nntp-thread.h"
120 #endif
121 #include "stock_pixmap.h"
122 #ifdef HAVE_VALGRIND
123 #include "valgrind.h"
124 #endif
125 #if (defined(USE_OPENSSL) || defined (USE_GNUTLS))
126 #  include "ssl.h"
127 #endif
128
129 #include "version.h"
130
131 #include "crash.h"
132
133 #include "timing.h"
134
135 #ifdef MAEMO
136 #ifdef CHINOOK
137 #include <hildon/hildon-banner.h>
138 #include <hildon/hildon-program.h>
139 #else
140 #include <hildon-widgets/hildon-banner.h>
141 #include <hildon-widgets/hildon-program.h>
142 #endif
143 #include <gtk/gtkmain.h>
144 #include <libosso.h>
145 #include <libgnomevfs/gnome-vfs-volume.h>
146 #include <libgnomevfs/gnome-vfs-volume-monitor.h>
147 #include <libgnomevfs/gnome-vfs-utils.h>
148
149 #define OSSO_NAME    "claws_mail"
150 #define OSSO_SERVICE "com.nokia."OSSO_NAME
151 #define OSSO_OBJECT  "/com/nokia/"OSSO_NAME
152 #define OSSO_IFACE   "com.nokia."OSSO_NAME
153
154 typedef struct _AppData AppData;
155 struct _AppData {
156     HildonProgram *program;
157     HildonWindow *window;
158     osso_context_t *osso_context;
159 };
160
161 static GnomeVFSVolumeMonitor *volmon;
162 #endif
163
164 #ifdef HAVE_NETWORKMANAGER_SUPPORT
165 /* Went offline due to NetworkManager */
166 static gboolean went_offline_nm;
167 #endif
168
169 #ifdef HAVE_DBUS_GLIB
170 static DBusGProxy *awn_proxy = NULL;
171 #endif
172
173 gchar *prog_version;
174 gchar *argv0;
175
176 #ifdef MAEMO
177 HildonProgram *hildon_program;
178 #endif
179
180 #ifdef HAVE_STARTUP_NOTIFICATION
181 static SnLauncheeContext *sn_context = NULL;
182 static SnDisplay *sn_display = NULL;
183 #endif
184
185 static gint lock_socket = -1;
186 static gint lock_socket_tag = 0;
187 static gchar *x_display = NULL;
188 typedef enum 
189 {
190         ONLINE_MODE_DONT_CHANGE,
191         ONLINE_MODE_ONLINE,
192         ONLINE_MODE_OFFLINE
193 } OnlineMode;
194
195 static struct RemoteCmd {
196         gboolean receive;
197         gboolean receive_all;
198         gboolean compose;
199         const gchar *compose_mailto;
200         GPtrArray *attach_files;
201         gboolean status;
202         gboolean status_full;
203         GPtrArray *status_folders;
204         GPtrArray *status_full_folders;
205         gboolean send;
206         gboolean crash;
207         int online_mode;
208         gchar   *crash_params;
209         gboolean exit;
210         gboolean subscribe;
211         const gchar *subscribe_uri;
212         const gchar *target;
213 } cmd;
214
215 static void parse_cmd_opt(int argc, char *argv[]);
216
217 static gint prohibit_duplicate_launch   (void);
218 static gchar * get_crashfile_name       (void);
219 static gint lock_socket_remove          (void);
220 static void lock_socket_input_cb        (gpointer          data,
221                                          gint              source,
222                                          GdkInputCondition condition);
223
224 static void open_compose_new            (const gchar    *address,
225                                          GPtrArray      *attach_files);
226
227 static void send_queue                  (void);
228 static void initial_processing          (FolderItem *item, gpointer data);
229 static void quit_signal_handler         (int sig);
230 static void install_basic_sighandlers   (void);
231 #if (defined linux && defined SIGIO)
232 static void install_memory_sighandler   (void);
233 #endif
234 static void exit_claws                  (MainWindow *mainwin);
235
236 #ifdef HAVE_NETWORKMANAGER_SUPPORT
237 static void networkmanager_state_change_cb(DBusGProxy *proxy, gchar *dev,
238                                                                                                                                                                          gpointer data);
239 #endif
240
241 #define MAKE_DIR_IF_NOT_EXIST(dir) \
242 { \
243         if (!is_dir_exist(dir)) { \
244                 if (is_file_exist(dir)) { \
245                         alertpanel_warning \
246                                 (_("File '%s' already exists.\n" \
247                                    "Can't create folder."), \
248                                  dir); \
249                         return 1; \
250                 } \
251                 if (make_dir(dir) < 0) \
252                         return 1; \
253         } \
254 }
255
256 static MainWindow *static_mainwindow;
257
258 #ifdef MAEMO
259 static osso_context_t *static_osso_context;
260
261 void exit_event_handler(gboolean die_now, gpointer data)
262 {
263         AppData *appdata;
264         appdata = (AppData *) data;
265         /* Do whatever application needs to do before exiting */
266         exit_claws(static_mainwindow);
267         hildon_banner_show_information(GTK_WIDGET(appdata->window), NULL,
268                                    _("Exiting..."));
269
270 }
271
272 /* Callback for hardware D-BUS events */
273 void hw_event_handler(osso_hw_state_t *state, gpointer data)
274 {
275         AppData *appdata;
276         appdata = (AppData *) data;
277
278         if (state->shutdown_ind) {
279                 exit_claws(static_mainwindow);
280                 hildon_banner_show_information(GTK_WIDGET(appdata->window), NULL,
281                         _("Exiting..."));
282         }
283 }
284
285 /* Callback for normal D-BUS messages */
286 gint dbus_req_handler(const gchar * interface, const gchar * method,
287                       GArray * arguments, gpointer data,
288                       osso_rpc_t * retval)
289 {
290     AppData *appdata;
291     appdata = (AppData *) data;
292
293     if (!strcmp(method, "top_application")) {
294             osso_rpc_free_val(retval);
295             return OSSO_OK;
296     }
297     osso_system_note_infoprint(appdata->osso_context, method, retval);
298     osso_rpc_free_val(retval);
299
300     return OSSO_OK;
301 }
302 #endif
303 static gboolean emergency_exit = FALSE;
304
305 #ifdef HAVE_STARTUP_NOTIFICATION
306 static void sn_error_trap_push(SnDisplay *display, Display *xdisplay)
307 {
308         gdk_error_trap_push();
309 }
310
311 static void sn_error_trap_pop(SnDisplay *display, Display *xdisplay)
312 {
313         gdk_error_trap_pop();
314 }
315
316 static void startup_notification_complete(gboolean with_window)
317 {
318         Display *xdisplay;
319         GtkWidget *hack = NULL;
320
321         if (with_window) {
322                 /* this is needed to make the startup notification leave,
323                  * if we have been launched from a menu.
324                  * We have to display a window, so let it be very little */
325                 hack = gtk_window_new(GTK_WINDOW_POPUP);
326                 gtk_window_move(GTK_WINDOW(hack), 0, 0);
327                 gtk_widget_set_size_request(hack, 1, 1);
328                 gtk_widget_show(hack);
329         }
330
331         xdisplay = GDK_DISPLAY();
332         sn_display = sn_display_new(xdisplay,
333                                 sn_error_trap_push,
334                                 sn_error_trap_pop);
335         sn_context = sn_launchee_context_new_from_environment(sn_display,
336                                                  DefaultScreen(xdisplay));
337
338         if (sn_context != NULL) {
339                 sn_launchee_context_complete(sn_context);
340                 sn_launchee_context_unref(sn_context);
341                 sn_display_unref(sn_display);
342         }
343         if (with_window) {
344                 gtk_widget_destroy(hack);
345         }
346 }
347 #endif /* HAVE_STARTUP_NOTIFICATION */
348
349 static void claws_gtk_idle(void) 
350 {
351         while(gtk_events_pending()) {
352                 gtk_main_iteration();
353         }
354         g_usleep(50000);
355 }
356
357 static gboolean sc_starting = FALSE;
358
359 static gboolean defer_check_all(void *data)
360 {
361         gboolean autochk = GPOINTER_TO_INT(data);
362
363         inc_all_account_mail(static_mainwindow, autochk, 
364                         prefs_common.newmail_notify_manu);
365
366         if (sc_starting) {
367                 sc_starting = FALSE;
368                 main_window_set_menu_sensitive(static_mainwindow);
369                 toolbar_main_set_sensitive(static_mainwindow);
370         }
371         return FALSE;
372 }
373
374 static gboolean defer_check(void *data)
375 {
376         inc_mail(static_mainwindow, prefs_common.newmail_notify_manu);
377
378         if (sc_starting) {
379                 sc_starting = FALSE;
380                 main_window_set_menu_sensitive(static_mainwindow);
381                 toolbar_main_set_sensitive(static_mainwindow);
382         }
383         return FALSE;
384 }
385
386 static gboolean defer_jump(void *data)
387 {
388         if (cmd.receive_all) {
389                 defer_check_all(GINT_TO_POINTER(FALSE));
390         } else if (prefs_common.chk_on_startup) {
391                 defer_check_all(GINT_TO_POINTER(TRUE));
392         } else if (cmd.receive) {
393                 defer_check(NULL);
394         } 
395         mainwindow_jump_to(data, FALSE);
396         if (sc_starting) {
397                 sc_starting = FALSE;
398                 main_window_set_menu_sensitive(static_mainwindow);
399                 toolbar_main_set_sensitive(static_mainwindow);
400         }
401         return FALSE;
402 }
403
404 static void chk_update_val(GtkWidget *widget, gpointer data)
405 {
406         gboolean *val = (gboolean *)data;
407         *val = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget));
408 }
409
410 static gboolean migrate_old_config(const gchar *old_cfg_dir, const gchar *new_cfg_dir, const gchar *oldversion)
411 {
412         gchar *message = g_strdup_printf(_("Configuration for %s found.\n"
413                          "Do you want to migrate this configuration?"), oldversion);
414         gchar *message2 = g_strdup_printf(_("\n\nYour Sylpheed filtering rules can be converted by a\n"
415                              "script available at %s."), TOOLS_URI);
416
417         if (!strcmp(oldversion, "Sylpheed"))
418                 message = g_strconcat(message, message2, NULL);
419         g_free(message2);
420
421         gint r = 0;
422         GtkWidget *window = NULL;
423         GtkWidget *keep_backup_chk;
424         CLAWS_TIP_DECL();
425         gboolean backup = TRUE;
426
427         keep_backup_chk = gtk_check_button_new_with_label (_("Keep old configuration"));
428         gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(keep_backup_chk), TRUE);
429         CLAWS_SET_TIP(keep_backup_chk,
430                              _("Keeping a backup will allow you to go back to an "
431                                "older version, but may take a while if you have "
432                                "cached IMAP or News data, and will take some extra "
433                                "room on your disk."));
434
435         g_signal_connect(G_OBJECT(keep_backup_chk), "toggled", 
436                         G_CALLBACK(chk_update_val), &backup);
437
438         if (alertpanel_full(_("Migration of configuration"), message,
439                         GTK_STOCK_NO, "+" GTK_STOCK_YES, NULL, FALSE,
440                         keep_backup_chk, ALERT_QUESTION, G_ALERTDEFAULT) != G_ALERTALTERNATE) {
441                 return FALSE;
442         }
443         
444         /* we can either do a fast migration requiring not any extra disk
445          * space, or a slow one that copies the old configuration and leaves
446          * it in place. */
447         if (backup) {
448 backup_mode:
449                 window = label_window_create(_("Copying configuration... This may take a while..."));
450                 GTK_EVENTS_FLUSH();
451                 
452                 r = copy_dir(old_cfg_dir, new_cfg_dir);
453                 label_window_destroy(window);
454                 
455                 /* if copy failed, we'll remove the partially copied
456                  * new directory */
457                 if (r != 0) {
458                         alertpanel_error(_("Migration failed!"));
459                         remove_dir_recursive(new_cfg_dir);
460                 } else {
461                         if (!backup) {
462                                 /* fast mode failed, but we don't want backup */
463                                 remove_dir_recursive(old_cfg_dir);
464                         }
465                 }
466         } else {
467                 window = label_window_create(_("Migrating configuration..."));
468                 GTK_EVENTS_FLUSH();
469                 
470                 r = g_rename(old_cfg_dir, new_cfg_dir);
471                 label_window_destroy(window);
472                 
473                 /* if g_rename failed, we'll try to copy */
474                 if (r != 0) {
475                         FILE_OP_ERROR(new_cfg_dir, "g_rename failed, trying copy\n");
476                         goto backup_mode;
477                 }
478         }
479         return (r == 0);
480 }
481
482 static int migrate_common_rc(const gchar *old_rc, const gchar *new_rc)
483 {
484         FILE *oldfp, *newfp;
485         gchar *plugin_path, *old_plugin_path, *new_plugin_path;
486         gchar buf[BUFFSIZE];
487         gboolean err = FALSE;
488
489         oldfp = g_fopen(old_rc, "r");
490         if (!oldfp)
491                 return -1;
492         newfp = g_fopen(new_rc, "w");
493         if (!newfp) {
494                 fclose(oldfp);
495                 return -1;
496         }
497         
498         plugin_path = g_strdup(get_plugin_dir());
499         new_plugin_path = g_strdup(plugin_path);
500         
501         if (strstr(plugin_path, "/claws-mail/")) {
502                 gchar *end = g_strdup(strstr(plugin_path, "/claws-mail/")+strlen("/claws-mail/"));
503                 *(strstr(plugin_path, "/claws-mail/")) = '\0';
504                 old_plugin_path = g_strconcat(plugin_path, "/sylpheed-claws/", end, NULL);
505                 g_free(end);
506         } else {
507                 old_plugin_path = g_strdup(new_plugin_path);
508         }
509         debug_print("replacing %s with %s\n", old_plugin_path, new_plugin_path);
510         while (fgets(buf, sizeof(buf), oldfp)) {
511                 if (strncmp(buf, old_plugin_path, strlen(old_plugin_path))) {
512                         err |= (fputs(buf, newfp) == EOF);
513                 } else {
514                         debug_print("->replacing %s", buf);
515                         debug_print("  with %s%s", new_plugin_path, buf+strlen(old_plugin_path));
516                         err |= (fputs(new_plugin_path, newfp) == EOF);
517                         err |= (fputs(buf+strlen(old_plugin_path), newfp) == EOF);
518                 }
519         }
520         g_free(plugin_path);
521         g_free(new_plugin_path);
522         g_free(old_plugin_path);
523         fclose(oldfp);
524         if (fclose(newfp) == EOF)
525                 err = TRUE;
526         
527         return (err ? -1:0);
528 }
529
530 #ifdef HAVE_LIBSM
531 static void
532 sc_client_set_value (MainWindow *mainwin,
533                   gchar       *name,
534                   char        *type,
535                   int          num_vals,
536                   SmPropValue *vals)
537 {
538         SmProp *proplist[1];
539         SmProp prop;
540
541         prop.name = name;
542         prop.type = type;
543         prop.num_vals = num_vals;
544         prop.vals = vals;
545
546         proplist[0]= &prop;
547         if (mainwin->smc_conn)
548                 SmcSetProperties ((SmcConn) mainwin->smc_conn, 1, proplist);
549 }
550
551 static void sc_die_callback (SmcConn smc_conn, SmPointer client_data)
552 {
553         clean_quit(NULL);
554 }
555
556 static void sc_save_complete_callback(SmcConn smc_conn, SmPointer client_data)
557 {
558 }
559
560 static void sc_shutdown_cancelled_callback (SmcConn smc_conn, SmPointer client_data)
561 {
562         MainWindow *mainwin = (MainWindow *)client_data;
563         if (mainwin->smc_conn)
564                 SmcSaveYourselfDone ((SmcConn) mainwin->smc_conn, TRUE);
565 }
566
567 static void sc_save_yourself_callback (SmcConn   smc_conn,
568                                SmPointer client_data,
569                                int       save_style,
570                                gboolean  shutdown,
571                                int       interact_style,
572                                gboolean  fast) {
573
574         MainWindow *mainwin = (MainWindow *)client_data;
575         if (mainwin->smc_conn)
576                 SmcSaveYourselfDone ((SmcConn) mainwin->smc_conn, TRUE);
577 }
578
579 static IceIOErrorHandler sc_ice_installed_handler;
580
581 static void sc_ice_io_error_handler (IceConn connection)
582 {
583         if (sc_ice_installed_handler)
584                 (*sc_ice_installed_handler) (connection);
585 }
586 static gboolean sc_process_ice_messages (GIOChannel   *source,
587                       GIOCondition  condition,
588                       gpointer      data)
589 {
590         IceConn connection = (IceConn) data;
591         IceProcessMessagesStatus status;
592
593         status = IceProcessMessages (connection, NULL, NULL);
594
595         if (status == IceProcessMessagesIOError) {
596                 IcePointer context = IceGetConnectionContext (connection);
597
598                 if (context && GTK_IS_OBJECT (context)) {
599                 guint disconnect_id = g_signal_lookup ("disconnect", G_OBJECT_TYPE (context));
600
601                 if (disconnect_id > 0)
602                         g_signal_emit (context, disconnect_id, 0);
603                 } else {
604                         IceSetShutdownNegotiation (connection, False);
605                         IceCloseConnection (connection);
606                 }
607         }
608
609         return TRUE;
610 }
611
612 static void new_ice_connection (IceConn connection, IcePointer client_data, Bool opening,
613                     IcePointer *watch_data)
614 {
615         guint input_id;
616
617         if (opening) {
618                 GIOChannel *channel;
619                 /* Make sure we don't pass on these file descriptors to any
620                 exec'ed children */
621                 fcntl(IceConnectionNumber(connection),F_SETFD,
622                 fcntl(IceConnectionNumber(connection),F_GETFD,0) | FD_CLOEXEC);
623
624                 channel = g_io_channel_unix_new (IceConnectionNumber (connection));
625                 input_id = g_io_add_watch (channel,
626                 G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_PRI,
627                 sc_process_ice_messages,
628                 connection);
629                 g_io_channel_unref (channel);
630
631                 *watch_data = (IcePointer) GUINT_TO_POINTER (input_id);
632         } else {
633                 input_id = GPOINTER_TO_UINT ((gpointer) *watch_data);
634                 g_source_remove (input_id);
635         }
636 }
637
638 static void sc_session_manager_connect(MainWindow *mainwin)
639 {
640         static gboolean connected = FALSE;
641         SmcCallbacks      callbacks;
642         gchar            *client_id;
643         IceIOErrorHandler default_handler;
644
645         if (connected)
646                 return;
647         connected = TRUE;
648
649
650         sc_ice_installed_handler = IceSetIOErrorHandler (NULL);
651         default_handler = IceSetIOErrorHandler (sc_ice_io_error_handler);
652
653         if (sc_ice_installed_handler == default_handler)
654                 sc_ice_installed_handler = NULL;
655
656         IceAddConnectionWatch (new_ice_connection, NULL);
657       
658       
659         callbacks.save_yourself.callback      = sc_save_yourself_callback;
660         callbacks.die.callback                = sc_die_callback;
661         callbacks.save_complete.callback      = sc_save_complete_callback;
662         callbacks.shutdown_cancelled.callback = sc_shutdown_cancelled_callback;
663
664         callbacks.save_yourself.client_data =
665                 callbacks.die.client_data =
666                 callbacks.save_complete.client_data =
667                 callbacks.shutdown_cancelled.client_data = (SmPointer) mainwin;
668         if (g_getenv ("SESSION_MANAGER")) {
669                 gchar error_string_ret[256] = "";
670
671                 mainwin->smc_conn = (gpointer)
672                         SmcOpenConnection (NULL, mainwin,
673                                 SmProtoMajor, SmProtoMinor,
674                                 SmcSaveYourselfProcMask | SmcDieProcMask |
675                                 SmcSaveCompleteProcMask |
676                                 SmcShutdownCancelledProcMask,
677                                 &callbacks,
678                                 NULL, &client_id,
679                                 256, error_string_ret);
680
681                 if (error_string_ret[0] || mainwin->smc_conn == NULL)
682                         g_warning ("While connecting to session manager:\n%s.",
683                                 error_string_ret);
684                 else {
685                         SmPropValue *vals;
686                         vals = g_new (SmPropValue, 1);
687                         vals[0].length = strlen(argv0);
688                         vals[0].value = argv0;
689                         sc_client_set_value (mainwin, SmCloneCommand, SmLISTofARRAY8, 1, vals);
690                         sc_client_set_value (mainwin, SmRestartCommand, SmLISTofARRAY8, 1, vals);
691                         sc_client_set_value (mainwin, SmProgram, SmARRAY8, 1, vals);
692
693                         vals[0].length = strlen(g_get_user_name()?g_get_user_name():"");
694                         vals[0].value = g_strdup(g_get_user_name()?g_get_user_name():"");
695                         sc_client_set_value (mainwin, SmUserID, SmARRAY8, 1, vals);
696                 }
697         }
698 }
699 #endif
700
701 static gboolean sc_exiting = FALSE;
702 static gboolean show_at_startup = TRUE;
703 static gboolean claws_crashed_bool = FALSE;
704
705 gboolean claws_crashed(void) {
706         return claws_crashed_bool;
707 }
708
709 void main_set_show_at_startup(gboolean show)
710 {
711         show_at_startup = show;
712 }
713
714 #ifdef MAEMO
715 static void main_vol_mount_cb(GnomeVFSVolumeMonitor *vfs, GnomeVFSVolume *vol, MainWindow *mainwin)
716 {
717         gchar *uri = gnome_vfs_volume_get_activation_uri (vol);
718         gchar *mount_path = uri?gnome_vfs_get_local_path_from_uri (uri):NULL;
719         g_free (uri);
720         if (mount_path) {
721                 if(!strcmp(mount_path, prefs_common.data_root)) {
722                         gtk_widget_set_sensitive(mainwin->window, TRUE);
723                         inc_unlock();
724                 }
725         }
726         g_free(mount_path);
727 }
728 static void main_vol_unmount_cb(GnomeVFSVolumeMonitor *vfs, GnomeVFSVolume *vol, MainWindow *mainwin)
729 {
730         gchar *uri = gnome_vfs_volume_get_activation_uri (vol);
731         gchar *mount_path = uri?gnome_vfs_get_local_path_from_uri (uri):NULL;
732         g_free (uri);
733         if (mount_path) {
734                 if(!strcmp(mount_path, prefs_common.data_root)) {
735                         gtk_widget_set_sensitive(mainwin->window, FALSE);
736                         inc_lock();
737                 }
738         }
739         g_free(mount_path);
740 }
741 #endif
742
743 #ifdef G_OS_WIN32
744 static FILE* win32_debug_fp=NULL;
745 static guint win32_log_handler_app_id;
746 static guint win32_log_handler_glib_id;
747 static guint win32_log_handler_gtk_id;
748
749 static void win32_print_stdout(const gchar *string)
750 {
751         if (win32_debug_fp) {
752                 fprintf(win32_debug_fp, string);
753                 fflush(win32_debug_fp);
754         }
755 }
756
757 static void win32_print_stderr(const gchar *string)
758 {
759         if (win32_debug_fp) {
760                 fprintf(win32_debug_fp, string);
761                 fflush(win32_debug_fp);
762         }
763 }
764
765 static void win32_log(const gchar *log_domain, GLogLevelFlags log_level, const gchar* message, gpointer user_data)
766 {
767         if (win32_debug_fp) {
768                 const gchar* type;
769
770                 switch(log_level & G_LOG_LEVEL_MASK)
771                 {
772                         case G_LOG_LEVEL_ERROR:
773                                 type="error";
774                                 break;
775                         case G_LOG_LEVEL_CRITICAL:
776                                 type="critical";
777                                 break;
778                         case G_LOG_LEVEL_WARNING:
779                                 type="warning";
780                                 break;
781                         case G_LOG_LEVEL_MESSAGE:
782                                 type="message";
783                                 break;
784                         case G_LOG_LEVEL_INFO:
785                                 type="info";
786                                 break;
787                         case G_LOG_LEVEL_DEBUG:
788                                 type="debug";
789                                 break;
790                         default:
791                                 type="N/A";
792                 }
793                 if (log_domain)
794                         fprintf(win32_debug_fp, "%s: %s: %s", log_domain, type, message);
795                 else
796                         fprintf(win32_debug_fp, "%s: %s", type, message);
797                 fflush(win32_debug_fp);
798         }
799 }
800
801 static void win32_open_log(void)
802 {
803         if (is_file_exist("claws-win32.log")) {
804                 if (rename_force("claws-win32.log", "claws-win32.log.bak") < 0)
805                         FILE_OP_ERROR("claws-win32.log", "rename");
806         }
807         win32_debug_fp = fopen("claws-win32.log", "w");
808         if (win32_debug_fp)
809         {
810                 g_set_print_handler(win32_print_stdout);
811                 g_set_printerr_handler(win32_print_stdout);
812                 win32_log_handler_app_id = g_log_set_handler(NULL, G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
813                      | G_LOG_FLAG_RECURSION, win32_log, NULL);
814                 win32_log_handler_glib_id = g_log_set_handler("GLib", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
815                      | G_LOG_FLAG_RECURSION, win32_log, NULL);
816                 win32_log_handler_gtk_id = g_log_set_handler("Gtk", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
817                      | G_LOG_FLAG_RECURSION, win32_log, NULL);
818         }
819 }
820
821 static void win32_close_log(void)
822 {
823         if (win32_debug_fp)
824         {
825                 g_log_remove_handler("", win32_log_handler_app_id);
826                 g_log_remove_handler("GLib", win32_log_handler_glib_id);
827                 g_log_remove_handler("Gtk", win32_log_handler_gtk_id);
828                 fclose(win32_debug_fp);
829                 win32_debug_fp=NULL;
830         }
831 }               
832 #endif
833
834 static void main_dump_features_list(gboolean show_debug_only)
835 /* display compiled-in features list */
836 {
837         if (show_debug_only && !debug_get_mode())
838                 return;
839
840         if (show_debug_only)
841                 debug_print("runtime GTK+ %d.%d.%d / GLib %d.%d.%d\n",
842                            gtk_major_version, gtk_minor_version, gtk_micro_version,
843                            glib_major_version, glib_minor_version, glib_micro_version);
844         else
845                 g_print("runtime GTK+ %d.%d.%d / GLib %d.%d.%d\n",
846                            gtk_major_version, gtk_minor_version, gtk_micro_version,
847                            glib_major_version, glib_minor_version, glib_micro_version);
848         if (show_debug_only)
849                 debug_print("buildtime GTK+ %d.%d.%d / GLib %d.%d.%d\n",
850                            GTK_MAJOR_VERSION, GTK_MINOR_VERSION, GTK_MICRO_VERSION,
851                            GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION);
852         else
853                 g_print("buildtime GTK+ %d.%d.%d / GLib %d.%d.%d\n",
854                            GTK_MAJOR_VERSION, GTK_MINOR_VERSION, GTK_MICRO_VERSION,
855                            GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION);
856         
857         if (show_debug_only)
858                 debug_print("Compiled-in features:\n");
859         else
860                 g_print("Compiled-in features:\n");
861 #if HAVE_LIBCOMPFACE
862         if (show_debug_only)
863                 debug_print(" compface\n");
864         else
865                 g_print(" compface\n");
866 #endif
867 #if USE_ASPELL
868         if (show_debug_only)
869                 debug_print(" aspell\n");
870         else
871                 g_print(" aspell\n");
872 #endif
873 #if USE_GNUTLS
874         if (show_debug_only)
875                 debug_print(" gnutls\n");
876         else
877                 g_print(" gnutls\n");
878 #endif
879 #if INET6
880         if (show_debug_only)
881                 debug_print(" ipv6\n");
882         else
883                 g_print(" ipv6\n");
884 #endif
885 #if HAVE_ICONV
886         if (show_debug_only)
887                 debug_print(" iconv\n");
888         else
889                 g_print(" iconv\n");
890 #endif
891 #if USE_JPILOT
892         if (show_debug_only)
893                 debug_print(" jpilot\n");
894         else
895                 g_print(" jpilot\n");
896 #endif
897 #if USE_LDAP
898         if (show_debug_only)
899                 debug_print(" ldap\n");
900         else
901                 g_print(" ldap\n");
902 #endif
903 #if HAVE_LIBETPAN
904         if (show_debug_only)
905                 debug_print(" libetpan %d.%d\n", LIBETPAN_VERSION_MAJOR, LIBETPAN_VERSION_MINOR);
906         else
907                 g_print(" libetpan %d.%d\n", LIBETPAN_VERSION_MAJOR, LIBETPAN_VERSION_MINOR);
908 #endif
909 #if USE_GNOMEPRINT
910         if (show_debug_only)
911                 debug_print(" gnomeprint\n");
912         else
913                 g_print(" gnomeprint\n");
914 #endif
915 #if HAVE_LIBSM
916         if (show_debug_only)
917                 debug_print(" libsm\n");
918         else
919                 g_print(" libsm\n");
920 #endif
921 #if HAVE_NETWORKMANAGER_SUPPORT
922         if (show_debug_only)
923                 debug_print(" NetworkManager\n");
924         else
925                 g_print(" NetworkManager\n");
926 #endif
927 #if USE_OPENSSL
928         if (show_debug_only)
929                 debug_print(" openssl\n");
930         else
931                 g_print(" openssl\n");
932 #endif
933 }
934
935 #ifdef HAVE_DBUS_GLIB
936 static guint dbus_item_hook_id = -1;
937 static guint dbus_folder_hook_id = -1;
938
939 static void uninstall_dbus_status_handler(void)
940 {
941         if(awn_proxy)
942                 g_object_unref(awn_proxy);
943         awn_proxy = NULL;
944         if (dbus_item_hook_id != -1)
945                 hooks_unregister_hook(FOLDER_ITEM_UPDATE_HOOKLIST, dbus_item_hook_id);
946         if (dbus_folder_hook_id != -1)
947                 hooks_unregister_hook(FOLDER_UPDATE_HOOKLIST, dbus_folder_hook_id);
948 }
949
950 static void dbus_update(FolderItem *removed_item)
951 {
952         guint new, unread, unreadmarked, marked, total;
953         guint replied, forwarded, locked, ignored, watched;
954         gchar *buf;
955         GError *error = NULL;
956
957         folder_count_total_msgs(&new, &unread, &unreadmarked, &marked, &total,
958                                 &replied, &forwarded, &locked, &ignored,
959                                 &watched);
960         if (removed_item) {
961                 total -= removed_item->total_msgs;
962                 new -= removed_item->new_msgs;
963                 unread -= removed_item->unread_msgs;
964         }
965
966         if (new > 0) {
967                 buf = g_strdup_printf("%d", new);
968                 dbus_g_proxy_call(awn_proxy, "SetInfoByName", &error,
969                         G_TYPE_STRING, "claws-mail",
970                         G_TYPE_STRING, buf,
971                         G_TYPE_INVALID, G_TYPE_INVALID);
972                 g_free(buf);
973                 
974         } else {
975                 dbus_g_proxy_call(awn_proxy, "UnsetInfoByName", &error, G_TYPE_STRING,
976                         "claws-mail", G_TYPE_INVALID, G_TYPE_INVALID);
977         }
978         if (error) {
979                 debug_print(error->message);
980                 g_error_free(error);
981         }
982 }
983
984 static gboolean dbus_status_update_folder_hook(gpointer source, gpointer data)
985 {
986         FolderUpdateData *hookdata;
987         hookdata = source;
988         if (hookdata->update_flags & FOLDER_REMOVE_FOLDERITEM)
989                 dbus_update(hookdata->item);
990         else
991                 dbus_update(NULL);
992
993         return FALSE;
994 }
995
996 static gboolean dbus_status_update_item_hook(gpointer source, gpointer data)
997 {
998         dbus_update(NULL);
999
1000         return FALSE;
1001 }
1002
1003 static void install_dbus_status_handler(void)
1004 {
1005         GError *tmp_error = NULL;
1006         DBusGConnection *connection = dbus_g_bus_get(DBUS_BUS_SESSION, &tmp_error);
1007         
1008         if(!connection) {
1009                 /* If calling code doesn't do error checking, at least print some debug */
1010                 debug_print("Failed to open connection to session bus: %s\n",
1011                                  tmp_error->message);
1012                 g_error_free(tmp_error);
1013                 return;
1014         }
1015         awn_proxy = dbus_g_proxy_new_for_name(connection,
1016                         "com.google.code.Awn",
1017                         "/com/google/code/Awn",
1018                         "com.google.code.Awn");
1019         dbus_item_hook_id = hooks_register_hook (FOLDER_ITEM_UPDATE_HOOKLIST, dbus_status_update_item_hook, NULL);
1020         if (dbus_item_hook_id == -1) {
1021                 g_warning(_("Failed to register folder item update hook"));
1022                 uninstall_dbus_status_handler();
1023                 return;
1024         }
1025
1026         dbus_folder_hook_id = hooks_register_hook (FOLDER_UPDATE_HOOKLIST, dbus_status_update_folder_hook, NULL);
1027         if (dbus_folder_hook_id == -1) {
1028                 g_warning(_("Failed to register folder update hook"));
1029                 uninstall_dbus_status_handler();
1030                 return;
1031         }
1032 }
1033 #endif
1034
1035 int main(int argc, char *argv[])
1036 {
1037 #ifdef MAEMO
1038         osso_context_t *osso_context;
1039         osso_return_t result;
1040 #endif
1041 #ifdef HAVE_DBUS_GLIB
1042         DBusGConnection *connection;
1043         GError *error;
1044 #endif
1045 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1046         DBusGProxy *nm_proxy;
1047 #endif
1048         gchar *userrc;
1049         MainWindow *mainwin;
1050         FolderView *folderview;
1051         GdkPixbuf *icon;
1052         gboolean crash_file_present = FALSE;
1053         gint num_folder_class = 0;
1054         gboolean asked_for_migration = FALSE;
1055         gboolean start_done = TRUE;
1056         GtkUIManager *gui_manager = NULL;
1057         
1058         START_TIMING("startup");
1059
1060         sc_starting = TRUE;
1061
1062 #ifdef G_OS_WIN32
1063         win32_open_log();
1064 #endif
1065         if (!claws_init(&argc, &argv)) {
1066 #ifdef G_OS_WIN32
1067                 win32_close_log();
1068 #endif
1069                 return 0;
1070         }
1071
1072         main_dump_features_list(TRUE);
1073
1074         prog_version = PROG_VERSION;
1075         argv0 = g_strdup(argv[0]);
1076
1077         parse_cmd_opt(argc, argv);
1078
1079         prefs_prepare_cache();
1080
1081 #ifdef CRASH_DIALOG
1082         if (cmd.crash) {
1083                 gtk_set_locale();
1084                 gtk_init(&argc, &argv);
1085                 crash_main(cmd.crash_params);
1086 #ifdef G_OS_WIN32
1087                 win32_close_log();
1088 #endif
1089                 return 0;
1090         }
1091         crash_install_handlers();
1092 #endif
1093         install_basic_sighandlers();
1094 #if (defined linux && defined SIGIO)
1095         install_memory_sighandler();
1096 #endif
1097         sock_init();
1098
1099         /* check and create unix domain socket for remote operation */
1100 #ifdef G_OS_UNIX
1101         lock_socket = prohibit_duplicate_launch();
1102         if (lock_socket < 0) {
1103 #ifdef HAVE_STARTUP_NOTIFICATION
1104                 if(gtk_init_check(&argc, &argv))
1105                         startup_notification_complete(TRUE);
1106 #endif
1107                 return 0;
1108         }
1109
1110         if (cmd.status || cmd.status_full) {
1111                 puts("0 Claws Mail not running.");
1112                 lock_socket_remove();
1113                 return 0;
1114         }
1115         
1116         if (cmd.exit)
1117                 return 0;
1118 #endif
1119         if (!g_thread_supported())
1120                 g_thread_init(NULL);
1121
1122         gtk_set_locale();
1123         gtk_init(&argc, &argv);
1124
1125 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1126         went_offline_nm = FALSE;
1127         nm_proxy = NULL;
1128 #endif
1129 #ifdef HAVE_DBUS_GLIB
1130         error = NULL;
1131         connection = dbus_g_bus_get(DBUS_BUS_SYSTEM, &error);
1132
1133         if(!connection) {
1134                 debug_print("Failed to open connection to system bus: %s\n", error->message);
1135                 g_error_free(error);
1136         }
1137         else {
1138 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1139                 nm_proxy = dbus_g_proxy_new_for_name(connection,
1140                         "org.freedesktop.NetworkManager",
1141                         "/org/freedesktop/NetworkManager",
1142                         "org.freedesktop.NetworkManager");
1143                 if (nm_proxy) {
1144                         dbus_g_proxy_add_signal(nm_proxy, "StateChange", G_TYPE_UINT, G_TYPE_INVALID);
1145                         dbus_g_proxy_connect_signal(nm_proxy, "StateChange",
1146                                 G_CALLBACK(networkmanager_state_change_cb),
1147                                 NULL,NULL);
1148                 }
1149 #endif
1150                 install_dbus_status_handler();
1151         }
1152 #endif
1153
1154
1155 #ifdef MAEMO
1156         osso_context = osso_initialize(OSSO_SERVICE, "2.8.1", TRUE, NULL);
1157         if (osso_context == NULL) {
1158                 return OSSO_ERROR;
1159         }
1160         hildon_program = HILDON_PROGRAM(hildon_program_get_instance());
1161         static_osso_context = osso_context;
1162 #endif  
1163         gtk_widget_set_default_colormap(gdk_rgb_get_colormap());
1164
1165         gui_manager = gtkut_create_ui_manager();
1166
1167         /* Create container for all the menus we will be adding */
1168         MENUITEM_ADDUI("/", "Menus", NULL, GTK_UI_MANAGER_MENUBAR);
1169
1170         if (!g_thread_supported()) {
1171                 g_error(_("g_thread is not supported by glib.\n"));
1172         }
1173
1174         /* check that we're not on a too recent/old gtk+ */
1175 #if GTK_CHECK_VERSION(2, 9, 0)
1176         if (gtk_check_version(2, 9, 0) != NULL) {
1177                 alertpanel_error(_("Claws Mail has been compiled with "
1178                                    "a more recent GTK+ library than is "
1179                                    "currently available. This will cause "
1180                                    "crashes. You need to upgrade GTK+ or "
1181                                    "recompile Claws Mail."));
1182 #ifdef G_OS_WIN32
1183                 win32_close_log();
1184 #endif
1185                 exit(1);
1186         }
1187 #else
1188         if (gtk_check_version(2, 9, 0) == NULL) {
1189                 alertpanel_error(_("Claws Mail has been compiled with "
1190                                    "an older GTK+ library than is "
1191                                    "currently available. This will cause "
1192                                    "crashes. You need to recompile "
1193                                    "Claws Mail."));
1194 #ifdef G_OS_WIN32
1195                 win32_close_log();
1196 #endif
1197                 exit(1);
1198         }
1199 #endif  
1200
1201 #ifdef G_OS_WIN32
1202         CHDIR_EXEC_CODE_RETURN_VAL_IF_FAIL(get_home_dir(), 1, win32_close_log(););
1203 #else
1204         CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
1205 #endif
1206         
1207         /* no config dir exists. See if we can migrate an old config. */
1208         if (!is_dir_exist(RC_DIR)) {
1209                 prefs_destroy_cache();
1210                 gboolean r = FALSE;
1211                 
1212                 /* if one of the old dirs exist, we'll ask if the user 
1213                  * want to migrates, and r will be TRUE if he said yes
1214                  * and migration succeeded, and FALSE otherwise.
1215                  */
1216                 if (is_dir_exist(OLD_GTK2_RC_DIR)) {
1217                         r = migrate_old_config(OLD_GTK2_RC_DIR, RC_DIR, _("Sylpheed-Claws 2.6.0 (or older)"));
1218                         asked_for_migration = TRUE;
1219                 } else if (is_dir_exist(OLDER_GTK2_RC_DIR)) {
1220                         r = migrate_old_config(OLDER_GTK2_RC_DIR, RC_DIR, _("Sylpheed-Claws 1.9.15 (or older)"));
1221                         asked_for_migration = TRUE;
1222                 } else if (is_dir_exist(OLD_GTK1_RC_DIR)) {
1223                         r = migrate_old_config(OLD_GTK1_RC_DIR, RC_DIR, _("Sylpheed-Claws 1.0.5 (or older)"));
1224                         asked_for_migration = TRUE;
1225                 } else if (is_dir_exist(SYLPHEED_RC_DIR)) {
1226                         r = migrate_old_config(SYLPHEED_RC_DIR, RC_DIR, "Sylpheed");
1227                         asked_for_migration = TRUE;
1228                 }
1229                 
1230                 /* If migration failed or the user didn't want to do it,
1231                  * we create a new one (and we'll hit wizard later). 
1232                  */
1233                 if (r == FALSE && !is_dir_exist(RC_DIR) && make_dir(RC_DIR) < 0) {
1234 #ifdef G_OS_WIN32
1235                         win32_close_log();
1236 #endif
1237                         exit(1);
1238         }
1239         }
1240         
1241
1242         if (!is_file_exist(RC_DIR G_DIR_SEPARATOR_S COMMON_RC) &&
1243             is_file_exist(RC_DIR G_DIR_SEPARATOR_S OLD_COMMON_RC)) {
1244                 /* post 2.6 name change */
1245                 migrate_common_rc(RC_DIR G_DIR_SEPARATOR_S OLD_COMMON_RC,
1246                           RC_DIR G_DIR_SEPARATOR_S COMMON_RC);
1247         }
1248
1249         if (!cmd.exit)
1250                 plugin_load_all("Common");
1251
1252         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, "gtkrc-2.0", NULL);
1253         gtk_rc_parse(userrc);
1254         g_free(userrc);
1255
1256         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
1257         gtk_accel_map_load (userrc);
1258         g_free(userrc);
1259
1260 #ifdef G_OS_WIN32
1261         CHDIR_EXEC_CODE_RETURN_VAL_IF_FAIL(get_rc_dir(), 1, win32_close_log(););
1262 #else
1263         CHDIR_RETURN_VAL_IF_FAIL(get_rc_dir(), 1);
1264 #endif
1265
1266         MAKE_DIR_IF_NOT_EXIST(get_mail_base_dir());
1267         MAKE_DIR_IF_NOT_EXIST(get_imap_cache_dir());
1268         MAKE_DIR_IF_NOT_EXIST(get_news_cache_dir());
1269         MAKE_DIR_IF_NOT_EXIST(get_mime_tmp_dir());
1270         MAKE_DIR_IF_NOT_EXIST(get_tmp_dir());
1271         MAKE_DIR_IF_NOT_EXIST(UIDL_DIR);
1272
1273         crash_file_present = is_file_exist(get_crashfile_name());
1274         /* remove temporary files */
1275         remove_all_files(get_tmp_dir());
1276         remove_all_files(get_mime_tmp_dir());
1277
1278         if (!cmd.crash && crash_file_present)
1279                 claws_crashed_bool = TRUE;
1280
1281         if (is_file_exist("claws.log")) {
1282                 if (rename_force("claws.log", "claws.log.bak") < 0)
1283                         FILE_OP_ERROR("claws.log", "rename");
1284         }
1285         set_log_file(LOG_PROTOCOL, "claws.log");
1286
1287         if (is_file_exist("filtering.log")) {
1288                 if (rename_force("filtering.log", "filtering.log.bak") < 0)
1289                         FILE_OP_ERROR("filtering.log", "rename");
1290         }
1291         set_log_file(LOG_DEBUG_FILTERING, "filtering.log");
1292
1293 #ifdef G_OS_WIN32
1294         CHDIR_EXEC_CODE_RETURN_VAL_IF_FAIL(get_home_dir(), 1, win32_close_log(););
1295 #else
1296         CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
1297 #endif
1298
1299         folder_system_init();
1300         prefs_common_read_config();
1301
1302         prefs_themes_init();
1303         prefs_fonts_init();
1304         prefs_ext_prog_init();
1305         prefs_wrapping_init();
1306         prefs_compose_writing_init();
1307         prefs_msg_colors_init();
1308         image_viewer_init();
1309         prefs_image_viewer_init();
1310         prefs_quote_init();
1311         prefs_summaries_init();
1312         prefs_message_init();
1313         prefs_other_init();
1314         prefs_logging_init();
1315         prefs_receive_init();
1316         prefs_send_init();
1317         tags_read_tags();
1318 #ifdef USE_ASPELL
1319         gtkaspell_checkers_init();
1320         prefs_spelling_init();
1321 #endif
1322
1323         sock_set_io_timeout(prefs_common.io_timeout_secs);
1324         prefs_actions_read_config();
1325         prefs_display_header_read_config();
1326         /* prefs_filtering_read_config(); */
1327         addressbook_read_file();
1328
1329         gtkut_widget_init();
1330         stock_pixbuf_gdk(NULL, STOCK_PIXMAP_CLAWS_MAIL_ICON, &icon);
1331         gtk_window_set_default_icon(icon);
1332
1333         folderview_initialize();
1334
1335         mh_gtk_init();
1336         imap_gtk_init();
1337         news_gtk_init();
1338
1339         mainwin = main_window_create();
1340
1341 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1342         networkmanager_state_change_cb(nm_proxy,NULL,mainwin);
1343 #endif
1344
1345 #ifdef MAEMO
1346         AppData *appdata;
1347         appdata = g_new0(AppData, 1);
1348         appdata->program = hildon_program;
1349         appdata->window = HILDON_WINDOW(mainwin->window);
1350         appdata->osso_context = osso_context;
1351         result = osso_rpc_set_cb_f(appdata->osso_context, 
1352                 OSSO_SERVICE, 
1353                 OSSO_OBJECT, 
1354                 OSSO_IFACE,
1355                 dbus_req_handler, appdata);
1356         if (result != OSSO_OK) {
1357                 return OSSO_ERROR;
1358         }
1359
1360 #ifndef CHINOOK
1361         /* Add handler for Exit D-BUS messages */
1362         result = osso_application_set_exit_cb(appdata->osso_context,
1363                                                 exit_event_handler,
1364                                                 (gpointer) appdata);
1365         if (result != OSSO_OK) {
1366                 return OSSO_ERROR;
1367         }
1368 #endif
1369         osso_hw_set_event_cb( appdata->osso_context,
1370                                 NULL, hw_event_handler, (gpointer) appdata );
1371 #endif
1372         manage_window_focus_in(mainwin->window, NULL, NULL);
1373         folderview = mainwin->folderview;
1374
1375         gtk_cmclist_freeze(GTK_CMCLIST(mainwin->folderview->ctree));
1376         folder_item_update_freeze();
1377
1378         /* register the callback of unix domain socket input */
1379 #ifdef G_OS_UNIX
1380         lock_socket_tag = claws_input_add(lock_socket,
1381                                         GDK_INPUT_READ | GDK_INPUT_EXCEPTION,
1382                                         lock_socket_input_cb,
1383                                         mainwin);
1384 #endif
1385
1386
1387         prefs_account_init();
1388         account_read_config_all();
1389
1390         /* If we can't read a folder list or don't have accounts,
1391          * it means the configuration's not done. Either this is
1392          * a brand new install, either a failed/refused migration.
1393          * So we'll start the wizard.
1394          */
1395         if (folder_read_list() < 0) {
1396                 prefs_destroy_cache();
1397                 
1398                 /* if run_wizard returns FALSE it's because it's
1399                  * been cancelled. We can't do much but exit.
1400                  * however, if the user was asked for a migration,
1401                  * we remove the newly created directory so that
1402                  * he's asked again for migration on next launch.*/
1403                 if (!run_wizard(mainwin, TRUE)) {
1404                         if (asked_for_migration)
1405                                 remove_dir_recursive(RC_DIR);
1406 #ifdef G_OS_WIN32
1407                         win32_close_log();
1408 #endif
1409                         exit(1);
1410                 }
1411                 main_window_reflect_prefs_all_now();
1412                 folder_write_list();
1413         }
1414
1415         if (!account_get_list()) {
1416                 prefs_destroy_cache();
1417                 if (!run_wizard(mainwin, FALSE)) {
1418                         if (asked_for_migration)
1419                                 remove_dir_recursive(RC_DIR);
1420 #ifdef G_OS_WIN32
1421                         win32_close_log();
1422 #endif
1423                         exit(1);
1424                 }
1425                 if(!account_get_list()) {
1426                         exit_claws(mainwin);
1427 #ifdef G_OS_WIN32
1428                         win32_close_log();
1429 #endif
1430                         exit(1);
1431                 }
1432         }
1433
1434         
1435         toolbar_main_set_sensitive(mainwin);
1436         main_window_set_menu_sensitive(mainwin);
1437
1438         /* if crashed, show window early so that the user
1439          * sees what's happening */
1440         if (claws_crashed())
1441                 main_window_popup(mainwin);
1442
1443 #ifdef USE_GNUTLS
1444         gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
1445 #endif
1446
1447 #ifdef HAVE_LIBETPAN
1448         imap_main_init(prefs_common.skip_ssl_cert_check);
1449         imap_main_set_timeout(prefs_common.io_timeout_secs);
1450         nntp_main_init(prefs_common.skip_ssl_cert_check);
1451 #endif  
1452         account_set_missing_folder();
1453         folder_set_missing_folders();
1454         folderview_set(folderview);
1455
1456         prefs_matcher_read_config();
1457
1458         /* make one all-folder processing before using claws */
1459         main_window_cursor_wait(mainwin);
1460         folder_func_to_all_folders(initial_processing, (gpointer *)mainwin);
1461
1462         /* if claws crashed, rebuild caches */
1463         if (claws_crashed()) {
1464                 GTK_EVENTS_FLUSH();
1465                 debug_print("Claws Mail crashed, checking for new messages in local folders\n");
1466                 folder_item_update_thaw();
1467                 folderview_check_new(NULL);
1468                 folder_clean_cache_memory_force();
1469                 folder_item_update_freeze();
1470         }
1471         /* make the crash-indicator file */
1472         str_write_to_file("foo", get_crashfile_name());
1473
1474         inc_autocheck_timer_init(mainwin);
1475
1476         /* ignore SIGPIPE signal for preventing sudden death of program */
1477 #ifdef G_OS_UNIX
1478         signal(SIGPIPE, SIG_IGN);
1479 #endif
1480         if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
1481                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
1482         }
1483         if (cmd.online_mode == ONLINE_MODE_ONLINE) {
1484                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
1485         }
1486
1487         if (cmd.status_folders) {
1488                 g_ptr_array_free(cmd.status_folders, TRUE);
1489                 cmd.status_folders = NULL;
1490         }
1491         if (cmd.status_full_folders) {
1492                 g_ptr_array_free(cmd.status_full_folders, TRUE);
1493                 cmd.status_full_folders = NULL;
1494         }
1495
1496         claws_register_idle_function(claws_gtk_idle);
1497
1498         prefs_toolbar_init();
1499
1500         num_folder_class = g_list_length(folder_get_list());
1501
1502         plugin_load_all("GTK2");
1503
1504         if (g_list_length(folder_get_list()) != num_folder_class) {
1505                 debug_print("new folders loaded, reloading processing rules\n");
1506                 prefs_matcher_read_config();
1507         }
1508         
1509         if (plugin_get_unloaded_list() != NULL) {
1510                 main_window_cursor_normal(mainwin);
1511                 alertpanel_warning(_("Some plugin(s) failed to load. "
1512                                      "Check the Plugins configuration "
1513                                      "for more information."));
1514                 main_window_cursor_wait(mainwin);
1515         }
1516
1517         plugin_load_standard_plugins ();
1518       
1519         /* if not crashed, show window now */
1520         if (!claws_crashed()) {
1521                 /* apart if something told not to show */
1522                 if (show_at_startup)
1523                         main_window_popup(mainwin);
1524         }
1525
1526         if (!folder_have_mailbox()) {
1527                 prefs_destroy_cache();
1528                 main_window_cursor_normal(mainwin);
1529                 if (folder_get_list() != NULL) {
1530                         alertpanel_error(_("Claws Mail has detected a configured "
1531                                    "mailbox, but it is incomplete. It is "
1532                                    "possibly due to a failing IMAP account. Use "
1533                                    "\"Rebuild folder tree\" on the mailbox parent "
1534                                    "folder's context menu to try to fix it."));
1535                 } else {
1536                         alertpanel_error(_("Claws Mail has detected a configured "
1537                                    "mailbox, but could not load it. It is "
1538                                    "probably provided by an out-of-date "
1539                                    "external plugin. Please reinstall the "
1540                                    "plugin and try again."));
1541                         exit_claws(mainwin);
1542 #ifdef G_OS_WIN32
1543                         win32_close_log();
1544 #endif
1545                         exit(1);
1546                 }
1547         }
1548         
1549         static_mainwindow = mainwin;
1550
1551 #ifdef MAEMO
1552         if (prefs_common.data_root != NULL && *prefs_common.data_root != '\0') {
1553                 GnomeVFSVolume *vol = NULL;
1554                 gchar *uri, *mount_path;
1555
1556                 volmon = gnome_vfs_get_volume_monitor();
1557                 vol = gnome_vfs_volume_monitor_get_volume_for_path(volmon, prefs_common.data_root);
1558
1559                 uri = gnome_vfs_volume_get_activation_uri (vol);
1560                 mount_path = uri?gnome_vfs_get_local_path_from_uri (uri):NULL;
1561                 g_free(uri);
1562
1563                 if (vol == NULL || !gnome_vfs_volume_is_mounted(vol) 
1564                     || strcmp(mount_path, prefs_common.data_root)) {
1565                         alertpanel_error(_("Claws Mail can not start without its data volume (%s)."), 
1566                                 prefs_common.data_root);
1567                         g_free(mount_path);
1568                         gnome_vfs_volume_unref(vol);
1569                         exit_claws(mainwin);
1570                         exit(1);
1571                 }
1572                 g_free(mount_path);
1573                 gnome_vfs_volume_unref(vol);
1574                 g_signal_connect(G_OBJECT(volmon), 
1575                                 "volume-mounted", G_CALLBACK(main_vol_mount_cb), mainwin);
1576                 g_signal_connect(G_OBJECT(volmon), 
1577                                 "volume-unmounted", G_CALLBACK(main_vol_unmount_cb), mainwin);
1578         }
1579 #endif
1580
1581 #ifdef HAVE_STARTUP_NOTIFICATION
1582         startup_notification_complete(FALSE);
1583 #endif
1584 #ifdef HAVE_LIBSM
1585         sc_session_manager_connect(mainwin);
1586 #endif
1587
1588         folder_item_update_thaw();
1589         gtk_cmclist_thaw(GTK_CMCLIST(mainwin->folderview->ctree));
1590         main_window_cursor_normal(mainwin);
1591
1592         if (!cmd.target && prefs_common.goto_last_folder_on_startup &&
1593             folder_find_item_from_identifier(prefs_common.last_opened_folder) != NULL &&
1594             !claws_crashed()) {
1595                 cmd.target = prefs_common.last_opened_folder;
1596         }
1597
1598         if (cmd.receive_all && !cmd.target) {
1599                 start_done = FALSE;
1600                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(FALSE));
1601         } else if (prefs_common.chk_on_startup && !cmd.target) {
1602                 start_done = FALSE;
1603                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(TRUE));
1604         } else if (cmd.receive && !cmd.target) {
1605                 start_done = FALSE;
1606                 g_timeout_add(1000, defer_check, NULL);
1607         } 
1608         gtk_widget_grab_focus(folderview->ctree);
1609
1610         if (cmd.compose) {
1611                 open_compose_new(cmd.compose_mailto, cmd.attach_files);
1612         }
1613         if (cmd.attach_files) {
1614                 ptr_array_free_strings(cmd.attach_files);
1615                 g_ptr_array_free(cmd.attach_files, TRUE);
1616                 cmd.attach_files = NULL;
1617         }
1618         if (cmd.subscribe) {
1619                 folder_subscribe(cmd.subscribe_uri);
1620         }
1621
1622         if (cmd.send) {
1623                 send_queue();
1624         }
1625         
1626         if (cmd.target) {
1627                 start_done = FALSE;
1628                 g_timeout_add(500, defer_jump, (gpointer)cmd.target);
1629         }
1630
1631         prefs_destroy_cache();
1632         
1633         compose_reopen_exit_drafts();
1634
1635         if (start_done) {
1636                 sc_starting = FALSE;
1637                 main_window_set_menu_sensitive(mainwin);
1638                 toolbar_main_set_sensitive(mainwin);
1639         }
1640         END_TIMING();
1641
1642         gtk_main();
1643
1644 #ifdef MAEMO
1645         osso_deinitialize(osso_context);
1646 #endif
1647 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1648         if(nm_proxy)
1649                 g_object_unref(nm_proxy);
1650 #endif
1651 #ifdef HAVE_DBUS_GLIB
1652         uninstall_dbus_status_handler();
1653         if(connection)
1654                 dbus_g_connection_unref(connection);
1655 #endif
1656 #ifdef G_OS_WIN32
1657         win32_close_log();
1658 #endif
1659         utils_free_regex();
1660         exit_claws(mainwin);
1661
1662         return 0;
1663 }
1664
1665 static void save_all_caches(FolderItem *item, gpointer data)
1666 {
1667         if (!item->cache) {
1668                 return;
1669         }
1670
1671         if (item->opened) {
1672                 folder_item_close(item);
1673         }
1674
1675         folder_item_free_cache(item, TRUE);
1676 }
1677
1678 static void exit_claws(MainWindow *mainwin)
1679 {
1680         gchar *filename;
1681
1682         sc_exiting = TRUE;
1683
1684         debug_print("shutting down\n");
1685         inc_autocheck_timer_remove();
1686
1687 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1688         if (prefs_common.work_offline && went_offline_nm)
1689                 prefs_common.work_offline = FALSE;
1690 #endif
1691
1692         /* save prefs for opened folder */
1693         if(mainwin->folderview->opened) {
1694                 FolderItem *item;
1695
1696                 item = gtk_cmctree_node_get_row_data(GTK_CMCTREE(mainwin->folderview->ctree), mainwin->folderview->opened);
1697                 summary_save_prefs_to_folderitem(mainwin->folderview->summaryview, item);
1698                 prefs_common.last_opened_folder = folder_item_get_identifier(item);
1699         }
1700
1701         /* save all state before exiting */
1702         folder_func_to_all_folders(save_all_caches, NULL);
1703         folder_write_list();
1704
1705         main_window_get_size(mainwin);
1706         main_window_get_position(mainwin);
1707
1708         prefs_common_write_config();
1709         account_write_config_all();
1710         addressbook_export_to_file();
1711
1712         filename = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
1713         gtk_accel_map_save(filename);
1714         g_free(filename);
1715
1716         /* delete temporary files */
1717         remove_all_files(get_tmp_dir());
1718         remove_all_files(get_mime_tmp_dir());
1719
1720         close_log_file(LOG_PROTOCOL);
1721         close_log_file(LOG_DEBUG_FILTERING);
1722
1723 #ifdef HAVE_LIBETPAN
1724         imap_main_done();
1725         nntp_main_done();
1726 #endif
1727         /* delete crashfile */
1728         if (!cmd.crash)
1729                 claws_unlink(get_crashfile_name());
1730
1731         lock_socket_remove();
1732
1733 #ifdef HAVE_LIBSM
1734         if (mainwin->smc_conn)
1735                 SmcCloseConnection ((SmcConn)mainwin->smc_conn, 0, NULL);
1736         mainwin->smc_conn = NULL;
1737 #endif
1738
1739         main_window_destroy_all();
1740         
1741         plugin_unload_all("GTK2");
1742
1743         prefs_toolbar_done();
1744
1745         addressbook_destroy();
1746
1747         prefs_themes_done();
1748         prefs_fonts_done();
1749         prefs_ext_prog_done();
1750         prefs_wrapping_done();
1751         prefs_compose_writing_done();
1752         prefs_msg_colors_done();
1753         prefs_image_viewer_done();
1754         image_viewer_done();
1755         prefs_quote_done();
1756         prefs_summaries_done();
1757         prefs_message_done();
1758         prefs_other_done();
1759         prefs_receive_done();
1760         prefs_logging_done();
1761         prefs_send_done();
1762         tags_write_tags();
1763 #ifdef USE_ASPELL       
1764         prefs_spelling_done();
1765         gtkaspell_checkers_quit();
1766 #endif
1767         plugin_unload_all("Common");
1768         claws_done();
1769 }
1770
1771 static void parse_cmd_opt(int argc, char *argv[])
1772 {
1773         gint i;
1774
1775         for (i = 1; i < argc; i++) {
1776                 if (!strncmp(argv[i], "--receive-all", 13)) {
1777                         cmd.receive_all = TRUE;
1778                 } else if (!strncmp(argv[i], "--receive", 9)) {
1779                         cmd.receive = TRUE;
1780                 } else if (!strncmp(argv[i], "--compose", 9)) {
1781                         const gchar *p = argv[i + 1];
1782
1783                         cmd.compose = TRUE;
1784                         cmd.compose_mailto = NULL;
1785                         if (p && *p != '\0' && *p != '-') {
1786                                 if (!strncmp(p, "mailto:", 7)) {
1787                                         cmd.compose_mailto = p + 7;
1788                                 } else {
1789                                         cmd.compose_mailto = p;
1790                                 }
1791                                 i++;
1792                         }
1793                 } else if (!strncmp(argv[i], "--subscribe", 11)) {
1794                         const gchar *p = argv[i + 1];
1795                         if (p && *p != '\0' && *p != '-') {
1796                                 cmd.subscribe = TRUE;
1797                                 cmd.subscribe_uri = p;
1798                         }
1799                 } else if (!strncmp(argv[i], "--attach", 8)) {
1800                         const gchar *p = argv[i + 1];
1801                         gchar *file = NULL;
1802
1803                         while (p && *p != '\0' && *p != '-') {
1804                                 if (!cmd.attach_files) {
1805                                         cmd.attach_files = g_ptr_array_new();
1806                                 }
1807                                 if ((file = g_filename_from_uri(p, NULL, NULL)) != NULL) {
1808                                         if (!is_file_exist(file)) {
1809                                                 g_free(file);
1810                                                 file = NULL;
1811                                         }
1812                                 }
1813                                 if (file == NULL && *p != G_DIR_SEPARATOR) {
1814                                         file = g_strconcat(claws_get_startup_dir(),
1815                                                            G_DIR_SEPARATOR_S,
1816                                                            p, NULL);
1817                                 } else if (file == NULL) {
1818                                         file = g_strdup(p);
1819                                 }
1820                                 g_ptr_array_add(cmd.attach_files, file);
1821                                 i++;
1822                                 p = argv[i + 1];
1823                         }
1824                 } else if (!strncmp(argv[i], "--send", 6)) {
1825                         cmd.send = TRUE;
1826                 } else if (!strncmp(argv[i], "--version-full", 14) ||
1827                            !strncmp(argv[i], "-V", 2)) {
1828                         g_print("Claws Mail version " VERSION "\n");
1829                         main_dump_features_list(FALSE);
1830                         exit(0);
1831                 } else if (!strncmp(argv[i], "--version", 9) ||
1832                            !strncmp(argv[i], "-v", 2)) {
1833                         g_print("Claws Mail version " VERSION "\n");
1834                         exit(0);
1835                 } else if (!strncmp(argv[i], "--status-full", 13)) {
1836                         const gchar *p = argv[i + 1];
1837  
1838                         cmd.status_full = TRUE;
1839                         while (p && *p != '\0' && *p != '-') {
1840                                 if (!cmd.status_full_folders) {
1841                                         cmd.status_full_folders =
1842                                                 g_ptr_array_new();
1843                                 }
1844                                 g_ptr_array_add(cmd.status_full_folders,
1845                                                 g_strdup(p));
1846                                 i++;
1847                                 p = argv[i + 1];
1848                         }
1849                 } else if (!strncmp(argv[i], "--status", 8)) {
1850                         const gchar *p = argv[i + 1];
1851  
1852                         cmd.status = TRUE;
1853                         while (p && *p != '\0' && *p != '-') {
1854                                 if (!cmd.status_folders)
1855                                         cmd.status_folders = g_ptr_array_new();
1856                                 g_ptr_array_add(cmd.status_folders,
1857                                                 g_strdup(p));
1858                                 i++;
1859                                 p = argv[i + 1];
1860                         }
1861                 } else if (!strncmp(argv[i], "--online", 8)) {
1862                         cmd.online_mode = ONLINE_MODE_ONLINE;
1863                 } else if (!strncmp(argv[i], "--offline", 9)) {
1864                         cmd.online_mode = ONLINE_MODE_OFFLINE;
1865                 } else if (!strncmp(argv[i], "--help", 6) ||
1866                            !strncmp(argv[i], "-h", 2)) {
1867                         gchar *base = g_path_get_basename(argv[0]);
1868                         g_print(_("Usage: %s [OPTION]...\n"), base);
1869
1870                         g_print("%s\n", _("  --compose [address]    open composition window"));
1871                         g_print("%s\n", _("  --subscribe [uri]      subscribe to the given URI if possible"));
1872                         g_print("%s\n", _("  --attach file1 [file2]...\n"
1873                                   "                         open composition window with specified files\n"
1874                                   "                         attached"));
1875                         g_print("%s\n", _("  --receive              receive new messages"));
1876                         g_print("%s\n", _("  --receive-all          receive new messages of all accounts"));
1877                         g_print("%s\n", _("  --send                 send all queued messages"));
1878                         g_print("%s\n", _("  --status [folder]...   show the total number of messages"));
1879                         g_print("%s\n", _("  --status-full [folder]...\n"
1880                                           "                         show the status of each folder"));
1881                         g_print("%s\n", _("  --select folder[/msg]  jumps to the specified folder/message\n" 
1882                                           "                         folder is a folder id like 'folder/sub_folder'"));
1883                         g_print("%s\n", _("  --online               switch to online mode"));
1884                         g_print("%s\n", _("  --offline              switch to offline mode"));
1885                         g_print("%s\n", _("  --exit --quit -q       exit Claws Mail"));
1886                         g_print("%s\n", _("  --debug                debug mode"));
1887                         g_print("%s\n", _("  --help -h              display this help and exit"));
1888                         g_print("%s\n", _("  --version -v           output version information and exit"));
1889                         g_print("%s\n", _("  --version-full -V      output version and built-in features information and exit"));
1890                         g_print("%s\n", _("  --config-dir           output configuration directory"));
1891                         g_print("%s\n", _("  --alternate-config-dir [dir]\n"
1892                                           "                         use specified configuration directory"));
1893
1894                         g_free(base);
1895                         exit(1);
1896                 } else if (!strncmp(argv[i], "--crash", 7)) {
1897                         cmd.crash = TRUE;
1898                         cmd.crash_params = g_strdup(argv[i + 1]);
1899                         i++;
1900                 } else if (!strncmp(argv[i], "--config-dir", sizeof "--config-dir" - 1)) {
1901                         g_print(RC_DIR "\n");
1902                         exit(0);
1903                 } else if (!strncmp(argv[i], "--alternate-config-dir", sizeof "--alternate-config-dir" - 1) && i+1 < argc) {
1904                         set_rc_dir(argv[i+1]);
1905                 } else if (!strncmp(argv[i], "--exit", 6) ||
1906                            !strncmp(argv[i], "--quit", 6) ||
1907                            !strncmp(argv[i], "-q", 2)) {
1908                         cmd.exit = TRUE;
1909                 } else if (!strncmp(argv[i], "--select", 8) && i+1 < argc) {
1910                         cmd.target = argv[i+1];
1911                 } else if (i == 1 && argc == 2) {
1912                         /* only one parameter. Do something intelligent about it */
1913                         if ((strstr(argv[i], "@")||!strncmp(argv[i], "mailto:", 7)) && !strstr(argv[i], "://")) {
1914                                 const gchar *p = argv[i];
1915
1916                                 cmd.compose = TRUE;
1917                                 cmd.compose_mailto = NULL;
1918                                 if (p && *p != '\0' && *p != '-') {
1919                                         if (!strncmp(p, "mailto:", 7)) {
1920                                                 cmd.compose_mailto = p + 7;
1921                                         } else {
1922                                                 cmd.compose_mailto = p;
1923                                         }
1924                                 }
1925                         } else if (!strncmp(argv[i], "file://", 7)) {
1926                                 cmd.target = argv[i];
1927                         } else if (!strncmp(argv[i], "?attach=file://", strlen("?attach=file://"))) {
1928                                 cmd.compose = TRUE;
1929                                 cmd.compose_mailto = argv[i];
1930                         } else if (strstr(argv[i], "://")) {
1931                                 const gchar *p = argv[i];
1932                                 if (p && *p != '\0' && *p != '-') {
1933                                         cmd.subscribe = TRUE;
1934                                         cmd.subscribe_uri = p;
1935                                 }
1936                         } else if (!strcmp(argv[i], "--sync")) {
1937                                 /* gtk debug */
1938                         } else if (is_dir_exist(argv[i]) || is_file_exist(argv[i])) {
1939                                 cmd.target = argv[i];
1940                         } else {
1941                                 g_print(_("Unknown option\n"));
1942                                 exit(1);
1943                         }
1944                 }
1945         }
1946
1947         if (cmd.attach_files && cmd.compose == FALSE) {
1948                 cmd.compose = TRUE;
1949                 cmd.compose_mailto = NULL;
1950         }
1951 }
1952
1953 static void initial_processing(FolderItem *item, gpointer data)
1954 {
1955         MainWindow *mainwin = (MainWindow *)data;
1956         gchar *buf;
1957
1958         g_return_if_fail(item);
1959         buf = g_strdup_printf(_("Processing (%s)..."), 
1960                               item->path 
1961                               ? item->path 
1962                               : _("top level folder"));
1963         g_free(buf);
1964
1965         
1966         if (item->prefs->enable_processing) {
1967                 item->processing_pending = TRUE;
1968                 folder_item_apply_processing(item);
1969                 item->processing_pending = FALSE;
1970         }
1971
1972         STATUSBAR_POP(mainwin);
1973 }
1974
1975 static gboolean draft_all_messages(void)
1976 {
1977         GList *compose_list = NULL;
1978         
1979         compose_clear_exit_drafts();
1980         compose_list = compose_get_compose_list();
1981         while (compose_list != NULL) {
1982                 Compose *c = (Compose*)compose_list->data;
1983                 if (!compose_draft(c, COMPOSE_DRAFT_FOR_EXIT))
1984                         return FALSE;
1985                 compose_list = compose_get_compose_list();
1986         }
1987         return TRUE;
1988 }
1989 gboolean clean_quit(gpointer data)
1990 {
1991         static gboolean firstrun = TRUE;
1992
1993         if (!firstrun) {
1994                 return FALSE;
1995         }
1996         firstrun = FALSE;
1997
1998         /*!< Good idea to have the main window stored in a 
1999          *   static variable so we can check that variable
2000          *   to see if we're really allowed to do things
2001          *   that actually the spawner is supposed to 
2002          *   do (like: sending mail, composing messages).
2003          *   Because, really, if we're the spawnee, and
2004          *   we touch GTK stuff, we're hosed. See the 
2005          *   next fixme. */
2006
2007         /* FIXME: Use something else to signal that we're
2008          * in the original spawner, and not in a spawned
2009          * child. */
2010         if (!static_mainwindow) {
2011                 return FALSE;
2012         }
2013                 
2014         draft_all_messages();
2015         emergency_exit = TRUE;
2016         exit_claws(static_mainwindow);
2017         exit(0);
2018
2019         return FALSE;
2020 }
2021
2022 void app_will_exit(GtkWidget *widget, gpointer data)
2023 {
2024         MainWindow *mainwin = data;
2025         
2026         if (gtk_main_level() == 0) {
2027                 debug_print("not even started\n");
2028                 return;
2029         }
2030         if (sc_exiting == TRUE) {
2031                 debug_print("exit pending\n");
2032                 return;
2033         }
2034         sc_exiting = TRUE;
2035         debug_print("exiting\n");
2036         if (compose_get_compose_list()) {
2037                 if (!draft_all_messages()) {
2038                         main_window_popup(mainwin);
2039                         sc_exiting = FALSE;
2040                         return;
2041                 }
2042         }
2043
2044         if (prefs_common.warn_queued_on_exit && procmsg_have_queued_mails_fast()) {
2045                 if (alertpanel(_("Queued messages"),
2046                                _("Some unsent messages are queued. Exit now?"),
2047                                GTK_STOCK_CANCEL, GTK_STOCK_OK, NULL)
2048                     != G_ALERTALTERNATE) {
2049                         main_window_popup(mainwin);
2050                         sc_exiting = FALSE;
2051                         return;
2052                 }
2053                 manage_window_focus_in(mainwin->window, NULL, NULL);
2054         }
2055
2056         sock_cleanup();
2057 #ifdef HAVE_VALGRIND
2058         if (RUNNING_ON_VALGRIND) {
2059                 summary_clear_list(mainwin->summaryview);
2060         }
2061 #endif
2062         if (folderview_get_selected_item(mainwin->folderview))
2063                 folder_item_close(folderview_get_selected_item(mainwin->folderview));
2064         gtk_main_quit();
2065 }
2066
2067 gboolean claws_is_exiting(void)
2068 {
2069         return sc_exiting;
2070 }
2071
2072 gboolean claws_is_starting(void)
2073 {
2074         return sc_starting;
2075 }
2076
2077 /*
2078  * CLAWS: want this public so crash dialog can delete the
2079  * lock file too
2080  */
2081 gchar *claws_get_socket_name(void)
2082 {
2083         static gchar *filename = NULL;
2084         const gchar *socket_dir = NULL;
2085         
2086         if (rc_dir_is_alt())
2087                 socket_dir = get_rc_dir();
2088         else
2089                 socket_dir = g_get_tmp_dir();
2090         if (filename == NULL) {
2091                 filename = g_strdup_printf("%s%cclaws-mail-%d",
2092                                            socket_dir, G_DIR_SEPARATOR,
2093 #if HAVE_GETUID
2094                                            getuid());
2095 #else
2096                                            0);                                          
2097 #endif
2098         }
2099
2100         return filename;
2101 }
2102
2103 static gchar *get_crashfile_name(void)
2104 {
2105         static gchar *filename = NULL;
2106
2107         if (filename == NULL) {
2108                 filename = g_strdup_printf("%s%cclaws-crashed",
2109                                            get_tmp_dir(), G_DIR_SEPARATOR);
2110         }
2111
2112         return filename;
2113 }
2114
2115 static gint prohibit_duplicate_launch(void)
2116 {
2117         gint uxsock;
2118         gchar *path;
2119
2120         path = claws_get_socket_name();
2121         uxsock = fd_connect_unix(path);
2122         
2123         if (x_display == NULL)
2124                 x_display = g_strdup(g_getenv("DISPLAY"));
2125
2126         if (uxsock < 0) {
2127                 claws_unlink(path);
2128                 return fd_open_unix(path);
2129         }
2130
2131         /* remote command mode */
2132
2133         debug_print("another Claws Mail instance is already running.\n");
2134
2135         if (cmd.receive_all) {
2136                 fd_write_all(uxsock, "receive_all\n", 12);
2137         } else if (cmd.receive) {
2138                 fd_write_all(uxsock, "receive\n", 8);
2139         } else if (cmd.compose && cmd.attach_files) {
2140                 gchar *str, *compose_str;
2141                 gint i;
2142
2143                 if (cmd.compose_mailto) {
2144                         compose_str = g_strdup_printf("compose_attach %s\n",
2145                                                       cmd.compose_mailto);
2146                 } else {
2147                         compose_str = g_strdup("compose_attach\n");
2148                 }
2149
2150                 fd_write_all(uxsock, compose_str, strlen(compose_str));
2151                 g_free(compose_str);
2152
2153                 for (i = 0; i < cmd.attach_files->len; i++) {
2154                         str = g_ptr_array_index(cmd.attach_files, i);
2155                         fd_write_all(uxsock, str, strlen(str));
2156                         fd_write_all(uxsock, "\n", 1);
2157                 }
2158
2159                 fd_write_all(uxsock, ".\n", 2);
2160         } else if (cmd.compose) {
2161                 gchar *compose_str;
2162
2163                 if (cmd.compose_mailto) {
2164                         compose_str = g_strdup_printf
2165                                 ("compose %s\n", cmd.compose_mailto);
2166                 } else {
2167                         compose_str = g_strdup("compose\n");
2168                 }
2169
2170                 fd_write_all(uxsock, compose_str, strlen(compose_str));
2171                 g_free(compose_str);
2172         } else if (cmd.subscribe) {
2173                 gchar *str = g_strdup_printf("subscribe %s\n", cmd.subscribe_uri);
2174                 fd_write_all(uxsock, str, strlen(str));
2175                 g_free(str);
2176         } else if (cmd.send) {
2177                 fd_write_all(uxsock, "send\n", 5);
2178         } else if (cmd.online_mode == ONLINE_MODE_ONLINE) {
2179                 fd_write(uxsock, "online\n", 6);
2180         } else if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
2181                 fd_write(uxsock, "offline\n", 7);
2182         } else if (cmd.status || cmd.status_full) {
2183                 gchar buf[BUFFSIZE];
2184                 gint i;
2185                 const gchar *command;
2186                 GPtrArray *folders;
2187                 gchar *folder;
2188  
2189                 command = cmd.status_full ? "status-full\n" : "status\n";
2190                 folders = cmd.status_full ? cmd.status_full_folders :
2191                         cmd.status_folders;
2192  
2193                 fd_write_all(uxsock, command, strlen(command));
2194                 for (i = 0; folders && i < folders->len; ++i) {
2195                         folder = g_ptr_array_index(folders, i);
2196                         fd_write_all(uxsock, folder, strlen(folder));
2197                         fd_write_all(uxsock, "\n", 1);
2198                 }
2199                 fd_write_all(uxsock, ".\n", 2);
2200                 for (;;) {
2201                         fd_gets(uxsock, buf, sizeof(buf));
2202                         if (!strncmp(buf, ".\n", 2)) break;
2203                         fputs(buf, stdout);
2204                 }
2205         } else if (cmd.exit) {
2206                 fd_write_all(uxsock, "exit\n", 5);
2207         } else if (cmd.target) {
2208                 gchar *str = g_strdup_printf("select %s\n", cmd.target);
2209                 fd_write_all(uxsock, str, strlen(str));
2210                 g_free(str);
2211         } else {
2212                 gchar buf[BUFSIZ];
2213                 fd_write_all(uxsock, "get_display\n", 12);
2214                 memset(buf, 0, sizeof(buf));
2215                 fd_gets(uxsock, buf, sizeof(buf));
2216                 if (strcmp2(buf, x_display)) {
2217                         g_print("Claws Mail is already running on display %s.\n",
2218                                 buf);
2219                 } else {
2220                         fd_close(uxsock);
2221                         uxsock = fd_connect_unix(path);
2222                         fd_write_all(uxsock, "popup\n", 6);
2223                 }
2224         }
2225
2226         fd_close(uxsock);
2227         return -1;
2228 }
2229
2230 static gint lock_socket_remove(void)
2231 {
2232 #ifdef G_OS_UNIX
2233         gchar *filename;
2234
2235         if (lock_socket < 0) {
2236                 return -1;
2237         }
2238
2239         if (lock_socket_tag > 0) {
2240                 g_source_remove(lock_socket_tag);
2241         }
2242         fd_close(lock_socket);
2243         filename = claws_get_socket_name();
2244         claws_unlink(filename);
2245 #endif
2246
2247         return 0;
2248 }
2249
2250 static GPtrArray *get_folder_item_list(gint sock)
2251 {
2252         gchar buf[BUFFSIZE];
2253         FolderItem *item;
2254         GPtrArray *folders = NULL;
2255
2256         for (;;) {
2257                 fd_gets(sock, buf, sizeof(buf));
2258                 if (!strncmp(buf, ".\n", 2)) {
2259                         break;
2260                 }
2261                 strretchomp(buf);
2262                 if (!folders) {
2263                         folders = g_ptr_array_new();
2264                 }
2265                 item = folder_find_item_from_identifier(buf);
2266                 if (item) {
2267                         g_ptr_array_add(folders, item);
2268                 } else {
2269                         g_warning("no such folder: %s\n", buf);
2270                 }
2271         }
2272
2273         return folders;
2274 }
2275
2276 static void lock_socket_input_cb(gpointer data,
2277                                  gint source,
2278                                  GdkInputCondition condition)
2279 {
2280         MainWindow *mainwin = (MainWindow *)data;
2281         gint sock;
2282         gchar buf[BUFFSIZE];
2283
2284         sock = fd_accept(source);
2285         fd_gets(sock, buf, sizeof(buf));
2286
2287         if (!strncmp(buf, "popup", 5)) {
2288                 main_window_popup(mainwin);
2289         } else if (!strncmp(buf, "get_display", 11)) {
2290                 fd_write_all(sock, x_display, strlen(x_display));
2291         } else if (!strncmp(buf, "receive_all", 11)) {
2292                 inc_all_account_mail(mainwin, FALSE,
2293                                      prefs_common.newmail_notify_manu);
2294         } else if (!strncmp(buf, "receive", 7)) {
2295                 inc_mail(mainwin, prefs_common.newmail_notify_manu);
2296         } else if (!strncmp(buf, "compose_attach", 14)) {
2297                 GPtrArray *files;
2298                 gchar *mailto;
2299
2300                 mailto = g_strdup(buf + strlen("compose_attach") + 1);
2301                 files = g_ptr_array_new();
2302                 while (fd_gets(sock, buf, sizeof(buf)) > 0) {
2303                         if (buf[0] == '.' && buf[1] == '\n') {
2304                                 break;
2305                         }
2306                         strretchomp(buf);
2307                         g_ptr_array_add(files, g_strdup(buf));
2308                 }
2309                 open_compose_new(mailto, files);
2310                 ptr_array_free_strings(files);
2311                 g_ptr_array_free(files, TRUE);
2312                 g_free(mailto);
2313         } else if (!strncmp(buf, "compose", 7)) {
2314                 open_compose_new(buf + strlen("compose") + 1, NULL);
2315         } else if (!strncmp(buf, "subscribe", 9)) {
2316                 main_window_popup(mainwin);
2317                 folder_subscribe(buf + strlen("subscribe") + 1);
2318         } else if (!strncmp(buf, "send", 4)) {
2319                 send_queue();
2320         } else if (!strncmp(buf, "online", 6)) {
2321                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
2322         } else if (!strncmp(buf, "offline", 7)) {
2323                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
2324         } else if (!strncmp(buf, "status-full", 11) ||
2325                    !strncmp(buf, "status", 6)) {
2326                 gchar *status;
2327                 GPtrArray *folders;
2328  
2329                 folders = get_folder_item_list(sock);
2330                 status = folder_get_status
2331                         (folders, !strncmp(buf, "status-full", 11));
2332                 fd_write_all(sock, status, strlen(status));
2333                 fd_write_all(sock, ".\n", 2);
2334                 g_free(status);
2335                 if (folders) g_ptr_array_free(folders, TRUE);
2336         } else if (!strncmp(buf, "select ", 7)) {
2337                 const gchar *target = buf+7;
2338                 mainwindow_jump_to(target, TRUE);
2339         } else if (!strncmp(buf, "exit", 4)) {
2340                 app_will_exit(NULL, mainwin);
2341         }
2342
2343         fd_close(sock);
2344 }
2345
2346 static void open_compose_new(const gchar *address, GPtrArray *attach_files)
2347 {
2348         gchar *addr = NULL;
2349
2350         if (address) {
2351                 Xstrdup_a(addr, address, return);
2352                 g_strstrip(addr);
2353         }
2354
2355         compose_new(NULL, addr, attach_files);
2356 }
2357
2358 static void send_queue(void)
2359 {
2360         GList *list;
2361         gchar *errstr = NULL;
2362         gboolean error = FALSE;
2363         for (list = folder_get_list(); list != NULL; list = list->next) {
2364                 Folder *folder = list->data;
2365
2366                 if (folder->queue) {
2367                         gint res = procmsg_send_queue
2368                                 (folder->queue, prefs_common.savemsg,
2369                                 &errstr);
2370
2371                         if (res) {
2372                                 folder_item_scan(folder->queue);
2373                         }
2374                         
2375                         if (res < 0)
2376                                 error = TRUE;
2377                 }
2378         }
2379         if (errstr) {
2380                 alertpanel_error_log(_("Some errors occurred "
2381                                 "while sending queued messages:\n%s"), errstr);
2382                 g_free(errstr);
2383         } else if (error) {
2384                 alertpanel_error_log("Some errors occurred "
2385                                 "while sending queued messages.");
2386         }
2387 }
2388
2389 static void quit_signal_handler(int sig)
2390 {
2391         debug_print("Quitting on signal %d\n", sig);
2392
2393         g_timeout_add(0, clean_quit, NULL);
2394 }
2395
2396 static void install_basic_sighandlers()
2397 {
2398 #ifndef G_OS_WIN32
2399         sigset_t    mask;
2400         struct sigaction act;
2401
2402         sigemptyset(&mask);
2403
2404 #ifdef SIGTERM
2405         sigaddset(&mask, SIGTERM);
2406 #endif
2407 #ifdef SIGINT
2408         sigaddset(&mask, SIGINT);
2409 #endif
2410 #ifdef SIGHUP
2411         sigaddset(&mask, SIGHUP);
2412 #endif
2413
2414         act.sa_handler = quit_signal_handler;
2415         act.sa_mask    = mask;
2416         act.sa_flags   = 0;
2417
2418 #ifdef SIGTERM
2419         sigaction(SIGTERM, &act, 0);
2420 #endif
2421 #ifdef SIGINT
2422         sigaction(SIGINT, &act, 0);
2423 #endif  
2424 #ifdef SIGHUP
2425         sigaction(SIGHUP, &act, 0);
2426 #endif  
2427
2428         sigprocmask(SIG_UNBLOCK, &mask, 0);
2429 #endif /* !G_OS_WIN32 */
2430 }
2431
2432 #if (defined linux && defined SIGIO)
2433 static int mem_notify_fd = 0;
2434
2435 static gboolean clean_caches(gpointer unused)
2436 {
2437         if (static_mainwindow && static_mainwindow->lock_count > 0)
2438                 return TRUE;
2439         debug_print("/dev/mem_notify: callback: Freeing some memory now!\n");
2440         folder_clean_cache_memory_force();
2441         return FALSE;
2442 }
2443
2444 static void memory_signal_handler(int sig)
2445 {
2446         debug_print("/dev/mem_notify: Kernel says we should free up some memory!\n");
2447         g_timeout_add(10, clean_caches, NULL); 
2448 }
2449
2450 static void install_memory_sighandler()
2451 {
2452         sigset_t    mask;
2453         struct sigaction act;
2454         int flags;
2455
2456         mem_notify_fd = open("/dev/mem_notify", O_RDONLY|O_NONBLOCK);
2457         if (mem_notify_fd == -1) {
2458                 debug_print("/dev/mem_notify not available (%s)\n", 
2459                         strerror(errno));
2460                 return;
2461         }
2462         
2463         fcntl(mem_notify_fd, F_SETOWN, getpid());
2464         flags = fcntl(mem_notify_fd, F_GETFL);
2465         fcntl(mem_notify_fd, flags|FASYNC);
2466
2467         sigemptyset(&mask);
2468
2469         sigaddset(&mask, SIGIO);
2470
2471         act.sa_handler = memory_signal_handler;
2472         act.sa_mask    = mask;
2473         act.sa_flags   = 0;
2474
2475         sigaction(SIGIO, &act, 0);
2476
2477         sigprocmask(SIG_UNBLOCK, &mask, 0);
2478
2479         debug_print("/dev/mem_notify: installed handler\n");
2480 }
2481 #endif /* linux && SIGIO */
2482
2483 #ifdef MAEMO
2484 osso_context_t *get_osso_context(void)
2485 {
2486         return static_osso_context;
2487 }
2488 #endif
2489
2490
2491 #ifdef HAVE_NETWORKMANAGER_SUPPORT
2492 static void networkmanager_state_change_cb(DBusGProxy *proxy, gchar *dev,
2493                                          gpointer data)
2494 {
2495         MainWindow *mainWin;
2496
2497         mainWin = NULL;
2498         if (static_mainwindow)
2499                 mainWin = static_mainwindow;
2500         else if (data)
2501                 mainWin = (MainWindow*)data;
2502         
2503         if (!prefs_common.use_networkmanager)
2504                 return;
2505
2506         if (mainWin) {
2507                 GError *error;
2508                 gboolean online;
2509
2510                 error = NULL;           
2511                 online = networkmanager_is_online(&error);
2512                 if(!error) {
2513                         if(online && went_offline_nm) {
2514                                 went_offline_nm = FALSE;
2515                                 main_window_toggle_work_offline(mainWin, FALSE, FALSE);
2516                                 debug_print("NetworkManager: Went online\n");
2517                                 log_message(LOG_PROTOCOL, _("NetworkManager: network is online.\n"));
2518                         }
2519                         else if(!online) {
2520                                 went_offline_nm = TRUE;
2521                                 main_window_toggle_work_offline(mainWin, TRUE, FALSE);
2522                                 debug_print("NetworkManager: Went offline\n");
2523                                 log_message(LOG_PROTOCOL, _("NetworkManager: network is offline.\n"));
2524                         }
2525                 }
2526                 else {
2527                         debug_print("Failed to get online information from NetworkManager: %s\n",
2528                                                          error->message);
2529                         g_error_free(error);
2530                 }
2531         }
2532         else
2533                 debug_print("NetworkManager: Cannot change connection state because "
2534                                                  "main window does not exist\n");
2535 }
2536
2537 /* Returns true (and sets error appropriately, if given) in case of error */
2538 gboolean networkmanager_is_online(GError **error)
2539 {
2540         DBusGConnection *connection;
2541         DBusGProxy *proxy;
2542         GError *tmp_error = NULL;
2543         gboolean retVal;
2544         guint32 state;
2545
2546         if (!prefs_common.use_networkmanager)
2547                 return TRUE;
2548
2549         tmp_error = NULL;
2550         proxy = NULL;
2551         connection = dbus_g_bus_get(DBUS_BUS_SYSTEM, &tmp_error);
2552
2553         if(!connection) {
2554                 /* If calling code doesn't do error checking, at least print some debug */
2555                 if((error == NULL) || (*error == NULL))
2556                         debug_print("Failed to open connection to system bus: %s\n",
2557                                                          tmp_error->message);
2558                 g_propagate_error(error, tmp_error);
2559                 return TRUE;
2560         }
2561
2562         proxy = dbus_g_proxy_new_for_name(connection,
2563                         "org.freedesktop.NetworkManager",
2564                         "/org/freedesktop/NetworkManager",
2565                         "org.freedesktop.NetworkManager");
2566
2567         retVal = dbus_g_proxy_call(proxy,"state",&tmp_error, G_TYPE_INVALID,
2568                         G_TYPE_UINT, &state, G_TYPE_INVALID);
2569
2570         if(proxy)
2571                 g_object_unref(proxy);
2572         if(connection)
2573                 dbus_g_connection_unref(connection);
2574
2575         if(!retVal) {
2576                 /* If calling code doesn't do error checking, at least print some debug */
2577                 if((error == NULL) || (*error == NULL))
2578                         debug_print("Failed to get state info from NetworkManager: %s\n",
2579                                                          tmp_error->message);
2580                 g_propagate_error(error, tmp_error);
2581                 return TRUE;
2582         }
2583
2584         return (state == NM_STATE_CONNECTED || state == NM_STATE_UNKNOWN);
2585 }
2586 #endif