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