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