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