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