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