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