2012-11-18 [colin] 3.9.0cvs14
[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 && G_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 #if !GTK_CHECK_VERSION(3, 0, 0)
1120                 gtk_set_locale();
1121 #endif
1122                 gtk_init(&argc, &argv);
1123                 crash_main(cmd.crash_params);
1124 #ifdef G_OS_WIN32
1125                 win32_close_log();
1126 #endif
1127                 return 0;
1128         }
1129         crash_install_handlers();
1130 #endif
1131         install_basic_sighandlers();
1132 #if (defined linux && defined SIGIO)
1133         install_memory_sighandler();
1134 #endif
1135
1136         if (cmd.status || cmd.status_full || cmd.search ||
1137                 cmd.statistics || cmd.reset_statistics || cmd.cancel_receiving) {
1138                 puts("0 Claws Mail not running.");
1139                 lock_socket_remove();
1140                 return 0;
1141         }
1142         
1143         if (cmd.exit)
1144                 return 0;
1145         if (!g_thread_supported())
1146                 g_thread_init(NULL);
1147
1148         reset_statistics();
1149         
1150 #if !GTK_CHECK_VERSION(3, 0, 0)
1151         gtk_set_locale();
1152 #endif
1153         gtk_init(&argc, &argv);
1154
1155 #ifdef G_OS_WIN32
1156         gtk_settings_set_string_property(gtk_settings_get_default(),
1157                         "gtk-theme-name",
1158                         "MS-Windows",
1159                         "XProperty");
1160 #endif
1161
1162 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1163         went_offline_nm = FALSE;
1164         nm_proxy = NULL;
1165 #endif
1166 #ifdef HAVE_DBUS_GLIB
1167         error = NULL;
1168         connection = dbus_g_bus_get(DBUS_BUS_SYSTEM, &error);
1169
1170         if(!connection) {
1171                 debug_print("Failed to open connection to system bus: %s\n", error->message);
1172                 g_error_free(error);
1173         }
1174         else {
1175 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1176                 nm_proxy = dbus_g_proxy_new_for_name(connection,
1177                         "org.freedesktop.NetworkManager",
1178                         "/org/freedesktop/NetworkManager",
1179                         "org.freedesktop.NetworkManager");
1180                 if (nm_proxy) {
1181 #if NM_CHECK_VERSION(0,8,992)
1182                         dbus_g_proxy_add_signal(nm_proxy, "StateChanged", G_TYPE_UINT, G_TYPE_INVALID);
1183                         dbus_g_proxy_connect_signal(nm_proxy, "StateChanged",
1184                                 G_CALLBACK(networkmanager_state_change_cb),
1185                                 NULL,NULL);
1186 #else
1187                         dbus_g_proxy_add_signal(nm_proxy, "StateChange", G_TYPE_UINT, G_TYPE_INVALID);
1188                         dbus_g_proxy_connect_signal(nm_proxy, "StateChange",
1189                                 G_CALLBACK(networkmanager_state_change_cb),
1190                                 NULL,NULL);
1191 #endif
1192                 }
1193 #endif
1194                 install_dbus_status_handler();
1195         }
1196 #endif
1197
1198
1199 #ifdef MAEMO
1200         osso_context = osso_initialize(OSSO_SERVICE, "2.8.1", TRUE, NULL);
1201         if (osso_context == NULL) {
1202                 return OSSO_ERROR;
1203         }
1204         hildon_program = HILDON_PROGRAM(hildon_program_get_instance());
1205         static_osso_context = osso_context;
1206 #endif  
1207 #if !GTK_CHECK_VERSION(3, 0, 0)
1208         gtk_widget_set_default_colormap(
1209                 gdk_screen_get_system_colormap(
1210                         gdk_screen_get_default()));
1211 #endif
1212
1213         gtkut_create_ui_manager();
1214
1215         /* Create container for all the menus we will be adding */
1216         MENUITEM_ADDUI("/", "Menus", NULL, GTK_UI_MANAGER_MENUBAR);
1217
1218         if (!g_thread_supported()) {
1219                 g_error(_("g_thread is not supported by glib.\n"));
1220         }
1221
1222 #ifdef G_OS_WIN32
1223         CHDIR_EXEC_CODE_RETURN_VAL_IF_FAIL(get_home_dir(), 1, win32_close_log(););
1224 #else
1225         CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
1226 #endif
1227         
1228         /* no config dir exists. See if we can migrate an old config. */
1229         if (!is_dir_exist(RC_DIR)) {
1230                 prefs_destroy_cache();
1231                 gboolean r = FALSE;
1232                 
1233                 /* if one of the old dirs exist, we'll ask if the user 
1234                  * want to migrates, and r will be TRUE if he said yes
1235                  * and migration succeeded, and FALSE otherwise.
1236                  */
1237                 if (is_dir_exist(OLD_GTK2_RC_DIR)) {
1238                         r = migrate_old_config(OLD_GTK2_RC_DIR, RC_DIR, _("Sylpheed-Claws 2.6.0 (or older)"));
1239                         asked_for_migration = TRUE;
1240                 } else if (is_dir_exist(OLDER_GTK2_RC_DIR)) {
1241                         r = migrate_old_config(OLDER_GTK2_RC_DIR, RC_DIR, _("Sylpheed-Claws 1.9.15 (or older)"));
1242                         asked_for_migration = TRUE;
1243                 } else if (is_dir_exist(OLD_GTK1_RC_DIR)) {
1244                         r = migrate_old_config(OLD_GTK1_RC_DIR, RC_DIR, _("Sylpheed-Claws 1.0.5 (or older)"));
1245                         asked_for_migration = TRUE;
1246                 } else if (is_dir_exist(SYLPHEED_RC_DIR)) {
1247                         r = migrate_old_config(SYLPHEED_RC_DIR, RC_DIR, "Sylpheed");
1248                         asked_for_migration = TRUE;
1249                 }
1250                 
1251                 /* If migration failed or the user didn't want to do it,
1252                  * we create a new one (and we'll hit wizard later). 
1253                  */
1254                 if (r == FALSE && !is_dir_exist(RC_DIR)) {
1255 #ifdef G_OS_UNIX
1256                         if (copy_dir(SYSCONFDIR "/skel/.claws-mail", RC_DIR) < 0) {
1257 #endif
1258                                 if (!is_dir_exist(RC_DIR) && make_dir(RC_DIR) < 0) {
1259 #ifdef G_OS_WIN32
1260                                         win32_close_log();
1261 #endif
1262                                         exit(1);
1263                                 }
1264 #ifdef G_OS_UNIX
1265                         }
1266 #endif
1267                 }
1268         }
1269         
1270
1271         if (!is_file_exist(RC_DIR G_DIR_SEPARATOR_S COMMON_RC) &&
1272             is_file_exist(RC_DIR G_DIR_SEPARATOR_S OLD_COMMON_RC)) {
1273                 /* post 2.6 name change */
1274                 migrate_common_rc(RC_DIR G_DIR_SEPARATOR_S OLD_COMMON_RC,
1275                           RC_DIR G_DIR_SEPARATOR_S COMMON_RC);
1276         }
1277
1278         if (!cmd.exit)
1279                 plugin_load_all("Common");
1280
1281         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, "gtkrc-2.0", NULL);
1282         gtk_rc_parse(userrc);
1283         g_free(userrc);
1284
1285         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
1286         gtk_accel_map_load (userrc);
1287         g_free(userrc);
1288
1289 #ifdef G_OS_WIN32
1290         CHDIR_EXEC_CODE_RETURN_VAL_IF_FAIL(get_rc_dir(), 1, win32_close_log(););
1291 #else
1292         CHDIR_RETURN_VAL_IF_FAIL(get_rc_dir(), 1);
1293 #endif
1294
1295         MAKE_DIR_IF_NOT_EXIST(get_mail_base_dir());
1296         MAKE_DIR_IF_NOT_EXIST(get_imap_cache_dir());
1297         MAKE_DIR_IF_NOT_EXIST(get_news_cache_dir());
1298         MAKE_DIR_IF_NOT_EXIST(get_mime_tmp_dir());
1299         MAKE_DIR_IF_NOT_EXIST(get_tmp_dir());
1300         MAKE_DIR_IF_NOT_EXIST(UIDL_DIR);
1301
1302         crash_file_present = is_file_exist(get_crashfile_name());
1303         /* remove temporary files */
1304         remove_all_files(get_tmp_dir());
1305         remove_all_files(get_mime_tmp_dir());
1306
1307         if (!cmd.crash && crash_file_present)
1308                 claws_crashed_bool = TRUE;
1309
1310         if (is_file_exist("claws.log")) {
1311                 if (rename_force("claws.log", "claws.log.bak") < 0)
1312                         FILE_OP_ERROR("claws.log", "rename");
1313         }
1314         set_log_file(LOG_PROTOCOL, "claws.log");
1315
1316         if (is_file_exist("filtering.log")) {
1317                 if (rename_force("filtering.log", "filtering.log.bak") < 0)
1318                         FILE_OP_ERROR("filtering.log", "rename");
1319         }
1320         set_log_file(LOG_DEBUG_FILTERING, "filtering.log");
1321
1322 #ifdef G_OS_WIN32
1323         CHDIR_EXEC_CODE_RETURN_VAL_IF_FAIL(get_home_dir(), 1, win32_close_log(););
1324 #else
1325         CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
1326 #endif
1327
1328         folder_system_init();
1329         prefs_common_read_config();
1330
1331         prefs_themes_init();
1332         prefs_fonts_init();
1333         prefs_ext_prog_init();
1334         prefs_wrapping_init();
1335         prefs_compose_writing_init();
1336         prefs_msg_colors_init();
1337         image_viewer_init();
1338         prefs_image_viewer_init();
1339         prefs_quote_init();
1340         prefs_summaries_init();
1341         prefs_message_init();
1342         prefs_other_init();
1343         prefs_logging_init();
1344         prefs_receive_init();
1345         prefs_send_init();
1346         tags_read_tags();
1347         matcher_init();
1348 #ifdef USE_ENCHANT
1349         gtkaspell_checkers_init();
1350         prefs_spelling_init();
1351 #endif
1352
1353         sock_set_io_timeout(prefs_common.io_timeout_secs);
1354         prefs_actions_read_config();
1355         prefs_display_header_read_config();
1356         /* prefs_filtering_read_config(); */
1357 #ifndef USE_NEW_ADDRBOOK
1358         addressbook_read_file();
1359 #else
1360         g_clear_error(&error);
1361         if (! addressbook_start_service(&error)) {
1362                 g_warning("%s", error->message);
1363                 g_clear_error(&error);
1364         }
1365         else {
1366                 addressbook_install_hooks(&error);
1367         }
1368 #endif
1369         gtkut_widget_init();
1370         stock_pixbuf_gdk(NULL, STOCK_PIXMAP_CLAWS_MAIL_ICON, &icon);
1371         gtk_window_set_default_icon(icon);
1372
1373         folderview_initialize();
1374
1375         mh_gtk_init();
1376         imap_gtk_init();
1377         news_gtk_init();
1378
1379         mainwin = main_window_create();
1380
1381 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1382         networkmanager_state_change_cb(nm_proxy,NULL,mainwin);
1383 #endif
1384
1385 #ifdef MAEMO
1386         AppData *appdata;
1387         appdata = g_new0(AppData, 1);
1388         appdata->program = hildon_program;
1389         appdata->window = HILDON_WINDOW(mainwin->window);
1390         appdata->osso_context = osso_context;
1391         result = osso_rpc_set_cb_f(appdata->osso_context, 
1392                 OSSO_SERVICE, 
1393                 OSSO_OBJECT, 
1394                 OSSO_IFACE,
1395                 dbus_req_handler, appdata);
1396         if (result != OSSO_OK) {
1397                 return OSSO_ERROR;
1398         }
1399
1400 #ifndef CHINOOK
1401         /* Add handler for Exit D-BUS messages */
1402         result = osso_application_set_exit_cb(appdata->osso_context,
1403                                                 exit_event_handler,
1404                                                 (gpointer) appdata);
1405         if (result != OSSO_OK) {
1406                 return OSSO_ERROR;
1407         }
1408 #endif
1409         osso_hw_set_event_cb( appdata->osso_context,
1410                                 NULL, hw_event_handler, (gpointer) appdata );
1411 #endif
1412         manage_window_focus_in(mainwin->window, NULL, NULL);
1413         folderview = mainwin->folderview;
1414
1415         gtk_cmclist_freeze(GTK_CMCLIST(mainwin->folderview->ctree));
1416         folder_item_update_freeze();
1417
1418         prefs_account_init();
1419         account_read_config_all();
1420
1421 #ifdef HAVE_LIBETPAN
1422         imap_main_init(prefs_common.skip_ssl_cert_check);
1423         imap_main_set_timeout(prefs_common.io_timeout_secs);
1424         nntp_main_init(prefs_common.skip_ssl_cert_check);
1425 #endif  
1426         /* If we can't read a folder list or don't have accounts,
1427          * it means the configuration's not done. Either this is
1428          * a brand new install, either a failed/refused migration.
1429          * So we'll start the wizard.
1430          */
1431         if (folder_read_list() < 0) {
1432                 prefs_destroy_cache();
1433                 
1434                 /* if run_wizard returns FALSE it's because it's
1435                  * been cancelled. We can't do much but exit.
1436                  * however, if the user was asked for a migration,
1437                  * we remove the newly created directory so that
1438                  * he's asked again for migration on next launch.*/
1439                 if (!run_wizard(mainwin, TRUE)) {
1440                         if (asked_for_migration)
1441                                 remove_dir_recursive(RC_DIR);
1442 #ifdef G_OS_WIN32
1443                         win32_close_log();
1444 #endif
1445                         exit(1);
1446                 }
1447                 main_window_reflect_prefs_all_now();
1448                 folder_write_list();
1449                 never_ran = TRUE;
1450         }
1451
1452         if (!account_get_list()) {
1453                 prefs_destroy_cache();
1454                 if (!run_wizard(mainwin, FALSE)) {
1455                         if (asked_for_migration)
1456                                 remove_dir_recursive(RC_DIR);
1457 #ifdef G_OS_WIN32
1458                         win32_close_log();
1459 #endif
1460                         exit(1);
1461                 }
1462                 if(!account_get_list()) {
1463                         exit_claws(mainwin);
1464 #ifdef G_OS_WIN32
1465                         win32_close_log();
1466 #endif
1467                         exit(1);
1468                 }
1469                 never_ran = TRUE;
1470         }
1471
1472         
1473         toolbar_main_set_sensitive(mainwin);
1474         main_window_set_menu_sensitive(mainwin);
1475
1476         /* if crashed, show window early so that the user
1477          * sees what's happening */
1478         if (claws_crashed()) {
1479                 main_window_popup(mainwin);
1480                 mainwin_shown = TRUE;
1481         }
1482
1483         account_set_missing_folder();
1484         folder_set_missing_folders();
1485         folderview_set(folderview);
1486
1487         prefs_matcher_read_config();
1488         quicksearch_set_search_strings(mainwin->summaryview->quicksearch);
1489
1490         /* make one all-folder processing before using claws */
1491         main_window_cursor_wait(mainwin);
1492         folder_func_to_all_folders(initial_processing, (gpointer *)mainwin);
1493
1494         /* if claws crashed, rebuild caches */
1495         if (claws_crashed()) {
1496                 GTK_EVENTS_FLUSH();
1497                 debug_print("Claws Mail crashed, checking for new messages in local folders\n");
1498                 folder_item_update_thaw();
1499                 folderview_check_new(NULL);
1500                 folder_clean_cache_memory_force();
1501                 folder_item_update_freeze();
1502         }
1503         /* make the crash-indicator file */
1504         str_write_to_file("foo", get_crashfile_name());
1505
1506         inc_autocheck_timer_init(mainwin);
1507
1508         /* ignore SIGPIPE signal for preventing sudden death of program */
1509 #ifdef G_OS_UNIX
1510         signal(SIGPIPE, SIG_IGN);
1511 #endif
1512         if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
1513                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
1514         }
1515         if (cmd.online_mode == ONLINE_MODE_ONLINE) {
1516                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
1517         }
1518
1519         if (cmd.status_folders) {
1520                 g_ptr_array_free(cmd.status_folders, TRUE);
1521                 cmd.status_folders = NULL;
1522         }
1523         if (cmd.status_full_folders) {
1524                 g_ptr_array_free(cmd.status_full_folders, TRUE);
1525                 cmd.status_full_folders = NULL;
1526         }
1527
1528         claws_register_idle_function(claws_gtk_idle);
1529
1530         prefs_toolbar_init();
1531
1532         num_folder_class = g_list_length(folder_get_list());
1533
1534         plugin_load_all("GTK2");
1535
1536         if (g_list_length(folder_get_list()) != num_folder_class) {
1537                 debug_print("new folders loaded, reloading processing rules\n");
1538                 prefs_matcher_read_config();
1539         }
1540         
1541         if ((plug_list = plugin_get_unloaded_list()) != NULL) {
1542                 GSList *cur;
1543                 gchar *list = NULL;
1544                 gint num_plugins = 0;
1545                 for (cur = plug_list; cur; cur = cur->next) {
1546                         Plugin *plugin = (Plugin *)cur->data;
1547                         gchar *tmp = g_strdup_printf("%s\n%s",
1548                                 list? list:"",
1549                                 plugin_get_name(plugin));
1550                         g_free(list);
1551                         list = tmp;
1552                         num_plugins++;
1553                 }
1554                 main_window_cursor_normal(mainwin);
1555                 main_window_popup(mainwin);
1556                 mainwin_shown = TRUE;
1557                 alertpanel_warning(ngettext(
1558                                      "The following plugin failed to load. "
1559                                      "Check the Plugins configuration "
1560                                      "for more information:\n%s",
1561                                      "The following plugins failed to load. "
1562                                      "Check the Plugins configuration "
1563                                      "for more information:\n%s", 
1564                                      num_plugins), 
1565                                      list);
1566                 main_window_cursor_wait(mainwin);
1567                 g_free(list);
1568                 g_slist_free(plug_list);
1569         }
1570
1571         if (never_ran) {
1572                 prefs_common_write_config();
1573                 plugin_load_standard_plugins ();
1574         }
1575         /* if not crashed, show window now */
1576         if (!mainwin_shown) {
1577                 /* apart if something told not to show */
1578                 if (show_at_startup)
1579                         main_window_popup(mainwin);
1580         }
1581
1582         if (!folder_have_mailbox()) {
1583                 prefs_destroy_cache();
1584                 main_window_cursor_normal(mainwin);
1585                 if (folder_get_list() != NULL) {
1586                         alertpanel_error(_("Claws Mail has detected a configured "
1587                                    "mailbox, but it is incomplete. It is "
1588                                    "possibly due to a failing IMAP account. Use "
1589                                    "\"Rebuild folder tree\" on the mailbox parent "
1590                                    "folder's context menu to try to fix it."));
1591                 } else {
1592                         alertpanel_error(_("Claws Mail has detected a configured "
1593                                    "mailbox, but could not load it. It is "
1594                                    "probably provided by an out-of-date "
1595                                    "external plugin. Please reinstall the "
1596                                    "plugin and try again."));
1597                         exit_claws(mainwin);
1598 #ifdef G_OS_WIN32
1599                         win32_close_log();
1600 #endif
1601                         exit(1);
1602                 }
1603         }
1604         
1605         static_mainwindow = mainwin;
1606
1607 #ifdef MAEMO
1608         if (prefs_common.data_root != NULL && *prefs_common.data_root != '\0') {
1609                 GnomeVFSVolume *vol = NULL;
1610                 gchar *uri, *mount_path;
1611
1612                 volmon = gnome_vfs_get_volume_monitor();
1613                 vol = gnome_vfs_volume_monitor_get_volume_for_path(volmon, prefs_common.data_root);
1614
1615                 uri = gnome_vfs_volume_get_activation_uri (vol);
1616                 mount_path = uri?gnome_vfs_get_local_path_from_uri (uri):NULL;
1617                 g_free(uri);
1618
1619                 if (vol == NULL || !gnome_vfs_volume_is_mounted(vol) 
1620                     || strcmp(mount_path, prefs_common.data_root)) {
1621                         alertpanel_error(_("Claws Mail can not start without its data volume (%s)."), 
1622                                 prefs_common.data_root);
1623                         g_free(mount_path);
1624                         gnome_vfs_volume_unref(vol);
1625                         exit_claws(mainwin);
1626                         exit(1);
1627                 }
1628                 g_free(mount_path);
1629                 gnome_vfs_volume_unref(vol);
1630                 g_signal_connect(G_OBJECT(volmon), 
1631                                 "volume-mounted", G_CALLBACK(main_vol_mount_cb), mainwin);
1632                 g_signal_connect(G_OBJECT(volmon), 
1633                                 "volume-unmounted", G_CALLBACK(main_vol_unmount_cb), mainwin);
1634         }
1635 #endif
1636
1637 #ifdef HAVE_STARTUP_NOTIFICATION
1638         startup_notification_complete(FALSE);
1639 #endif
1640 #ifdef HAVE_LIBSM
1641         sc_session_manager_connect(mainwin);
1642 #endif
1643
1644         folder_item_update_thaw();
1645         gtk_cmclist_thaw(GTK_CMCLIST(mainwin->folderview->ctree));
1646         main_window_cursor_normal(mainwin);
1647
1648         if (!cmd.target && prefs_common.goto_last_folder_on_startup &&
1649             folder_find_item_from_identifier(prefs_common.last_opened_folder) != NULL &&
1650             !claws_crashed()) {
1651                 cmd.target = prefs_common.last_opened_folder;
1652         }
1653
1654         if (cmd.receive_all && !cmd.target) {
1655                 start_done = FALSE;
1656                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(FALSE));
1657         } else if (prefs_common.chk_on_startup && !cmd.target) {
1658                 start_done = FALSE;
1659                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(TRUE));
1660         } else if (cmd.receive && !cmd.target) {
1661                 start_done = FALSE;
1662                 g_timeout_add(1000, defer_check, NULL);
1663         } 
1664         gtk_widget_grab_focus(folderview->ctree);
1665
1666         if (cmd.compose) {
1667                 open_compose_new(cmd.compose_mailto, cmd.attach_files);
1668         }
1669         if (cmd.attach_files) {
1670                 list_free_strings(cmd.attach_files);
1671                 g_list_free(cmd.attach_files);
1672                 cmd.attach_files = NULL;
1673         }
1674         if (cmd.subscribe) {
1675                 folder_subscribe(cmd.subscribe_uri);
1676         }
1677
1678         if (cmd.send) {
1679                 send_queue();
1680         }
1681         
1682         if (cmd.target) {
1683                 start_done = FALSE;
1684                 g_timeout_add(500, defer_jump, (gpointer)cmd.target);
1685         }
1686
1687         prefs_destroy_cache();
1688         
1689         compose_reopen_exit_drafts();
1690
1691         if (start_done) {
1692                 sc_starting = FALSE;
1693                 main_window_set_menu_sensitive(mainwin);
1694                 toolbar_main_set_sensitive(mainwin);
1695         }
1696
1697         /* register the callback of unix domain socket input */
1698         lock_socket_tag = claws_input_add(lock_socket,
1699                                         G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_PRI,
1700                                         lock_socket_input_cb,
1701                                         mainwin, TRUE);
1702
1703         END_TIMING();
1704
1705         gtk_main();
1706
1707 #ifdef MAEMO
1708         osso_deinitialize(osso_context);
1709 #endif
1710 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1711         if(nm_proxy)
1712                 g_object_unref(nm_proxy);
1713 #endif
1714 #ifdef HAVE_DBUS_GLIB
1715         uninstall_dbus_status_handler();
1716         if(connection)
1717                 dbus_g_connection_unref(connection);
1718 #endif
1719 #ifdef G_OS_WIN32
1720         win32_close_log();
1721 #endif
1722         utils_free_regex();
1723         exit_claws(mainwin);
1724
1725         return 0;
1726 }
1727
1728 static void save_all_caches(FolderItem *item, gpointer data)
1729 {
1730         if (!item->cache) {
1731                 return;
1732         }
1733
1734         if (item->opened) {
1735                 folder_item_close(item);
1736         }
1737
1738         folder_item_free_cache(item, TRUE);
1739 }
1740
1741 static void exit_claws(MainWindow *mainwin)
1742 {
1743         gchar *filename;
1744         gboolean have_connectivity;
1745
1746         sc_exiting = TRUE;
1747
1748         debug_print("shutting down\n");
1749         inc_autocheck_timer_remove();
1750
1751 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1752         if (prefs_common.work_offline && went_offline_nm)
1753                 prefs_common.work_offline = FALSE;
1754 #endif
1755
1756         /* save prefs for opened folder */
1757         if(mainwin->folderview->opened) {
1758                 FolderItem *item;
1759
1760                 item = gtk_cmctree_node_get_row_data(GTK_CMCTREE(mainwin->folderview->ctree), mainwin->folderview->opened);
1761                 summary_save_prefs_to_folderitem(mainwin->folderview->summaryview, item);
1762                 prefs_common.last_opened_folder = folder_item_get_identifier(item);
1763         }
1764
1765         /* save all state before exiting */
1766         folder_func_to_all_folders(save_all_caches, NULL);
1767         folder_write_list();
1768
1769         main_window_get_size(mainwin);
1770         main_window_get_position(mainwin);
1771
1772         prefs_common_write_config();
1773         account_write_config_all();
1774 #ifndef USE_NEW_ADDRBOOK
1775         addressbook_export_to_file();
1776 #endif
1777         filename = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
1778         gtk_accel_map_save(filename);
1779         g_free(filename);
1780
1781         /* delete temporary files */
1782         remove_all_files(get_tmp_dir());
1783         remove_all_files(get_mime_tmp_dir());
1784
1785         close_log_file(LOG_PROTOCOL);
1786         close_log_file(LOG_DEBUG_FILTERING);
1787
1788 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1789         have_connectivity = networkmanager_is_online(NULL); 
1790 #else
1791         have_connectivity = TRUE;
1792 #endif
1793 #ifdef HAVE_LIBETPAN
1794         imap_main_done(have_connectivity);
1795         nntp_main_done(have_connectivity);
1796 #endif
1797         /* delete crashfile */
1798         if (!cmd.crash)
1799                 claws_unlink(get_crashfile_name());
1800
1801         lock_socket_remove();
1802
1803 #ifdef HAVE_LIBSM
1804         if (mainwin->smc_conn)
1805                 SmcCloseConnection ((SmcConn)mainwin->smc_conn, 0, NULL);
1806         mainwin->smc_conn = NULL;
1807 #endif
1808
1809         main_window_destroy_all();
1810         
1811         plugin_unload_all("GTK2");
1812
1813         matcher_done();
1814         prefs_toolbar_done();
1815
1816 #ifndef USE_NEW_ADDRBOOK
1817         addressbook_destroy();
1818 #endif
1819         prefs_themes_done();
1820         prefs_fonts_done();
1821         prefs_ext_prog_done();
1822         prefs_wrapping_done();
1823         prefs_compose_writing_done();
1824         prefs_msg_colors_done();
1825         prefs_image_viewer_done();
1826         image_viewer_done();
1827         prefs_quote_done();
1828         prefs_summaries_done();
1829         prefs_message_done();
1830         prefs_other_done();
1831         prefs_receive_done();
1832         prefs_logging_done();
1833         prefs_send_done();
1834         tags_write_tags();
1835 #ifdef USE_ENCHANT       
1836         prefs_spelling_done();
1837         gtkaspell_checkers_quit();
1838 #endif
1839         plugin_unload_all("Common");
1840         claws_done();
1841 }
1842
1843 #define G_STRING_APPEND_ENCODED_URI(gstring,source)     \
1844         {                                               \
1845                 gchar tmpbuf[BUFFSIZE];                 \
1846                 encode_uri(tmpbuf, BUFFSIZE, (source)); \
1847                 g_string_append((gstring), tmpbuf);     \
1848         }
1849
1850 #define G_PRINT_EXIT(msg)       \
1851         {                       \
1852                 g_print(msg);   \
1853                 exit(1);        \
1854         }
1855
1856 static GString * parse_cmd_compose_from_file(const gchar *fn)
1857 {
1858         GString *headers = g_string_new(NULL);
1859         GString *body = g_string_new(NULL);
1860         gchar *to = NULL;
1861         gchar *h;
1862         gchar *v;
1863         gchar fb[BUFFSIZE];
1864         FILE *fp;
1865         gboolean isstdin;
1866
1867         if (fn == NULL || *fn == '\0')
1868                 G_PRINT_EXIT(_("Missing filename\n"));
1869         isstdin = (*fn == '-' && *(fn + 1) == '\0');
1870         if (isstdin)
1871                 fp = stdin;
1872         else {
1873                 fp = g_fopen(fn, "r");
1874                 if (!fp)
1875                         G_PRINT_EXIT(_("Cannot open filename for reading\n"));
1876         }
1877
1878         while (fgets(fb, sizeof(fb), fp)) {
1879                 gchar *tmp;     
1880                 strretchomp(fb);
1881                 if (*fb == '\0')
1882                         break;
1883                 h = fb;
1884                 while (*h && *h != ':') { ++h; } /* search colon */
1885                 if (*h == '\0')
1886                         G_PRINT_EXIT(_("Malformed header\n"));
1887                 v = h + 1;
1888                 while (*v && *v == ' ') { ++v; } /* trim value start */
1889                 *h = '\0';
1890                 tmp = g_ascii_strdown(fb, -1); /* get header name */
1891                 if (!strcmp(tmp, "to")) {
1892                         if (to != NULL)
1893                                 G_PRINT_EXIT(_("Duplicated 'To:' header\n"));
1894                         to = g_strdup(v);
1895                 } else {
1896                         g_string_append_c(headers, '&');
1897                         g_string_append(headers, tmp);
1898                         g_string_append_c(headers, '=');
1899 #if GLIB_CHECK_VERSION(2,16,0)
1900                         g_string_append_uri_escaped(headers, v, NULL, TRUE);
1901 #else
1902                         G_STRING_APPEND_ENCODED_URI(headers, v);
1903 #endif  
1904                 }
1905                 g_free(tmp);
1906         }
1907         if (to == NULL)
1908                 G_PRINT_EXIT(_("Missing required 'To:' header\n"));
1909         g_string_append(body, to);
1910         g_free(to);
1911         g_string_append(body, "?body=");
1912         while (fgets(fb, sizeof(fb), fp)) {
1913 #if GLIB_CHECK_VERSION(2,16,0)
1914                 g_string_append_uri_escaped(body, fb, NULL, TRUE);
1915 #else
1916                 G_STRING_APPEND_ENCODED_URI(body, fb);
1917 #endif
1918         }
1919         if (!isstdin)
1920                 fclose(fp);
1921         /* append the remaining headers */
1922         g_string_append(body, headers->str);
1923         g_string_free(headers, TRUE);
1924
1925         return body;
1926 }
1927
1928 #undef G_STRING_APPEND_ENCODED_URI
1929 #undef G_PRINT_EXIT
1930
1931 static void parse_cmd_opt(int argc, char *argv[])
1932 {
1933         AttachInfo *ainfo;
1934         gint i;
1935
1936         for (i = 1; i < argc; i++) {
1937                 if (!strncmp(argv[i], "--receive-all", 13)) {
1938                         cmd.receive_all = TRUE;
1939                 } else if (!strncmp(argv[i], "--receive", 9)) {
1940                         cmd.receive = TRUE;
1941                 } else if (!strncmp(argv[i], "--cancel-receiving", 18)) {
1942                         cmd.cancel_receiving = TRUE;
1943                 } else if (!strncmp(argv[i], "--compose-from-file", 19)) {
1944                         const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
1945
1946                         GString *mailto = parse_cmd_compose_from_file(p);
1947                         cmd.compose = TRUE;
1948                         cmd.compose_mailto = mailto->str;
1949                         i++;
1950                 } else if (!strncmp(argv[i], "--compose", 9)) {
1951                         const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
1952
1953                         cmd.compose = TRUE;
1954                         cmd.compose_mailto = NULL;
1955                         if (p && *p != '\0' && *p != '-') {
1956                                 if (!strncmp(p, "mailto:", 7)) {
1957                                         cmd.compose_mailto = p + 7;
1958                                 } else {
1959                                         cmd.compose_mailto = p;
1960                                 }
1961                                 i++;
1962                         }
1963                 } else if (!strncmp(argv[i], "--subscribe", 11)) {
1964                         const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
1965                         if (p && *p != '\0' && *p != '-') {
1966                                 cmd.subscribe = TRUE;
1967                                 cmd.subscribe_uri = p;
1968                         }
1969                 } else if (!strncmp(argv[i], "--attach", 8)) {
1970                         const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
1971                         gchar *file = NULL;
1972
1973                         while (p && *p != '\0' && *p != '-') {
1974                                 if ((file = g_filename_from_uri(p, NULL, NULL)) != NULL) {
1975                                         if (!is_file_exist(file)) {
1976                                                 g_free(file);
1977                                                 file = NULL;
1978                                         }
1979                                 }
1980                                 if (file == NULL && *p != G_DIR_SEPARATOR) {
1981                                         file = g_strconcat(claws_get_startup_dir(),
1982                                                            G_DIR_SEPARATOR_S,
1983                                                            p, NULL);
1984                                 } else if (file == NULL) {
1985                                         file = g_strdup(p);
1986                                 }
1987                                 ainfo = g_new0(AttachInfo, 1);
1988                                 ainfo->file = file;
1989                                 cmd.attach_files = g_list_append(cmd.attach_files, ainfo);
1990                                 i++;
1991                                 p = (i+1 < argc)?argv[i+1]:NULL;
1992                         }
1993                 } else if (!strncmp(argv[i], "--send", 6)) {
1994                         cmd.send = TRUE;
1995                 } else if (!strncmp(argv[i], "--version-full", 14) ||
1996                            !strncmp(argv[i], "-V", 2)) {
1997                         g_print("Claws Mail version " VERSION "\n");
1998                         main_dump_features_list(FALSE);
1999                         exit(0);
2000                 } else if (!strncmp(argv[i], "--version", 9) ||
2001                            !strncmp(argv[i], "-v", 2)) {
2002                         g_print("Claws Mail version " VERSION "\n");
2003                         exit(0);
2004                 } else if (!strncmp(argv[i], "--status-full", 13)) {
2005                         const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
2006  
2007                         cmd.status_full = TRUE;
2008                         while (p && *p != '\0' && *p != '-') {
2009                                 if (!cmd.status_full_folders) {
2010                                         cmd.status_full_folders =
2011                                                 g_ptr_array_new();
2012                                 }
2013                                 g_ptr_array_add(cmd.status_full_folders,
2014                                                 g_strdup(p));
2015                                 i++;
2016                                 p = (i+1 < argc)?argv[i+1]:NULL;
2017                         }
2018                 } else if (!strncmp(argv[i], "--status", 8)) {
2019                         const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
2020  
2021                         cmd.status = TRUE;
2022                         while (p && *p != '\0' && *p != '-') {
2023                                 if (!cmd.status_folders)
2024                                         cmd.status_folders = g_ptr_array_new();
2025                                 g_ptr_array_add(cmd.status_folders,
2026                                                 g_strdup(p));
2027                                 i++;
2028                                 p = (i+1 < argc)?argv[i+1]:NULL;
2029                         }
2030                 } else if (!strncmp(argv[i], "--search", 8)) {
2031                         cmd.search_folder    = (i+1 < argc)?argv[i+1]:NULL;
2032                         cmd.search_type      = (i+2 < argc)?argv[i+2]:NULL;
2033                         cmd.search_request   = (i+3 < argc)?argv[i+3]:NULL;
2034                         const char* rec      = (i+4 < argc)?argv[i+4]:NULL;
2035                         cmd.search_recursive = TRUE;
2036                         if (rec && (tolower(*rec)=='n' || tolower(*rec)=='f' || *rec=='0'))
2037                                 cmd.search_recursive = FALSE;
2038                         if (cmd.search_folder && cmd.search_type && cmd.search_request)
2039                                 cmd.search = TRUE;
2040                 } else if (!strncmp(argv[i], "--online", 8)) {
2041                         cmd.online_mode = ONLINE_MODE_ONLINE;
2042                 } else if (!strncmp(argv[i], "--offline", 9)) {
2043                         cmd.online_mode = ONLINE_MODE_OFFLINE;
2044                 } else if (!strncmp(argv[i], "--statistics", 12)) {
2045                         cmd.statistics = TRUE;
2046                 } else if (!strncmp(argv[i], "--reset-statistics", 18)) {
2047                         cmd.reset_statistics = TRUE;
2048                 } else if (!strncmp(argv[i], "--help", 6) ||
2049                            !strncmp(argv[i], "-h", 2)) {
2050                         gchar *base = g_path_get_basename(argv[0]);
2051                         g_print(_("Usage: %s [OPTION]...\n"), base);
2052
2053                         g_print("%s\n", _("  --compose [address]    open composition window"));
2054                         g_print("%s\n", _("  --compose-from-file file\n"
2055                                           "                         open composition window with data from given file;\n"
2056                                           "                         use - as file name for reading from standard input;\n"
2057                                           "                         content format: headers first (To: required) until an\n"
2058                                           "                         empty line, then mail body until end of file."));
2059                         g_print("%s\n", _("  --subscribe [uri]      subscribe to the given URI if possible"));
2060                         g_print("%s\n", _("  --attach file1 [file2]...\n"
2061                                           "                         open composition window with specified files\n"
2062                                           "                         attached"));
2063                         g_print("%s\n", _("  --receive              receive new messages"));
2064                         g_print("%s\n", _("  --receive-all          receive new messages of all accounts"));
2065                         g_print("%s\n", _("  --cancel-receiving     cancel receiving of messages"));
2066                         g_print("%s\n", _("  --search folder type request [recursive]\n"
2067                                           "                         searches mail\n"
2068                                           "                         folder ex.: \"#mh/Mailbox/inbox\" or \"Mail\"\n"
2069                                           "                         type: s[ubject],f[rom],t[o],e[xtended],m[ixed] or g: tag\n"
2070                                           "                         request: search string\n"
2071                                           "                         recursive: false if arg. starts with 0, n, N, f or F"));
2072
2073                         g_print("%s\n", _("  --send                 send all queued messages"));
2074                         g_print("%s\n", _("  --status [folder]...   show the total number of messages"));
2075                         g_print("%s\n", _("  --status-full [folder]...\n"
2076                                           "                         show the status of each folder"));
2077                         g_print("%s\n", _("  --statistics           show session statistics"));
2078                         g_print("%s\n", _("  --reset-statistics     reset session statistics"));
2079                         g_print("%s\n", _("  --select folder[/msg]  jumps to the specified folder/message\n" 
2080                                           "                         folder is a folder id like 'folder/sub_folder'"));
2081                         g_print("%s\n", _("  --online               switch to online mode"));
2082                         g_print("%s\n", _("  --offline              switch to offline mode"));
2083                         g_print("%s\n", _("  --exit --quit -q       exit Claws Mail"));
2084                         g_print("%s\n", _("  --debug                debug mode"));
2085                         g_print("%s\n", _("  --help -h              display this help and exit"));
2086                         g_print("%s\n", _("  --version -v           output version information and exit"));
2087                         g_print("%s\n", _("  --version-full -V      output version and built-in features information and exit"));
2088                         g_print("%s\n", _("  --config-dir           output configuration directory"));
2089                         g_print("%s\n", _("  --alternate-config-dir [dir]\n"
2090                                           "                         use specified configuration directory"));
2091
2092                         g_free(base);
2093                         exit(1);
2094                 } else if (!strncmp(argv[i], "--crash", 7)) {
2095                         cmd.crash = TRUE;
2096                         cmd.crash_params = g_strdup((i+1 < argc)?argv[i+1]:NULL);
2097                         i++;
2098                 } else if (!strncmp(argv[i], "--config-dir", sizeof "--config-dir" - 1)) {
2099                         g_print(RC_DIR "\n");
2100                         exit(0);
2101                 } else if (!strncmp(argv[i], "--alternate-config-dir", sizeof "--alternate-config-dir" - 1) && i+1 < argc) {
2102                         set_rc_dir(argv[i+1]);
2103                 } else if (!strncmp(argv[i], "--exit", 6) ||
2104                            !strncmp(argv[i], "--quit", 6) ||
2105                            !strncmp(argv[i], "-q", 2)) {
2106                         cmd.exit = TRUE;
2107                 } else if (!strncmp(argv[i], "--select", 8) && i+1 < argc) {
2108                         cmd.target = argv[i+1];
2109                 } else if (i == 1 && argc == 2) {
2110                         /* only one parameter. Do something intelligent about it */
2111                         if ((strstr(argv[i], "@")||!strncmp(argv[i], "mailto:", 7)) && !strstr(argv[i], "://")) {
2112                                 const gchar *p = argv[i];
2113
2114                                 cmd.compose = TRUE;
2115                                 cmd.compose_mailto = NULL;
2116                                 if (p && *p != '\0' && *p != '-') {
2117                                         if (!strncmp(p, "mailto:", 7)) {
2118                                                 cmd.compose_mailto = p + 7;
2119                                         } else {
2120                                                 cmd.compose_mailto = p;
2121                                         }
2122                                 }
2123                         } else if (!strncmp(argv[i], "file://", 7)) {
2124                                 cmd.target = argv[i];
2125                         } else if (!strncmp(argv[i], "?attach=file://", strlen("?attach=file://"))) {
2126                                 cmd.compose = TRUE;
2127                                 cmd.compose_mailto = argv[i];
2128                         } else if (strstr(argv[i], "://")) {
2129                                 const gchar *p = argv[i];
2130                                 if (p && *p != '\0' && *p != '-') {
2131                                         cmd.subscribe = TRUE;
2132                                         cmd.subscribe_uri = p;
2133                                 }
2134                         } else if (!strcmp(argv[i], "--sync")) {
2135                                 /* gtk debug */
2136                         } else if (is_dir_exist(argv[i]) || is_file_exist(argv[i])) {
2137                                 cmd.target = argv[i];
2138                         } else {
2139                                 g_print(_("Unknown option\n"));
2140                                 exit(1);
2141                         }
2142                 }
2143         }
2144
2145         if (cmd.attach_files && cmd.compose == FALSE) {
2146                 cmd.compose = TRUE;
2147                 cmd.compose_mailto = NULL;
2148         }
2149 }
2150
2151 static void initial_processing(FolderItem *item, gpointer data)
2152 {
2153         MainWindow *mainwin = (MainWindow *)data;
2154         gchar *buf;
2155
2156         cm_return_if_fail(item);
2157         buf = g_strdup_printf(_("Processing (%s)..."), 
2158                               item->path 
2159                               ? item->path 
2160                               : _("top level folder"));
2161         g_free(buf);
2162
2163         
2164         if (item->prefs->enable_processing) {
2165                 item->processing_pending = TRUE;
2166                 folder_item_apply_processing(item);
2167                 item->processing_pending = FALSE;
2168         }
2169
2170         STATUSBAR_POP(mainwin);
2171 }
2172
2173 static gboolean draft_all_messages(void)
2174 {
2175         GList *compose_list = NULL;
2176         
2177         compose_clear_exit_drafts();
2178         compose_list = compose_get_compose_list();
2179         while (compose_list != NULL) {
2180                 Compose *c = (Compose*)compose_list->data;
2181                 if (!compose_draft(c, COMPOSE_DRAFT_FOR_EXIT))
2182                         return FALSE;
2183                 compose_list = compose_get_compose_list();
2184         }
2185         return TRUE;
2186 }
2187 gboolean clean_quit(gpointer data)
2188 {
2189         static gboolean firstrun = TRUE;
2190
2191         if (!firstrun) {
2192                 return FALSE;
2193         }
2194         firstrun = FALSE;
2195
2196         /*!< Good idea to have the main window stored in a 
2197          *   static variable so we can check that variable
2198          *   to see if we're really allowed to do things
2199          *   that actually the spawner is supposed to 
2200          *   do (like: sending mail, composing messages).
2201          *   Because, really, if we're the spawnee, and
2202          *   we touch GTK stuff, we're hosed. See the 
2203          *   next fixme. */
2204
2205         /* FIXME: Use something else to signal that we're
2206          * in the original spawner, and not in a spawned
2207          * child. */
2208         if (!static_mainwindow) {
2209                 return FALSE;
2210         }
2211                 
2212         draft_all_messages();
2213         emergency_exit = TRUE;
2214         exit_claws(static_mainwindow);
2215         exit(0);
2216
2217         return FALSE;
2218 }
2219
2220 void app_will_exit(GtkWidget *widget, gpointer data)
2221 {
2222         MainWindow *mainwin = data;
2223         
2224         if (gtk_main_level() == 0) {
2225                 debug_print("not even started\n");
2226                 return;
2227         }
2228         if (sc_exiting == TRUE) {
2229                 debug_print("exit pending\n");
2230                 return;
2231         }
2232         sc_exiting = TRUE;
2233         debug_print("exiting\n");
2234         if (compose_get_compose_list()) {
2235                 if (!draft_all_messages()) {
2236                         main_window_popup(mainwin);
2237                         sc_exiting = FALSE;
2238                         return;
2239                 }
2240         }
2241
2242         if (prefs_common.warn_queued_on_exit && procmsg_have_queued_mails_fast()) {
2243                 if (alertpanel(_("Queued messages"),
2244                                _("Some unsent messages are queued. Exit now?"),
2245                                GTK_STOCK_CANCEL, GTK_STOCK_OK, NULL)
2246                     != G_ALERTALTERNATE) {
2247                         main_window_popup(mainwin);
2248                         sc_exiting = FALSE;
2249                         return;
2250                 }
2251                 manage_window_focus_in(mainwin->window, NULL, NULL);
2252         }
2253
2254         sock_cleanup();
2255 #ifdef HAVE_VALGRIND
2256         if (RUNNING_ON_VALGRIND) {
2257                 summary_clear_list(mainwin->summaryview);
2258         }
2259 #endif
2260         if (folderview_get_selected_item(mainwin->folderview))
2261                 folder_item_close(folderview_get_selected_item(mainwin->folderview));
2262         gtk_main_quit();
2263 }
2264
2265 gboolean claws_is_exiting(void)
2266 {
2267         return sc_exiting;
2268 }
2269
2270 gboolean claws_is_starting(void)
2271 {
2272         return sc_starting;
2273 }
2274
2275 /*
2276  * CLAWS: want this public so crash dialog can delete the
2277  * lock file too
2278  */
2279 gchar *claws_get_socket_name(void)
2280 {
2281         static gchar *filename = NULL;
2282         const gchar *socket_dir = NULL;
2283         
2284         if (rc_dir_is_alt())
2285                 socket_dir = get_rc_dir();
2286         else
2287                 socket_dir = g_get_tmp_dir();
2288         if (filename == NULL) {
2289                 filename = g_strdup_printf("%s%cclaws-mail-%d",
2290                                            socket_dir, G_DIR_SEPARATOR,
2291 #if HAVE_GETUID
2292                                            getuid());
2293 #else
2294                                            0);                                          
2295 #endif
2296         }
2297
2298         return filename;
2299 }
2300
2301 static gchar *get_crashfile_name(void)
2302 {
2303         static gchar *filename = NULL;
2304
2305         if (filename == NULL) {
2306                 filename = g_strdup_printf("%s%cclaws-crashed",
2307                                            get_tmp_dir(), G_DIR_SEPARATOR);
2308         }
2309
2310         return filename;
2311 }
2312
2313 static gint prohibit_duplicate_launch(void)
2314 {
2315         gint uxsock;
2316         GList *curr;
2317 #ifdef G_OS_UNIX
2318         gchar *path;
2319
2320         path = claws_get_socket_name();
2321         /* Try to connect to the control socket */
2322         uxsock = fd_connect_unix(path);
2323         
2324         if (x_display == NULL)
2325                 x_display = g_strdup(g_getenv("DISPLAY"));
2326
2327         if (uxsock < 0) {
2328 #if HAVE_FLOCK
2329                 gchar *socket_lock;
2330                 gint lock_fd;
2331                 gint ret;
2332                 /* If connect failed, no other process is running.
2333                  * Unlink the potentially existing socket, then
2334                  * open it. This has to be done locking a temporary
2335                  * file to avoid the race condition where another
2336                  * process could have created the socket just in
2337                  * between.
2338                  */
2339                 socket_lock = g_strconcat(path, ".lock",
2340                                           NULL);
2341                 lock_fd = g_open(socket_lock, O_RDWR|O_CREAT, 0);
2342                 if (lock_fd < 0) {
2343                         debug_print("Couldn't open %s: %s (%d)\n", socket_lock,
2344                                 strerror(errno), errno);
2345                         g_free(socket_lock);
2346                         return -1;
2347                 }
2348                 if (flock(lock_fd, LOCK_EX) < 0) {
2349                         debug_print("Couldn't lock %s: %s (%d)\n", socket_lock,
2350                                 strerror(errno), errno);
2351                         close(lock_fd);
2352                         g_free(socket_lock);
2353                         return -1;
2354                 }
2355 #endif
2356
2357                 claws_unlink(path);
2358                 debug_print("Opening socket %s\n", path);
2359                 ret = fd_open_unix(path);
2360 #if HAVE_FLOCK
2361                 flock(lock_fd, LOCK_UN);
2362                 claws_unlink(socket_lock);
2363                 g_free(socket_lock);
2364 #endif
2365                 return ret;
2366         }
2367 #else
2368         HANDLE hmutex;
2369
2370         hmutex = CreateMutexA(NULL, FALSE, "ClawsMail");
2371         if (!hmutex) {
2372                 debug_print("cannot create Mutex\n");
2373                 return -1;
2374         }
2375         if (GetLastError() != ERROR_ALREADY_EXISTS) {
2376                 uxsock = fd_open_inet(50216);
2377                 if (uxsock < 0)
2378                         return 0;
2379                 return uxsock;
2380         }
2381
2382         uxsock = fd_connect_inet(50216);
2383         if (uxsock < 0)
2384                 return -1;
2385 #endif
2386         /* remote command mode */
2387
2388         debug_print("another Claws Mail instance is already running.\n");
2389
2390         if (cmd.receive_all) {
2391                 fd_write_all(uxsock, "receive_all\n", 12);
2392         } else if (cmd.receive) {
2393                 fd_write_all(uxsock, "receive\n", 8);
2394         } else if (cmd.cancel_receiving) {
2395                 fd_write_all(uxsock, "cancel_receiving\n", 17);
2396         } else if (cmd.compose && cmd.attach_files) {
2397                 gchar *str, *compose_str;
2398
2399                 if (cmd.compose_mailto) {
2400                         compose_str = g_strdup_printf("compose_attach %s\n",
2401                                                       cmd.compose_mailto);
2402                 } else {
2403                         compose_str = g_strdup("compose_attach\n");
2404                 }
2405
2406                 fd_write_all(uxsock, compose_str, strlen(compose_str));
2407                 g_free(compose_str);
2408
2409                 for (curr = cmd.attach_files; curr != NULL ; curr = curr->next) {
2410                         str = (gchar *) ((AttachInfo *)curr->data)->file;
2411                         fd_write_all(uxsock, str, strlen(str));
2412                         fd_write_all(uxsock, "\n", 1);
2413                 }
2414
2415                 fd_write_all(uxsock, ".\n", 2);
2416         } else if (cmd.compose) {
2417                 gchar *compose_str;
2418
2419                 if (cmd.compose_mailto) {
2420                         compose_str = g_strdup_printf
2421                                 ("compose %s\n", cmd.compose_mailto);
2422                 } else {
2423                         compose_str = g_strdup("compose\n");
2424                 }
2425
2426                 fd_write_all(uxsock, compose_str, strlen(compose_str));
2427                 g_free(compose_str);
2428         } else if (cmd.subscribe) {
2429                 gchar *str = g_strdup_printf("subscribe %s\n", cmd.subscribe_uri);
2430                 fd_write_all(uxsock, str, strlen(str));
2431                 g_free(str);
2432         } else if (cmd.send) {
2433                 fd_write_all(uxsock, "send\n", 5);
2434         } else if (cmd.online_mode == ONLINE_MODE_ONLINE) {
2435                 fd_write(uxsock, "online\n", 6);
2436         } else if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
2437                 fd_write(uxsock, "offline\n", 7);
2438         } else if (cmd.status || cmd.status_full) {
2439                 gchar buf[BUFFSIZE];
2440                 gint i;
2441                 const gchar *command;
2442                 GPtrArray *folders;
2443                 gchar *folder;
2444  
2445                 command = cmd.status_full ? "status-full\n" : "status\n";
2446                 folders = cmd.status_full ? cmd.status_full_folders :
2447                         cmd.status_folders;
2448  
2449                 fd_write_all(uxsock, command, strlen(command));
2450                 for (i = 0; folders && i < folders->len; ++i) {
2451                         folder = g_ptr_array_index(folders, i);
2452                         fd_write_all(uxsock, folder, strlen(folder));
2453                         fd_write_all(uxsock, "\n", 1);
2454                 }
2455                 fd_write_all(uxsock, ".\n", 2);
2456                 for (;;) {
2457                         fd_gets(uxsock, buf, sizeof(buf));
2458                         if (!strncmp(buf, ".\n", 2)) break;
2459                         fputs(buf, stdout);
2460                 }
2461         } else if (cmd.exit) {
2462                 fd_write_all(uxsock, "exit\n", 5);
2463         } else if (cmd.statistics) {
2464                 gchar buf[BUFSIZ];
2465                 fd_write(uxsock, "statistics\n", 11);
2466                 for (;;) {
2467                         fd_gets(uxsock, buf, sizeof(buf));
2468                         if (!strncmp(buf, ".\n", 2)) break;
2469                         fputs(buf, stdout);
2470                 }
2471         } else if (cmd.reset_statistics) {
2472                 fd_write(uxsock, "reset_statistics\n", 17);
2473         } else if (cmd.target) {
2474                 gchar *str = g_strdup_printf("select %s\n", cmd.target);
2475                 fd_write_all(uxsock, str, strlen(str));
2476                 g_free(str);
2477         } else if (cmd.search) {
2478                 gchar buf[BUFFSIZE];
2479                 gchar *str =
2480                         g_strdup_printf("search %s\n%s\n%s\n%c\n",
2481                                                         cmd.search_folder, cmd.search_type, cmd.search_request,
2482                                                         (cmd.search_recursive==TRUE)?'1':'0');
2483                 fd_write_all(uxsock, str, strlen(str));
2484                 g_free(str);
2485                 for (;;) {
2486                         fd_gets(uxsock, buf, sizeof(buf));
2487                         if (!strncmp(buf, ".\n", 2)) break;
2488                         fputs(buf, stdout);
2489                 }
2490         } else {
2491 #ifndef G_OS_WIN32
2492                 gchar buf[BUFSIZ];
2493                 fd_write_all(uxsock, "get_display\n", 12);
2494                 memset(buf, 0, sizeof(buf));
2495                 fd_gets(uxsock, buf, sizeof(buf));
2496                 if (strcmp2(buf, x_display)) {
2497                         g_print("Claws Mail is already running on display %s.\n",
2498                                 buf);
2499                 } else {
2500                         fd_close(uxsock);
2501                         uxsock = fd_connect_unix(path);
2502                         fd_write_all(uxsock, "popup\n", 6);
2503                 }
2504 #else
2505                 fd_write_all(uxsock, "popup\n", 6);
2506 #endif
2507         }
2508
2509         fd_close(uxsock);
2510         return -1;
2511 }
2512
2513 static gint lock_socket_remove(void)
2514 {
2515 #ifdef G_OS_UNIX
2516         gchar *filename;
2517 #endif
2518         if (lock_socket < 0) {
2519                 return -1;
2520         }
2521
2522         if (lock_socket_tag > 0) {
2523                 g_source_remove(lock_socket_tag);
2524         }
2525         fd_close(lock_socket);
2526
2527 #ifdef G_OS_UNIX
2528         filename = claws_get_socket_name();
2529         claws_unlink(filename);
2530 #endif
2531
2532         return 0;
2533 }
2534
2535 static GPtrArray *get_folder_item_list(gint sock)
2536 {
2537         gchar buf[BUFFSIZE];
2538         FolderItem *item;
2539         GPtrArray *folders = NULL;
2540
2541         for (;;) {
2542                 fd_gets(sock, buf, sizeof(buf));
2543                 if (!strncmp(buf, ".\n", 2)) {
2544                         break;
2545                 }
2546                 strretchomp(buf);
2547                 if (!folders) {
2548                         folders = g_ptr_array_new();
2549                 }
2550                 item = folder_find_item_from_identifier(buf);
2551                 if (item) {
2552                         g_ptr_array_add(folders, item);
2553                 } else {
2554                         g_warning("no such folder: %s\n", buf);
2555                 }
2556         }
2557
2558         return folders;
2559 }
2560
2561 static void lock_socket_input_cb(gpointer data,
2562                                  gint source,
2563                                  GIOCondition condition)
2564 {
2565         MainWindow *mainwin = (MainWindow *)data;
2566         gint sock;
2567         gchar buf[BUFFSIZE];
2568
2569         sock = fd_accept(source);
2570         fd_gets(sock, buf, sizeof(buf));
2571
2572         if (!strncmp(buf, "popup", 5)) {
2573                 main_window_popup(mainwin);
2574         } else if (!strncmp(buf, "get_display", 11)) {
2575                 fd_write_all(sock, x_display, strlen(x_display));
2576         } else if (!strncmp(buf, "receive_all", 11)) {
2577                 inc_all_account_mail(mainwin, FALSE,
2578                                      prefs_common.newmail_notify_manu);
2579         } else if (!strncmp(buf, "receive", 7)) {
2580                 inc_mail(mainwin, prefs_common.newmail_notify_manu);
2581         } else if (!strncmp(buf, "cancel_receiving", 16)) {
2582                 inc_cancel_all();
2583                 imap_cancel_all();
2584         } else if (!strncmp(buf, "compose_attach", 14)) {
2585                 GList *files = NULL, *curr;
2586                 AttachInfo *ainfo;
2587                 gchar *mailto;
2588
2589                 mailto = g_strdup(buf + strlen("compose_attach") + 1);
2590                 while (fd_gets(sock, buf, sizeof(buf)) > 0) {
2591                         strretchomp(buf);
2592                         if (!strcmp2(buf, "."))
2593                                 break;
2594                                 
2595                         ainfo = g_new0(AttachInfo, 1);
2596                         ainfo->file = g_strdup(buf);
2597                         files = g_list_append(files, ainfo);
2598                 }
2599                 open_compose_new(mailto, files);
2600                 
2601                 curr = g_list_first(files);
2602                 while (curr != NULL) {
2603                         ainfo = (AttachInfo *)curr->data;
2604                         g_free(ainfo->file);
2605                         g_free(ainfo);
2606                         curr = curr->next;
2607                 }
2608                 g_list_free(files);
2609                 g_free(mailto);
2610         } else if (!strncmp(buf, "compose", 7)) {
2611                 open_compose_new(buf + strlen("compose") + 1, NULL);
2612         } else if (!strncmp(buf, "subscribe", 9)) {
2613                 main_window_popup(mainwin);
2614                 folder_subscribe(buf + strlen("subscribe") + 1);
2615         } else if (!strncmp(buf, "send", 4)) {
2616                 send_queue();
2617         } else if (!strncmp(buf, "online", 6)) {
2618                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
2619         } else if (!strncmp(buf, "offline", 7)) {
2620                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
2621         } else if (!strncmp(buf, "status-full", 11) ||
2622                    !strncmp(buf, "status", 6)) {
2623                 gchar *status;
2624                 GPtrArray *folders;
2625  
2626                 folders = get_folder_item_list(sock);
2627                 status = folder_get_status
2628                         (folders, !strncmp(buf, "status-full", 11));
2629                 fd_write_all(sock, status, strlen(status));
2630                 fd_write_all(sock, ".\n", 2);
2631                 g_free(status);
2632                 if (folders) g_ptr_array_free(folders, TRUE);
2633         } else if (!strncmp(buf, "statistics", 10)) {
2634                 gchar tmp[BUFSIZ];
2635
2636                 g_snprintf(tmp, sizeof(tmp), _("Session statistics\n"));
2637                 fd_write_all(sock, tmp, strlen(tmp));
2638
2639                 if (prefs_common.date_format) {
2640                         struct tm *lt;
2641                         gint len = 100;
2642                         gchar date[len];
2643
2644                         lt = localtime(&session_stats.time_started);
2645                         fast_strftime(date, len, prefs_common.date_format, lt);
2646                         g_snprintf(tmp, sizeof(tmp), _("Started: %s\n"),
2647                                         lt ? date : ctime(&session_stats.time_started));
2648                 } else
2649                         g_snprintf(tmp, sizeof(tmp), _("Started: %s\n"),
2650                                         ctime(&session_stats.time_started));
2651                 fd_write_all(sock, tmp, strlen(tmp));
2652
2653                 fd_write_all(sock, "\n", 1);
2654
2655                 g_snprintf(tmp, sizeof(tmp), _("Incoming traffic\n"));
2656                 fd_write_all(sock, tmp, strlen(tmp));
2657
2658                 g_snprintf(tmp, sizeof(tmp), _("Received messages: %d\n"),
2659                                 session_stats.received);
2660                 fd_write_all(sock, tmp, strlen(tmp));
2661
2662                 fd_write_all(sock, "\n", 1);
2663
2664                 g_snprintf(tmp, sizeof(tmp), _("Outgoing traffic\n"));
2665                 fd_write_all(sock, tmp, strlen(tmp));
2666
2667                 g_snprintf(tmp, sizeof(tmp), _("New/redirected messages: %d\n"),
2668                                 session_stats.sent);
2669                 fd_write_all(sock, tmp, strlen(tmp));
2670
2671                 g_snprintf(tmp, sizeof(tmp), _("Replied messages: %d\n"),
2672                                 session_stats.replied);
2673                 fd_write_all(sock, tmp, strlen(tmp));
2674
2675                 g_snprintf(tmp, sizeof(tmp), _("Forwarded messages: %d\n"),
2676                                 session_stats.forwarded);
2677                 fd_write_all(sock, tmp, strlen(tmp));
2678
2679                 g_snprintf(tmp, sizeof(tmp), _("Total outgoing messages: %d\n"),
2680                                 (session_stats.sent + session_stats.replied +
2681                                  session_stats.forwarded));
2682                 fd_write_all(sock, tmp, strlen(tmp));
2683
2684                 fd_write_all(sock, ".\n", 2);
2685         } else if (!strncmp(buf, "reset_statistics", 16)) {
2686                 reset_statistics();
2687         } else if (!strncmp(buf, "select ", 7)) {
2688                 const gchar *target = buf+7;
2689                 mainwindow_jump_to(target, TRUE);
2690         } else if (!strncmp(buf, "search ", 7)) {
2691                 FolderItem* folderItem = NULL;
2692                 GSList *messages = NULL;
2693                 gchar *folder_name = NULL;
2694                 gchar *request = NULL;
2695                 AdvancedSearch *search;
2696                 gboolean recursive;
2697                 AdvancedSearchType searchType = ADVANCED_SEARCH_EXTENDED;
2698                 
2699                 search = advsearch_new();
2700
2701                 folder_name = g_strdup(buf+7);
2702                 strretchomp(folder_name);
2703
2704                 if (fd_gets(sock, buf, sizeof(buf)) <= 0) 
2705                         goto search_exit;
2706
2707                 switch (toupper(buf[0])) {
2708                 case 'S': searchType = ADVANCED_SEARCH_SUBJECT; break;
2709                 case 'F': searchType = ADVANCED_SEARCH_FROM; break;
2710                 case 'T': searchType = ADVANCED_SEARCH_TO; break;
2711                 case 'M': searchType = ADVANCED_SEARCH_MIXED; break;
2712                 case 'G': searchType = ADVANCED_SEARCH_TAG; break;
2713                 case 'E': searchType = ADVANCED_SEARCH_EXTENDED; break;
2714                 }
2715
2716                 if (fd_gets(sock, buf, sizeof(buf)) <= 0) 
2717                         goto search_exit;
2718
2719                 request = g_strdup(buf);
2720                 strretchomp(request);
2721
2722                 recursive = TRUE;
2723                 if (fd_gets(sock, buf, sizeof(buf)) > 0)
2724                         recursive = buf[0] != '0';
2725
2726                 debug_print("search: %s %i %s %i\n", folder_name, searchType, request, recursive);
2727
2728                 if (folder_name)
2729                         folderItem = folder_find_item_from_identifier(folder_name);
2730
2731                 if (folder_name && folderItem == NULL) {
2732                         debug_print("Unknown folder item : '%s', searching folder\n",folder_name);
2733                         Folder* folder = folder_find_from_path(folder_name);
2734                         if (folder != NULL)
2735                                 folderItem = FOLDER_ITEM(folder->node->data);
2736                         else
2737                                 debug_print("Unknown folder: '%s'\n",folder_name);
2738                 } else {
2739                         debug_print("%s %s\n",folderItem->name, folderItem->path);
2740                 }
2741
2742                 if (folderItem != NULL) {
2743                         advsearch_set(search, searchType, request);
2744                         advsearch_search_msgs_in_folders(search, &messages, folderItem, recursive);
2745                 } else {
2746                         g_print("Folder '%s' not found.\n'", folder_name);
2747                 }
2748
2749                 GSList *cur;
2750                 for (cur = messages; cur != NULL; cur = cur->next) {
2751                         MsgInfo* msg = (MsgInfo *)cur->data;
2752                         gchar *file = procmsg_get_message_file_path(msg);
2753                         fd_write_all(sock, file, strlen(file));
2754                         fd_write_all(sock, "\n", 1);
2755                         g_free(file);
2756                 }
2757                 fd_write_all(sock, ".\n", 2);
2758
2759 search_exit:
2760                 g_free(folder_name);
2761                 g_free(request);
2762                 advsearch_free(search);
2763                 if (messages != NULL)
2764                         procmsg_msg_list_free(messages);
2765         } else if (!strncmp(buf, "exit", 4)) {
2766                 if (prefs_common.clean_on_exit && !prefs_common.ask_on_clean) {
2767                         procmsg_empty_all_trash();
2768                 }
2769                 app_will_exit(NULL, mainwin);
2770         }
2771         fd_close(sock);
2772
2773 }
2774
2775 static void open_compose_new(const gchar *address, GList *attach_files)
2776 {
2777         gchar *addr = NULL;
2778
2779         if (address) {
2780                 Xstrdup_a(addr, address, return);
2781                 g_strstrip(addr);
2782         }
2783
2784         compose_new(NULL, addr, attach_files);
2785 }
2786
2787 static void send_queue(void)
2788 {
2789         GList *list;
2790         gchar *errstr = NULL;
2791         gboolean error = FALSE;
2792         for (list = folder_get_list(); list != NULL; list = list->next) {
2793                 Folder *folder = list->data;
2794
2795                 if (folder->queue) {
2796                         gint res = procmsg_send_queue
2797                                 (folder->queue, prefs_common.savemsg,
2798                                 &errstr);
2799
2800                         if (res) {
2801                                 folder_item_scan(folder->queue);
2802                         }
2803                         
2804                         if (res < 0)
2805                                 error = TRUE;
2806                 }
2807         }
2808         if (errstr) {
2809                 alertpanel_error_log(_("Some errors occurred "
2810                                 "while sending queued messages:\n%s"), errstr);
2811                 g_free(errstr);
2812         } else if (error) {
2813                 alertpanel_error_log("Some errors occurred "
2814                                 "while sending queued messages.");
2815         }
2816 }
2817
2818 static void quit_signal_handler(int sig)
2819 {
2820         debug_print("Quitting on signal %d\n", sig);
2821
2822         g_timeout_add(0, clean_quit, NULL);
2823 }
2824
2825 static void install_basic_sighandlers()
2826 {
2827 #ifndef G_OS_WIN32
2828         sigset_t    mask;
2829         struct sigaction act;
2830
2831         sigemptyset(&mask);
2832
2833 #ifdef SIGTERM
2834         sigaddset(&mask, SIGTERM);
2835 #endif
2836 #ifdef SIGINT
2837         sigaddset(&mask, SIGINT);
2838 #endif
2839 #ifdef SIGHUP
2840         sigaddset(&mask, SIGHUP);
2841 #endif
2842
2843         act.sa_handler = quit_signal_handler;
2844         act.sa_mask    = mask;
2845         act.sa_flags   = 0;
2846
2847 #ifdef SIGTERM
2848         sigaction(SIGTERM, &act, 0);
2849 #endif
2850 #ifdef SIGINT
2851         sigaction(SIGINT, &act, 0);
2852 #endif  
2853 #ifdef SIGHUP
2854         sigaction(SIGHUP, &act, 0);
2855 #endif  
2856
2857         sigprocmask(SIG_UNBLOCK, &mask, 0);
2858 #endif /* !G_OS_WIN32 */
2859 }
2860
2861 #if (defined linux && defined SIGIO)
2862 static int mem_notify_fd = 0;
2863
2864 static gboolean clean_caches(gpointer unused)
2865 {
2866         if (static_mainwindow && static_mainwindow->lock_count > 0)
2867                 return TRUE;
2868         debug_print("/dev/mem_notify: callback: Freeing some memory now!\n");
2869         folder_clean_cache_memory_force();
2870         return FALSE;
2871 }
2872
2873 static void memory_signal_handler(int sig)
2874 {
2875         debug_print("/dev/mem_notify: Kernel says we should free up some memory!\n");
2876         g_timeout_add(10, clean_caches, NULL); 
2877 }
2878
2879 static void install_memory_sighandler()
2880 {
2881         sigset_t    mask;
2882         struct sigaction act;
2883         int flags;
2884
2885         mem_notify_fd = g_open("/dev/mem_notify", O_RDONLY|O_NONBLOCK, 0);
2886         if (mem_notify_fd == -1) {
2887                 debug_print("/dev/mem_notify not available (%s)\n", 
2888                         strerror(errno));
2889                 return;
2890         }
2891         
2892         fcntl(mem_notify_fd, F_SETOWN, getpid());
2893         flags = fcntl(mem_notify_fd, F_GETFL);
2894         fcntl(mem_notify_fd, flags|FASYNC);
2895
2896         sigemptyset(&mask);
2897
2898         sigaddset(&mask, SIGIO);
2899
2900         act.sa_handler = memory_signal_handler;
2901         act.sa_mask    = mask;
2902         act.sa_flags   = 0;
2903
2904         sigaction(SIGIO, &act, 0);
2905
2906         sigprocmask(SIG_UNBLOCK, &mask, 0);
2907
2908         debug_print("/dev/mem_notify: installed handler\n");
2909 }
2910 #endif /* linux && SIGIO */
2911
2912 #ifdef MAEMO
2913 osso_context_t *get_osso_context(void)
2914 {
2915         return static_osso_context;
2916 }
2917 #endif
2918
2919
2920 #ifdef HAVE_NETWORKMANAGER_SUPPORT
2921 static void networkmanager_state_change_cb(DBusGProxy *proxy, gchar *dev,
2922                                          gpointer data)
2923 {
2924         MainWindow *mainWin;
2925
2926         mainWin = NULL;
2927         if (static_mainwindow)
2928                 mainWin = static_mainwindow;
2929         else if (data)
2930                 mainWin = (MainWindow*)data;
2931         
2932         if (!prefs_common.use_networkmanager)
2933                 return;
2934
2935         if (mainWin) {
2936                 GError *error;
2937                 gboolean online;
2938
2939                 error = NULL;           
2940                 online = networkmanager_is_online(&error);
2941                 if(!error) {
2942                         if(online && went_offline_nm) {
2943                                 went_offline_nm = FALSE;
2944                                 main_window_toggle_work_offline(mainWin, FALSE, FALSE);
2945                                 debug_print("NetworkManager: Went online\n");
2946                                 log_message(LOG_PROTOCOL, _("NetworkManager: network is online.\n"));
2947                         }
2948                         else if(!online) {
2949                                 went_offline_nm = TRUE;
2950                                 main_window_toggle_work_offline(mainWin, TRUE, FALSE);
2951                                 debug_print("NetworkManager: Went offline\n");
2952                                 log_message(LOG_PROTOCOL, _("NetworkManager: network is offline.\n"));
2953                         }
2954                 }
2955                 else {
2956                         debug_print("Failed to get online information from NetworkManager: %s\n",
2957                                                          error->message);
2958                         g_error_free(error);
2959                 }
2960         }
2961         else
2962                 debug_print("NetworkManager: Cannot change connection state because "
2963                                                  "main window does not exist\n");
2964 }
2965
2966 /* Returns true (and sets error appropriately, if given) in case of error */
2967 gboolean networkmanager_is_online(GError **error)
2968 {
2969         DBusGConnection *connection;
2970         DBusGProxy *proxy;
2971         GError *tmp_error = NULL;
2972         gboolean retVal;
2973         guint32 state;
2974
2975         if (!prefs_common.use_networkmanager)
2976                 return TRUE;
2977
2978         tmp_error = NULL;
2979         proxy = NULL;
2980         connection = dbus_g_bus_get(DBUS_BUS_SYSTEM, &tmp_error);
2981
2982         if(!connection) {
2983                 /* If calling code doesn't do error checking, at least print some debug */
2984                 if((error == NULL) || (*error == NULL))
2985                         debug_print("Failed to open connection to system bus: %s\n",
2986                                                          tmp_error->message);
2987                 g_propagate_error(error, tmp_error);
2988                 return TRUE;
2989         }
2990
2991         proxy = dbus_g_proxy_new_for_name(connection,
2992                         "org.freedesktop.NetworkManager",
2993                         "/org/freedesktop/NetworkManager",
2994                         "org.freedesktop.NetworkManager");
2995
2996         retVal = dbus_g_proxy_call(proxy,"state",&tmp_error, G_TYPE_INVALID,
2997                         G_TYPE_UINT, &state, G_TYPE_INVALID);
2998
2999         if(proxy)
3000                 g_object_unref(proxy);
3001         if(connection)
3002                 dbus_g_connection_unref(connection);
3003
3004         if(!retVal) {
3005                 /* If calling code doesn't do error checking, at least print some debug */
3006                 if((error == NULL) || (*error == NULL))
3007                         debug_print("Failed to get state info from NetworkManager: %s\n",
3008                                                          tmp_error->message);
3009                 g_propagate_error(error, tmp_error);
3010                 return TRUE;
3011         }
3012 #if NM_CHECK_VERSION(0,8,992)
3013         return (state == NM_STATE_CONNECTED_LOCAL ||
3014                 state == NM_STATE_CONNECTED_SITE ||
3015                 state == NM_STATE_CONNECTED_GLOBAL ||
3016                 state == NM_STATE_UNKNOWN);
3017 #else
3018         return (state == NM_STATE_CONNECTED ||
3019                 state == NM_STATE_UNKNOWN);
3020 #endif
3021 }
3022 #endif