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