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