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