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