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