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