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