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