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