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