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