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