2011-07-03 [paul] 3.7.9cvs30
[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_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                 main_window_popup(mainwin);
1540                 alertpanel_warning(ngettext(
1541                                      "The following plugin failed to load. "
1542                                      "Check the Plugins configuration "
1543                                      "for more information:\n%s",
1544                                      "The following plugins failed to load. "
1545                                      "Check the Plugins configuration "
1546                                      "for more information:\n%s", 
1547                                      num_plugins), 
1548                                      list);
1549                 main_window_cursor_wait(mainwin);
1550                 g_free(list);
1551                 g_slist_free(plug_list);
1552         }
1553
1554         if (never_ran) {
1555                 prefs_common_write_config();
1556                 plugin_load_standard_plugins ();
1557         }
1558         /* if not crashed, show window now */
1559         if (!claws_crashed()) {
1560                 /* apart if something told not to show */
1561                 if (show_at_startup)
1562                         main_window_popup(mainwin);
1563         }
1564
1565         if (!folder_have_mailbox()) {
1566                 prefs_destroy_cache();
1567                 main_window_cursor_normal(mainwin);
1568                 if (folder_get_list() != NULL) {
1569                         alertpanel_error(_("Claws Mail has detected a configured "
1570                                    "mailbox, but it is incomplete. It is "
1571                                    "possibly due to a failing IMAP account. Use "
1572                                    "\"Rebuild folder tree\" on the mailbox parent "
1573                                    "folder's context menu to try to fix it."));
1574                 } else {
1575                         alertpanel_error(_("Claws Mail has detected a configured "
1576                                    "mailbox, but could not load it. It is "
1577                                    "probably provided by an out-of-date "
1578                                    "external plugin. Please reinstall the "
1579                                    "plugin and try again."));
1580                         exit_claws(mainwin);
1581 #ifdef G_OS_WIN32
1582                         win32_close_log();
1583 #endif
1584                         exit(1);
1585                 }
1586         }
1587         
1588         static_mainwindow = mainwin;
1589
1590 #ifdef MAEMO
1591         if (prefs_common.data_root != NULL && *prefs_common.data_root != '\0') {
1592                 GnomeVFSVolume *vol = NULL;
1593                 gchar *uri, *mount_path;
1594
1595                 volmon = gnome_vfs_get_volume_monitor();
1596                 vol = gnome_vfs_volume_monitor_get_volume_for_path(volmon, prefs_common.data_root);
1597
1598                 uri = gnome_vfs_volume_get_activation_uri (vol);
1599                 mount_path = uri?gnome_vfs_get_local_path_from_uri (uri):NULL;
1600                 g_free(uri);
1601
1602                 if (vol == NULL || !gnome_vfs_volume_is_mounted(vol) 
1603                     || strcmp(mount_path, prefs_common.data_root)) {
1604                         alertpanel_error(_("Claws Mail can not start without its data volume (%s)."), 
1605                                 prefs_common.data_root);
1606                         g_free(mount_path);
1607                         gnome_vfs_volume_unref(vol);
1608                         exit_claws(mainwin);
1609                         exit(1);
1610                 }
1611                 g_free(mount_path);
1612                 gnome_vfs_volume_unref(vol);
1613                 g_signal_connect(G_OBJECT(volmon), 
1614                                 "volume-mounted", G_CALLBACK(main_vol_mount_cb), mainwin);
1615                 g_signal_connect(G_OBJECT(volmon), 
1616                                 "volume-unmounted", G_CALLBACK(main_vol_unmount_cb), mainwin);
1617         }
1618 #endif
1619
1620 #ifdef HAVE_STARTUP_NOTIFICATION
1621         startup_notification_complete(FALSE);
1622 #endif
1623 #ifdef HAVE_LIBSM
1624         sc_session_manager_connect(mainwin);
1625 #endif
1626
1627         folder_item_update_thaw();
1628         gtk_cmclist_thaw(GTK_CMCLIST(mainwin->folderview->ctree));
1629         main_window_cursor_normal(mainwin);
1630
1631         if (!cmd.target && prefs_common.goto_last_folder_on_startup &&
1632             folder_find_item_from_identifier(prefs_common.last_opened_folder) != NULL &&
1633             !claws_crashed()) {
1634                 cmd.target = prefs_common.last_opened_folder;
1635         }
1636
1637         if (cmd.receive_all && !cmd.target) {
1638                 start_done = FALSE;
1639                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(FALSE));
1640         } else if (prefs_common.chk_on_startup && !cmd.target) {
1641                 start_done = FALSE;
1642                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(TRUE));
1643         } else if (cmd.receive && !cmd.target) {
1644                 start_done = FALSE;
1645                 g_timeout_add(1000, defer_check, NULL);
1646         } 
1647         gtk_widget_grab_focus(folderview->ctree);
1648
1649         if (cmd.compose) {
1650                 open_compose_new(cmd.compose_mailto, cmd.attach_files);
1651         }
1652         if (cmd.attach_files) {
1653                 ptr_array_free_strings(cmd.attach_files);
1654                 g_ptr_array_free(cmd.attach_files, TRUE);
1655                 cmd.attach_files = NULL;
1656         }
1657         if (cmd.subscribe) {
1658                 folder_subscribe(cmd.subscribe_uri);
1659         }
1660
1661         if (cmd.send) {
1662                 send_queue();
1663         }
1664         
1665         if (cmd.target) {
1666                 start_done = FALSE;
1667                 g_timeout_add(500, defer_jump, (gpointer)cmd.target);
1668         }
1669
1670         prefs_destroy_cache();
1671         
1672         compose_reopen_exit_drafts();
1673
1674         if (start_done) {
1675                 sc_starting = FALSE;
1676                 main_window_set_menu_sensitive(mainwin);
1677                 toolbar_main_set_sensitive(mainwin);
1678         }
1679         END_TIMING();
1680
1681         gtk_main();
1682
1683 #ifdef MAEMO
1684         osso_deinitialize(osso_context);
1685 #endif
1686 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1687         if(nm_proxy)
1688                 g_object_unref(nm_proxy);
1689 #endif
1690 #ifdef HAVE_DBUS_GLIB
1691         uninstall_dbus_status_handler();
1692         if(connection)
1693                 dbus_g_connection_unref(connection);
1694 #endif
1695 #ifdef G_OS_WIN32
1696         win32_close_log();
1697 #endif
1698         utils_free_regex();
1699         exit_claws(mainwin);
1700
1701         return 0;
1702 }
1703
1704 static void save_all_caches(FolderItem *item, gpointer data)
1705 {
1706         if (!item->cache) {
1707                 return;
1708         }
1709
1710         if (item->opened) {
1711                 folder_item_close(item);
1712         }
1713
1714         folder_item_free_cache(item, TRUE);
1715 }
1716
1717 static void exit_claws(MainWindow *mainwin)
1718 {
1719         gchar *filename;
1720         gboolean have_connectivity;
1721
1722         sc_exiting = TRUE;
1723
1724         debug_print("shutting down\n");
1725         inc_autocheck_timer_remove();
1726
1727 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1728         if (prefs_common.work_offline && went_offline_nm)
1729                 prefs_common.work_offline = FALSE;
1730 #endif
1731
1732         /* save prefs for opened folder */
1733         if(mainwin->folderview->opened) {
1734                 FolderItem *item;
1735
1736                 item = gtk_cmctree_node_get_row_data(GTK_CMCTREE(mainwin->folderview->ctree), mainwin->folderview->opened);
1737                 summary_save_prefs_to_folderitem(mainwin->folderview->summaryview, item);
1738                 prefs_common.last_opened_folder = folder_item_get_identifier(item);
1739         }
1740
1741         /* save all state before exiting */
1742         folder_func_to_all_folders(save_all_caches, NULL);
1743         folder_write_list();
1744
1745         main_window_get_size(mainwin);
1746         main_window_get_position(mainwin);
1747
1748         prefs_common_write_config();
1749         account_write_config_all();
1750         addressbook_export_to_file();
1751
1752         filename = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
1753         gtk_accel_map_save(filename);
1754         g_free(filename);
1755
1756         /* delete temporary files */
1757         remove_all_files(get_tmp_dir());
1758         remove_all_files(get_mime_tmp_dir());
1759
1760         close_log_file(LOG_PROTOCOL);
1761         close_log_file(LOG_DEBUG_FILTERING);
1762
1763 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1764         have_connectivity = networkmanager_is_online(NULL); 
1765 #else
1766         have_connectivity = TRUE;
1767 #endif
1768 #ifdef HAVE_LIBETPAN
1769         imap_main_done(have_connectivity);
1770         nntp_main_done(have_connectivity);
1771 #endif
1772         /* delete crashfile */
1773         if (!cmd.crash)
1774                 claws_unlink(get_crashfile_name());
1775
1776         lock_socket_remove();
1777
1778 #ifdef HAVE_LIBSM
1779         if (mainwin->smc_conn)
1780                 SmcCloseConnection ((SmcConn)mainwin->smc_conn, 0, NULL);
1781         mainwin->smc_conn = NULL;
1782 #endif
1783
1784         main_window_destroy_all();
1785         
1786         plugin_unload_all("GTK2");
1787
1788         prefs_toolbar_done();
1789
1790         addressbook_destroy();
1791
1792         prefs_themes_done();
1793         prefs_fonts_done();
1794         prefs_ext_prog_done();
1795         prefs_wrapping_done();
1796         prefs_compose_writing_done();
1797         prefs_msg_colors_done();
1798         prefs_image_viewer_done();
1799         image_viewer_done();
1800         prefs_quote_done();
1801         prefs_summaries_done();
1802         prefs_message_done();
1803         prefs_other_done();
1804         prefs_receive_done();
1805         prefs_logging_done();
1806         prefs_send_done();
1807         tags_write_tags();
1808 #ifdef USE_ENCHANT       
1809         prefs_spelling_done();
1810         gtkaspell_checkers_quit();
1811 #endif
1812         plugin_unload_all("Common");
1813         claws_done();
1814 }
1815
1816 static void parse_cmd_opt(int argc, char *argv[])
1817 {
1818         gint i;
1819
1820         for (i = 1; i < argc; i++) {
1821                 if (!strncmp(argv[i], "--receive-all", 13)) {
1822                         cmd.receive_all = TRUE;
1823                 } else if (!strncmp(argv[i], "--receive", 9)) {
1824                         cmd.receive = TRUE;
1825                 } else if (!strncmp(argv[i], "--compose", 9)) {
1826                         const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
1827
1828                         cmd.compose = TRUE;
1829                         cmd.compose_mailto = NULL;
1830                         if (p && *p != '\0' && *p != '-') {
1831                                 if (!strncmp(p, "mailto:", 7)) {
1832                                         cmd.compose_mailto = p + 7;
1833                                 } else {
1834                                         cmd.compose_mailto = p;
1835                                 }
1836                                 i++;
1837                         }
1838                 } else if (!strncmp(argv[i], "--subscribe", 11)) {
1839                         const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
1840                         if (p && *p != '\0' && *p != '-') {
1841                                 cmd.subscribe = TRUE;
1842                                 cmd.subscribe_uri = p;
1843                         }
1844                 } else if (!strncmp(argv[i], "--attach", 8)) {
1845                         const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
1846                         gchar *file = NULL;
1847
1848                         while (p && *p != '\0' && *p != '-') {
1849                                 if (!cmd.attach_files) {
1850                                         cmd.attach_files = g_ptr_array_new();
1851                                 }
1852                                 if ((file = g_filename_from_uri(p, NULL, NULL)) != NULL) {
1853                                         if (!is_file_exist(file)) {
1854                                                 g_free(file);
1855                                                 file = NULL;
1856                                         }
1857                                 }
1858                                 if (file == NULL && *p != G_DIR_SEPARATOR) {
1859                                         file = g_strconcat(claws_get_startup_dir(),
1860                                                            G_DIR_SEPARATOR_S,
1861                                                            p, NULL);
1862                                 } else if (file == NULL) {
1863                                         file = g_strdup(p);
1864                                 }
1865                                 g_ptr_array_add(cmd.attach_files, file);
1866                                 i++;
1867                                 p = (i+1 < argc)?argv[i+1]:NULL;
1868                         }
1869                 } else if (!strncmp(argv[i], "--send", 6)) {
1870                         cmd.send = TRUE;
1871                 } else if (!strncmp(argv[i], "--version-full", 14) ||
1872                            !strncmp(argv[i], "-V", 2)) {
1873                         g_print("Claws Mail version " VERSION "\n");
1874                         main_dump_features_list(FALSE);
1875                         exit(0);
1876                 } else if (!strncmp(argv[i], "--version", 9) ||
1877                            !strncmp(argv[i], "-v", 2)) {
1878                         g_print("Claws Mail version " VERSION "\n");
1879                         exit(0);
1880                 } else if (!strncmp(argv[i], "--status-full", 13)) {
1881                         const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
1882  
1883                         cmd.status_full = TRUE;
1884                         while (p && *p != '\0' && *p != '-') {
1885                                 if (!cmd.status_full_folders) {
1886                                         cmd.status_full_folders =
1887                                                 g_ptr_array_new();
1888                                 }
1889                                 g_ptr_array_add(cmd.status_full_folders,
1890                                                 g_strdup(p));
1891                                 i++;
1892                                 p = (i+1 < argc)?argv[i+1]:NULL;
1893                         }
1894                 } else if (!strncmp(argv[i], "--status", 8)) {
1895                         const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
1896  
1897                         cmd.status = TRUE;
1898                         while (p && *p != '\0' && *p != '-') {
1899                                 if (!cmd.status_folders)
1900                                         cmd.status_folders = g_ptr_array_new();
1901                                 g_ptr_array_add(cmd.status_folders,
1902                                                 g_strdup(p));
1903                                 i++;
1904                                 p = (i+1 < argc)?argv[i+1]:NULL;
1905                         }
1906                 } else if (!strncmp(argv[i], "--search", 8)) {
1907                         cmd.search_folder    = (i+1 < argc)?argv[i+1]:NULL;
1908                         cmd.search_type      = (i+2 < argc)?argv[i+2]:NULL;
1909                         cmd.search_request   = (i+3 < argc)?argv[i+3]:NULL;
1910                         const char* rec      = (i+4 < argc)?argv[i+4]:NULL;
1911                         cmd.search_recursive = TRUE;
1912                         if (rec && (tolower(*rec)=='n' || tolower(*rec)=='f' || *rec=='0'))
1913                                 cmd.search_recursive = FALSE;
1914                         if (cmd.search_folder && cmd.search_type && cmd.search_request)
1915                                 cmd.search = TRUE;
1916                 } else if (!strncmp(argv[i], "--online", 8)) {
1917                         cmd.online_mode = ONLINE_MODE_ONLINE;
1918                 } else if (!strncmp(argv[i], "--offline", 9)) {
1919                         cmd.online_mode = ONLINE_MODE_OFFLINE;
1920                 } else if (!strncmp(argv[i], "--help", 6) ||
1921                            !strncmp(argv[i], "-h", 2)) {
1922                         gchar *base = g_path_get_basename(argv[0]);
1923                         g_print(_("Usage: %s [OPTION]...\n"), base);
1924
1925                         g_print("%s\n", _("  --compose [address]    open composition window"));
1926                         g_print("%s\n", _("  --subscribe [uri]      subscribe to the given URI if possible"));
1927                         g_print("%s\n", _("  --attach file1 [file2]...\n"
1928                                   "                         open composition window with specified files\n"
1929                                   "                         attached"));
1930                         g_print("%s\n", _("  --receive              receive new messages"));
1931                         g_print("%s\n", _("  --receive-all          receive new messages of all accounts"));
1932                         g_print("%s\n", _("  --search folder type request [recursive]"));
1933                         g_print("%s\n", _("                         searches mail"));
1934                         g_print("%s\n", _("                         folder ex.: \"#mh/Mailbox/inbox\" or \"Mail\""));
1935                         g_print("%s\n", _("                         type: s[ubject],f[rom],t[o],e[xtended],m[ixed] or g: tag"));
1936                         g_print("%s\n", _("                         request: search string"));
1937                         g_print("%s\n", _("                         recursive: false if arg. starts with 0, n, N, f or F"));
1938
1939                         g_print("%s\n", _("  --send                 send all queued messages"));
1940                         g_print("%s\n", _("  --status [folder]...   show the total number of messages"));
1941                         g_print("%s\n", _("  --status-full [folder]...\n"
1942                                           "                         show the status of each folder"));
1943                         g_print("%s\n", _("  --select folder[/msg]  jumps to the specified folder/message\n" 
1944                                           "                         folder is a folder id like 'folder/sub_folder'"));
1945                         g_print("%s\n", _("  --online               switch to online mode"));
1946                         g_print("%s\n", _("  --offline              switch to offline mode"));
1947                         g_print("%s\n", _("  --exit --quit -q       exit Claws Mail"));
1948                         g_print("%s\n", _("  --debug                debug mode"));
1949                         g_print("%s\n", _("  --help -h              display this help and exit"));
1950                         g_print("%s\n", _("  --version -v           output version information and exit"));
1951                         g_print("%s\n", _("  --version-full -V      output version and built-in features information and exit"));
1952                         g_print("%s\n", _("  --config-dir           output configuration directory"));
1953                         g_print("%s\n", _("  --alternate-config-dir [dir]\n"
1954                                           "                         use specified configuration directory"));
1955
1956                         g_free(base);
1957                         exit(1);
1958                 } else if (!strncmp(argv[i], "--crash", 7)) {
1959                         cmd.crash = TRUE;
1960                         cmd.crash_params = g_strdup((i+1 < argc)?argv[i+1]:NULL);
1961                         i++;
1962                 } else if (!strncmp(argv[i], "--config-dir", sizeof "--config-dir" - 1)) {
1963                         g_print(RC_DIR "\n");
1964                         exit(0);
1965                 } else if (!strncmp(argv[i], "--alternate-config-dir", sizeof "--alternate-config-dir" - 1) && i+1 < argc) {
1966                         set_rc_dir(argv[i+1]);
1967                 } else if (!strncmp(argv[i], "--exit", 6) ||
1968                            !strncmp(argv[i], "--quit", 6) ||
1969                            !strncmp(argv[i], "-q", 2)) {
1970                         cmd.exit = TRUE;
1971                 } else if (!strncmp(argv[i], "--select", 8) && i+1 < argc) {
1972                         cmd.target = argv[i+1];
1973                 } else if (i == 1 && argc == 2) {
1974                         /* only one parameter. Do something intelligent about it */
1975                         if ((strstr(argv[i], "@")||!strncmp(argv[i], "mailto:", 7)) && !strstr(argv[i], "://")) {
1976                                 const gchar *p = argv[i];
1977
1978                                 cmd.compose = TRUE;
1979                                 cmd.compose_mailto = NULL;
1980                                 if (p && *p != '\0' && *p != '-') {
1981                                         if (!strncmp(p, "mailto:", 7)) {
1982                                                 cmd.compose_mailto = p + 7;
1983                                         } else {
1984                                                 cmd.compose_mailto = p;
1985                                         }
1986                                 }
1987                         } else if (!strncmp(argv[i], "file://", 7)) {
1988                                 cmd.target = argv[i];
1989                         } else if (!strncmp(argv[i], "?attach=file://", strlen("?attach=file://"))) {
1990                                 cmd.compose = TRUE;
1991                                 cmd.compose_mailto = argv[i];
1992                         } else if (strstr(argv[i], "://")) {
1993                                 const gchar *p = argv[i];
1994                                 if (p && *p != '\0' && *p != '-') {
1995                                         cmd.subscribe = TRUE;
1996                                         cmd.subscribe_uri = p;
1997                                 }
1998                         } else if (!strcmp(argv[i], "--sync")) {
1999                                 /* gtk debug */
2000                         } else if (is_dir_exist(argv[i]) || is_file_exist(argv[i])) {
2001                                 cmd.target = argv[i];
2002                         } else {
2003                                 g_print(_("Unknown option\n"));
2004                                 exit(1);
2005                         }
2006                 }
2007         }
2008
2009         if (cmd.attach_files && cmd.compose == FALSE) {
2010                 cmd.compose = TRUE;
2011                 cmd.compose_mailto = NULL;
2012         }
2013 }
2014
2015 static void initial_processing(FolderItem *item, gpointer data)
2016 {
2017         MainWindow *mainwin = (MainWindow *)data;
2018         gchar *buf;
2019
2020         cm_return_if_fail(item);
2021         buf = g_strdup_printf(_("Processing (%s)..."), 
2022                               item->path 
2023                               ? item->path 
2024                               : _("top level folder"));
2025         g_free(buf);
2026
2027         
2028         if (item->prefs->enable_processing) {
2029                 item->processing_pending = TRUE;
2030                 folder_item_apply_processing(item);
2031                 item->processing_pending = FALSE;
2032         }
2033
2034         STATUSBAR_POP(mainwin);
2035 }
2036
2037 static gboolean draft_all_messages(void)
2038 {
2039         GList *compose_list = NULL;
2040         
2041         compose_clear_exit_drafts();
2042         compose_list = compose_get_compose_list();
2043         while (compose_list != NULL) {
2044                 Compose *c = (Compose*)compose_list->data;
2045                 if (!compose_draft(c, COMPOSE_DRAFT_FOR_EXIT))
2046                         return FALSE;
2047                 compose_list = compose_get_compose_list();
2048         }
2049         return TRUE;
2050 }
2051 gboolean clean_quit(gpointer data)
2052 {
2053         static gboolean firstrun = TRUE;
2054
2055         if (!firstrun) {
2056                 return FALSE;
2057         }
2058         firstrun = FALSE;
2059
2060         /*!< Good idea to have the main window stored in a 
2061          *   static variable so we can check that variable
2062          *   to see if we're really allowed to do things
2063          *   that actually the spawner is supposed to 
2064          *   do (like: sending mail, composing messages).
2065          *   Because, really, if we're the spawnee, and
2066          *   we touch GTK stuff, we're hosed. See the 
2067          *   next fixme. */
2068
2069         /* FIXME: Use something else to signal that we're
2070          * in the original spawner, and not in a spawned
2071          * child. */
2072         if (!static_mainwindow) {
2073                 return FALSE;
2074         }
2075                 
2076         draft_all_messages();
2077         emergency_exit = TRUE;
2078         exit_claws(static_mainwindow);
2079         exit(0);
2080
2081         return FALSE;
2082 }
2083
2084 void app_will_exit(GtkWidget *widget, gpointer data)
2085 {
2086         MainWindow *mainwin = data;
2087         
2088         if (gtk_main_level() == 0) {
2089                 debug_print("not even started\n");
2090                 return;
2091         }
2092         if (sc_exiting == TRUE) {
2093                 debug_print("exit pending\n");
2094                 return;
2095         }
2096         sc_exiting = TRUE;
2097         debug_print("exiting\n");
2098         if (compose_get_compose_list()) {
2099                 if (!draft_all_messages()) {
2100                         main_window_popup(mainwin);
2101                         sc_exiting = FALSE;
2102                         return;
2103                 }
2104         }
2105
2106         if (prefs_common.warn_queued_on_exit && procmsg_have_queued_mails_fast()) {
2107                 if (alertpanel(_("Queued messages"),
2108                                _("Some unsent messages are queued. Exit now?"),
2109                                GTK_STOCK_CANCEL, GTK_STOCK_OK, NULL)
2110                     != G_ALERTALTERNATE) {
2111                         main_window_popup(mainwin);
2112                         sc_exiting = FALSE;
2113                         return;
2114                 }
2115                 manage_window_focus_in(mainwin->window, NULL, NULL);
2116         }
2117
2118         sock_cleanup();
2119 #ifdef HAVE_VALGRIND
2120         if (RUNNING_ON_VALGRIND) {
2121                 summary_clear_list(mainwin->summaryview);
2122         }
2123 #endif
2124         if (folderview_get_selected_item(mainwin->folderview))
2125                 folder_item_close(folderview_get_selected_item(mainwin->folderview));
2126         gtk_main_quit();
2127 }
2128
2129 gboolean claws_is_exiting(void)
2130 {
2131         return sc_exiting;
2132 }
2133
2134 gboolean claws_is_starting(void)
2135 {
2136         return sc_starting;
2137 }
2138
2139 /*
2140  * CLAWS: want this public so crash dialog can delete the
2141  * lock file too
2142  */
2143 gchar *claws_get_socket_name(void)
2144 {
2145         static gchar *filename = NULL;
2146         const gchar *socket_dir = NULL;
2147         
2148         if (rc_dir_is_alt())
2149                 socket_dir = get_rc_dir();
2150         else
2151                 socket_dir = g_get_tmp_dir();
2152         if (filename == NULL) {
2153                 filename = g_strdup_printf("%s%cclaws-mail-%d",
2154                                            socket_dir, G_DIR_SEPARATOR,
2155 #if HAVE_GETUID
2156                                            getuid());
2157 #else
2158                                            0);                                          
2159 #endif
2160         }
2161
2162         return filename;
2163 }
2164
2165 static gchar *get_crashfile_name(void)
2166 {
2167         static gchar *filename = NULL;
2168
2169         if (filename == NULL) {
2170                 filename = g_strdup_printf("%s%cclaws-crashed",
2171                                            get_tmp_dir(), G_DIR_SEPARATOR);
2172         }
2173
2174         return filename;
2175 }
2176
2177 static gint prohibit_duplicate_launch(void)
2178 {
2179         gint uxsock;
2180 #ifdef G_OS_UNIX
2181         gchar *path;
2182
2183         path = claws_get_socket_name();
2184         uxsock = fd_connect_unix(path);
2185         
2186         if (x_display == NULL)
2187                 x_display = g_strdup(g_getenv("DISPLAY"));
2188
2189         if (uxsock < 0) {
2190                 claws_unlink(path);
2191                 return fd_open_unix(path);
2192         }
2193 #else
2194         HANDLE hmutex;
2195
2196         hmutex = CreateMutexA(NULL, FALSE, "ClawsMail");
2197         if (!hmutex) {
2198                 debug_print("cannot create Mutex\n");
2199                 return -1;
2200         }
2201         if (GetLastError() != ERROR_ALREADY_EXISTS) {
2202                 uxsock = fd_open_inet(50216);
2203                 if (uxsock < 0)
2204                         return 0;
2205                 return uxsock;
2206         }
2207
2208         uxsock = fd_connect_inet(50216);
2209         if (uxsock < 0)
2210                 return -1;
2211 #endif
2212         /* remote command mode */
2213
2214         debug_print("another Claws Mail instance is already running.\n");
2215
2216         if (cmd.receive_all) {
2217                 fd_write_all(uxsock, "receive_all\n", 12);
2218         } else if (cmd.receive) {
2219                 fd_write_all(uxsock, "receive\n", 8);
2220         } else if (cmd.compose && cmd.attach_files) {
2221                 gchar *str, *compose_str;
2222                 gint i;
2223
2224                 if (cmd.compose_mailto) {
2225                         compose_str = g_strdup_printf("compose_attach %s\n",
2226                                                       cmd.compose_mailto);
2227                 } else {
2228                         compose_str = g_strdup("compose_attach\n");
2229                 }
2230
2231                 fd_write_all(uxsock, compose_str, strlen(compose_str));
2232                 g_free(compose_str);
2233
2234                 for (i = 0; i < cmd.attach_files->len; i++) {
2235                         str = g_ptr_array_index(cmd.attach_files, i);
2236                         fd_write_all(uxsock, str, strlen(str));
2237                         fd_write_all(uxsock, "\n", 1);
2238                 }
2239
2240                 fd_write_all(uxsock, ".\n", 2);
2241         } else if (cmd.compose) {
2242                 gchar *compose_str;
2243
2244                 if (cmd.compose_mailto) {
2245                         compose_str = g_strdup_printf
2246                                 ("compose %s\n", cmd.compose_mailto);
2247                 } else {
2248                         compose_str = g_strdup("compose\n");
2249                 }
2250
2251                 fd_write_all(uxsock, compose_str, strlen(compose_str));
2252                 g_free(compose_str);
2253         } else if (cmd.subscribe) {
2254                 gchar *str = g_strdup_printf("subscribe %s\n", cmd.subscribe_uri);
2255                 fd_write_all(uxsock, str, strlen(str));
2256                 g_free(str);
2257         } else if (cmd.send) {
2258                 fd_write_all(uxsock, "send\n", 5);
2259         } else if (cmd.online_mode == ONLINE_MODE_ONLINE) {
2260                 fd_write(uxsock, "online\n", 6);
2261         } else if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
2262                 fd_write(uxsock, "offline\n", 7);
2263         } else if (cmd.status || cmd.status_full) {
2264                 gchar buf[BUFFSIZE];
2265                 gint i;
2266                 const gchar *command;
2267                 GPtrArray *folders;
2268                 gchar *folder;
2269  
2270                 command = cmd.status_full ? "status-full\n" : "status\n";
2271                 folders = cmd.status_full ? cmd.status_full_folders :
2272                         cmd.status_folders;
2273  
2274                 fd_write_all(uxsock, command, strlen(command));
2275                 for (i = 0; folders && i < folders->len; ++i) {
2276                         folder = g_ptr_array_index(folders, i);
2277                         fd_write_all(uxsock, folder, strlen(folder));
2278                         fd_write_all(uxsock, "\n", 1);
2279                 }
2280                 fd_write_all(uxsock, ".\n", 2);
2281                 for (;;) {
2282                         fd_gets(uxsock, buf, sizeof(buf));
2283                         if (!strncmp(buf, ".\n", 2)) break;
2284                         fputs(buf, stdout);
2285                 }
2286         } else if (cmd.exit) {
2287                 fd_write_all(uxsock, "exit\n", 5);
2288         } else if (cmd.target) {
2289                 gchar *str = g_strdup_printf("select %s\n", cmd.target);
2290                 fd_write_all(uxsock, str, strlen(str));
2291                 g_free(str);
2292         } else if (cmd.search) {
2293                 gchar buf[BUFFSIZE];
2294                 gchar *str =
2295                         g_strdup_printf("search %s\n%s\n%s\n%c\n",
2296                                                         cmd.search_folder, cmd.search_type, cmd.search_request,
2297                                                         (cmd.search_recursive==TRUE)?'1':'0');
2298                 fd_write_all(uxsock, str, strlen(str));
2299                 g_free(str);
2300                 for (;;) {
2301                         fd_gets(uxsock, buf, sizeof(buf));
2302                         if (!strncmp(buf, ".\n", 2)) break;
2303                         fputs(buf, stdout);
2304                 }
2305         } else {
2306 #ifndef G_OS_WIN32
2307                 gchar buf[BUFSIZ];
2308                 fd_write_all(uxsock, "get_display\n", 12);
2309                 memset(buf, 0, sizeof(buf));
2310                 fd_gets(uxsock, buf, sizeof(buf));
2311                 if (strcmp2(buf, x_display)) {
2312                         g_print("Claws Mail is already running on display %s.\n",
2313                                 buf);
2314                 } else {
2315                         fd_close(uxsock);
2316                         uxsock = fd_connect_unix(path);
2317                         fd_write_all(uxsock, "popup\n", 6);
2318                 }
2319 #else
2320                 fd_write_all(uxsock, "popup\n", 6);
2321 #endif
2322         }
2323
2324         fd_close(uxsock);
2325         return -1;
2326 }
2327
2328 static gint lock_socket_remove(void)
2329 {
2330 #ifdef G_OS_UNIX
2331         gchar *filename;
2332 #endif
2333         if (lock_socket < 0) {
2334                 return -1;
2335         }
2336
2337         if (lock_socket_tag > 0) {
2338                 g_source_remove(lock_socket_tag);
2339         }
2340         fd_close(lock_socket);
2341
2342 #ifdef G_OS_UNIX
2343         filename = claws_get_socket_name();
2344         claws_unlink(filename);
2345 #endif
2346
2347         return 0;
2348 }
2349
2350 static GPtrArray *get_folder_item_list(gint sock)
2351 {
2352         gchar buf[BUFFSIZE];
2353         FolderItem *item;
2354         GPtrArray *folders = NULL;
2355
2356         for (;;) {
2357                 fd_gets(sock, buf, sizeof(buf));
2358                 if (!strncmp(buf, ".\n", 2)) {
2359                         break;
2360                 }
2361                 strretchomp(buf);
2362                 if (!folders) {
2363                         folders = g_ptr_array_new();
2364                 }
2365                 item = folder_find_item_from_identifier(buf);
2366                 if (item) {
2367                         g_ptr_array_add(folders, item);
2368                 } else {
2369                         g_warning("no such folder: %s\n", buf);
2370                 }
2371         }
2372
2373         return folders;
2374 }
2375
2376 static void lock_socket_input_cb(gpointer data,
2377                                  gint source,
2378                                  GdkInputCondition condition)
2379 {
2380         MainWindow *mainwin = (MainWindow *)data;
2381         gint sock;
2382         gchar buf[BUFFSIZE];
2383         /* re-use the same quicksearch (& avoid matcher_list mem.leaks) */
2384         static QuickSearch *quicksearch = NULL;
2385
2386         sock = fd_accept(source);
2387         fd_gets(sock, buf, sizeof(buf));
2388
2389         if (!strncmp(buf, "popup", 5)) {
2390                 main_window_popup(mainwin);
2391         } else if (!strncmp(buf, "get_display", 11)) {
2392                 fd_write_all(sock, x_display, strlen(x_display));
2393         } else if (!strncmp(buf, "receive_all", 11)) {
2394                 inc_all_account_mail(mainwin, FALSE,
2395                                      prefs_common.newmail_notify_manu);
2396         } else if (!strncmp(buf, "receive", 7)) {
2397                 inc_mail(mainwin, prefs_common.newmail_notify_manu);
2398         } else if (!strncmp(buf, "compose_attach", 14)) {
2399                 GPtrArray *files;
2400                 gchar *mailto;
2401
2402                 mailto = g_strdup(buf + strlen("compose_attach") + 1);
2403                 files = g_ptr_array_new();
2404                 while (fd_gets(sock, buf, sizeof(buf)) > 0) {
2405                         strretchomp(buf);
2406                         if (!strcmp2(buf, "."))
2407                                 break;
2408                         g_ptr_array_add(files, g_strdup(buf));
2409                 }
2410                 open_compose_new(mailto, files);
2411                 ptr_array_free_strings(files);
2412                 g_ptr_array_free(files, TRUE);
2413                 g_free(mailto);
2414         } else if (!strncmp(buf, "compose", 7)) {
2415                 open_compose_new(buf + strlen("compose") + 1, NULL);
2416         } else if (!strncmp(buf, "subscribe", 9)) {
2417                 main_window_popup(mainwin);
2418                 folder_subscribe(buf + strlen("subscribe") + 1);
2419         } else if (!strncmp(buf, "send", 4)) {
2420                 send_queue();
2421         } else if (!strncmp(buf, "online", 6)) {
2422                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
2423         } else if (!strncmp(buf, "offline", 7)) {
2424                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
2425         } else if (!strncmp(buf, "status-full", 11) ||
2426                    !strncmp(buf, "status", 6)) {
2427                 gchar *status;
2428                 GPtrArray *folders;
2429  
2430                 folders = get_folder_item_list(sock);
2431                 status = folder_get_status
2432                         (folders, !strncmp(buf, "status-full", 11));
2433                 fd_write_all(sock, status, strlen(status));
2434                 fd_write_all(sock, ".\n", 2);
2435                 g_free(status);
2436                 if (folders) g_ptr_array_free(folders, TRUE);
2437         } else if (!strncmp(buf, "select ", 7)) {
2438                 const gchar *target = buf+7;
2439                 mainwindow_jump_to(target, TRUE);
2440         } else if (!strncmp(buf, "search ", 7)) {
2441                 FolderItem* folderItem = NULL;
2442                 GSList *messages = NULL;
2443                 gchar *folder_name, *request;
2444                 QuickSearchType searchType = QUICK_SEARCH_EXTENDED;
2445                 gboolean recursive;
2446
2447                 if (quicksearch==NULL)
2448                         quicksearch = quicksearch_new_nogui();
2449                 
2450                 folder_name = g_strdup(buf+7);
2451                 strretchomp(folder_name);
2452
2453                 if (fd_gets(sock, buf, sizeof(buf)) <= 0) {
2454                         g_free(folder_name);
2455                         folder_name=NULL;
2456                 }
2457                 searchType = quicksearch_type(buf);
2458                 if (fd_gets(sock, buf, sizeof(buf)) <= 0) {
2459                         g_free(folder_name);
2460                         folder_name=NULL;
2461                 }
2462                 request = g_strdup(buf);
2463                 strretchomp(request);
2464
2465                 recursive = TRUE;
2466                 if (fd_gets(sock, buf, sizeof(buf)) > 0)
2467                         if (buf[0]=='0')
2468                                 recursive = FALSE;
2469
2470                 debug_print("search: %s %i %s %i\n",folder_name,searchType,request,recursive);
2471
2472                 if (folder_name)
2473                         folderItem = folder_find_item_from_identifier(folder_name);
2474                 if (folder_name && folderItem == NULL) {
2475                         debug_print("Unknow folder item : '%s', searching folder\n",folder_name);
2476                         Folder* folder = folder_find_from_path(folder_name);
2477                         if (folder != NULL)
2478                                 folderItem = FOLDER_ITEM(folder->node->data);
2479                         else
2480                                 debug_print("Unknown folder: '%s'\n",folder_name);
2481                 } else {
2482                         debug_print("%s %s\n",folderItem->name, folderItem->path);
2483         }
2484                 if (folderItem != NULL) {
2485                         quicksearch_set(quicksearch, searchType, request);
2486                         quicksearch_set_recursive(quicksearch, recursive);
2487                         search_msgs_in_folders(&messages, quicksearch, folderItem);
2488                 } else {
2489                         g_print("Folder '%s' not found.\n'", folder_name);
2490                 }
2491
2492                 GSList *cur;
2493                 for (cur=messages; cur != NULL; cur = cur->next) {
2494                         MsgInfo* msg = (MsgInfo *)cur->data;
2495                         gchar *file = procmsg_get_message_file_path(msg);
2496                         fd_write_all(sock, file, strlen(file));
2497                         fd_write_all(sock, "\n", 1);
2498                         g_free(file);
2499                 }
2500                 fd_write_all(sock, ".\n", 2);
2501
2502                 if (messages != NULL)
2503                         procmsg_msg_list_free(messages);
2504                 g_free(folder_name);
2505                 g_free(request);
2506         } else if (!strncmp(buf, "exit", 4)) {
2507                 if (prefs_common.clean_on_exit && !prefs_common.ask_on_clean) {
2508                         procmsg_empty_all_trash();
2509                 }
2510                 app_will_exit(NULL, mainwin);
2511         }
2512         fd_close(sock);
2513
2514 }
2515
2516 static void open_compose_new(const gchar *address, GPtrArray *attach_files)
2517 {
2518         gchar *addr = NULL;
2519
2520         if (address) {
2521                 Xstrdup_a(addr, address, return);
2522                 g_strstrip(addr);
2523         }
2524
2525         compose_new(NULL, addr, attach_files);
2526 }
2527
2528 static void send_queue(void)
2529 {
2530         GList *list;
2531         gchar *errstr = NULL;
2532         gboolean error = FALSE;
2533         for (list = folder_get_list(); list != NULL; list = list->next) {
2534                 Folder *folder = list->data;
2535
2536                 if (folder->queue) {
2537                         gint res = procmsg_send_queue
2538                                 (folder->queue, prefs_common.savemsg,
2539                                 &errstr);
2540
2541                         if (res) {
2542                                 folder_item_scan(folder->queue);
2543                         }
2544                         
2545                         if (res < 0)
2546                                 error = TRUE;
2547                 }
2548         }
2549         if (errstr) {
2550                 alertpanel_error_log(_("Some errors occurred "
2551                                 "while sending queued messages:\n%s"), errstr);
2552                 g_free(errstr);
2553         } else if (error) {
2554                 alertpanel_error_log("Some errors occurred "
2555                                 "while sending queued messages.");
2556         }
2557 }
2558
2559 static void quit_signal_handler(int sig)
2560 {
2561         debug_print("Quitting on signal %d\n", sig);
2562
2563         g_timeout_add(0, clean_quit, NULL);
2564 }
2565
2566 static void install_basic_sighandlers()
2567 {
2568 #ifndef G_OS_WIN32
2569         sigset_t    mask;
2570         struct sigaction act;
2571
2572         sigemptyset(&mask);
2573
2574 #ifdef SIGTERM
2575         sigaddset(&mask, SIGTERM);
2576 #endif
2577 #ifdef SIGINT
2578         sigaddset(&mask, SIGINT);
2579 #endif
2580 #ifdef SIGHUP
2581         sigaddset(&mask, SIGHUP);
2582 #endif
2583
2584         act.sa_handler = quit_signal_handler;
2585         act.sa_mask    = mask;
2586         act.sa_flags   = 0;
2587
2588 #ifdef SIGTERM
2589         sigaction(SIGTERM, &act, 0);
2590 #endif
2591 #ifdef SIGINT
2592         sigaction(SIGINT, &act, 0);
2593 #endif  
2594 #ifdef SIGHUP
2595         sigaction(SIGHUP, &act, 0);
2596 #endif  
2597
2598         sigprocmask(SIG_UNBLOCK, &mask, 0);
2599 #endif /* !G_OS_WIN32 */
2600 }
2601
2602 #if (defined linux && defined SIGIO)
2603 static int mem_notify_fd = 0;
2604
2605 static gboolean clean_caches(gpointer unused)
2606 {
2607         if (static_mainwindow && static_mainwindow->lock_count > 0)
2608                 return TRUE;
2609         debug_print("/dev/mem_notify: callback: Freeing some memory now!\n");
2610         folder_clean_cache_memory_force();
2611         return FALSE;
2612 }
2613
2614 static void memory_signal_handler(int sig)
2615 {
2616         debug_print("/dev/mem_notify: Kernel says we should free up some memory!\n");
2617         g_timeout_add(10, clean_caches, NULL); 
2618 }
2619
2620 static void install_memory_sighandler()
2621 {
2622         sigset_t    mask;
2623         struct sigaction act;
2624         int flags;
2625
2626         mem_notify_fd = g_open("/dev/mem_notify", O_RDONLY|O_NONBLOCK, 0);
2627         if (mem_notify_fd == -1) {
2628                 debug_print("/dev/mem_notify not available (%s)\n", 
2629                         strerror(errno));
2630                 return;
2631         }
2632         
2633         fcntl(mem_notify_fd, F_SETOWN, getpid());
2634         flags = fcntl(mem_notify_fd, F_GETFL);
2635         fcntl(mem_notify_fd, flags|FASYNC);
2636
2637         sigemptyset(&mask);
2638
2639         sigaddset(&mask, SIGIO);
2640
2641         act.sa_handler = memory_signal_handler;
2642         act.sa_mask    = mask;
2643         act.sa_flags   = 0;
2644
2645         sigaction(SIGIO, &act, 0);
2646
2647         sigprocmask(SIG_UNBLOCK, &mask, 0);
2648
2649         debug_print("/dev/mem_notify: installed handler\n");
2650 }
2651 #endif /* linux && SIGIO */
2652
2653 #ifdef MAEMO
2654 osso_context_t *get_osso_context(void)
2655 {
2656         return static_osso_context;
2657 }
2658 #endif
2659
2660
2661 #ifdef HAVE_NETWORKMANAGER_SUPPORT
2662 static void networkmanager_state_change_cb(DBusGProxy *proxy, gchar *dev,
2663                                          gpointer data)
2664 {
2665         MainWindow *mainWin;
2666
2667         mainWin = NULL;
2668         if (static_mainwindow)
2669                 mainWin = static_mainwindow;
2670         else if (data)
2671                 mainWin = (MainWindow*)data;
2672         
2673         if (!prefs_common.use_networkmanager)
2674                 return;
2675
2676         if (mainWin) {
2677                 GError *error;
2678                 gboolean online;
2679
2680                 error = NULL;           
2681                 online = networkmanager_is_online(&error);
2682                 if(!error) {
2683                         if(online && went_offline_nm) {
2684                                 went_offline_nm = FALSE;
2685                                 main_window_toggle_work_offline(mainWin, FALSE, FALSE);
2686                                 debug_print("NetworkManager: Went online\n");
2687                                 log_message(LOG_PROTOCOL, _("NetworkManager: network is online.\n"));
2688                         }
2689                         else if(!online) {
2690                                 went_offline_nm = TRUE;
2691                                 main_window_toggle_work_offline(mainWin, TRUE, FALSE);
2692                                 debug_print("NetworkManager: Went offline\n");
2693                                 log_message(LOG_PROTOCOL, _("NetworkManager: network is offline.\n"));
2694                         }
2695                 }
2696                 else {
2697                         debug_print("Failed to get online information from NetworkManager: %s\n",
2698                                                          error->message);
2699                         g_error_free(error);
2700                 }
2701         }
2702         else
2703                 debug_print("NetworkManager: Cannot change connection state because "
2704                                                  "main window does not exist\n");
2705 }
2706
2707 /* Returns true (and sets error appropriately, if given) in case of error */
2708 gboolean networkmanager_is_online(GError **error)
2709 {
2710         DBusGConnection *connection;
2711         DBusGProxy *proxy;
2712         GError *tmp_error = NULL;
2713         gboolean retVal;
2714         guint32 state;
2715
2716         if (!prefs_common.use_networkmanager)
2717                 return TRUE;
2718
2719         tmp_error = NULL;
2720         proxy = NULL;
2721         connection = dbus_g_bus_get(DBUS_BUS_SYSTEM, &tmp_error);
2722
2723         if(!connection) {
2724                 /* If calling code doesn't do error checking, at least print some debug */
2725                 if((error == NULL) || (*error == NULL))
2726                         debug_print("Failed to open connection to system bus: %s\n",
2727                                                          tmp_error->message);
2728                 g_propagate_error(error, tmp_error);
2729                 return TRUE;
2730         }
2731
2732         proxy = dbus_g_proxy_new_for_name(connection,
2733                         "org.freedesktop.NetworkManager",
2734                         "/org/freedesktop/NetworkManager",
2735                         "org.freedesktop.NetworkManager");
2736
2737         retVal = dbus_g_proxy_call(proxy,"state",&tmp_error, G_TYPE_INVALID,
2738                         G_TYPE_UINT, &state, G_TYPE_INVALID);
2739
2740         if(proxy)
2741                 g_object_unref(proxy);
2742         if(connection)
2743                 dbus_g_connection_unref(connection);
2744
2745         if(!retVal) {
2746                 /* If calling code doesn't do error checking, at least print some debug */
2747                 if((error == NULL) || (*error == NULL))
2748                         debug_print("Failed to get state info from NetworkManager: %s\n",
2749                                                          tmp_error->message);
2750                 g_propagate_error(error, tmp_error);
2751                 return TRUE;
2752         }
2753 #if NM_CHECK_VERSION(0,8,992)
2754         return (state == NM_STATE_CONNECTED_LOCAL ||
2755                 state == NM_STATE_CONNECTED_SITE ||
2756                 state == NM_STATE_CONNECTED_GLOBAL ||
2757                 state == NM_STATE_UNKNOWN);
2758 #else
2759         return (state == NM_STATE_CONNECTED ||
2760                 state == NM_STATE_UNKNOWN);
2761 #endif
2762 }
2763 #endif