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