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