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