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