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