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