2 * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3 * Copyright (C) 1999-2016 Hiroyuki Yamamoto and the Claws Mail team
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.
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.
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/>.
21 #include "claws-features.h"
27 #include <glib/gi18n.h>
37 #include <sys/types.h>
44 #include <X11/SM/SMlib.h>
51 #include "file_checker.h"
53 #ifdef HAVE_STARTUP_NOTIFICATION
54 # define SN_API_NOT_YET_FROZEN
55 # include <libsn/sn-launchee.h>
56 # include <gdk/gdkx.h>
60 #include <dbus/dbus-glib.h>
62 #ifdef HAVE_NETWORKMANAGER_SUPPORT
63 #include <NetworkManager.h>
69 #include <librsvg/rsvg.h>
74 #include "mainwindow.h"
75 #include "folderview.h"
76 #include "image_viewer.h"
77 #include "summaryview.h"
78 #include "prefs_common.h"
79 #include "prefs_account.h"
80 #include "prefs_actions.h"
81 #include "prefs_ext_prog.h"
82 #include "prefs_fonts.h"
83 #include "prefs_image_viewer.h"
84 #include "prefs_message.h"
85 #include "prefs_migration.h"
86 #include "prefs_receive.h"
87 #include "prefs_msg_colors.h"
88 #include "prefs_quote.h"
89 #include "prefs_spelling.h"
90 #include "prefs_summaries.h"
91 #include "prefs_themes.h"
92 #include "prefs_other.h"
93 #include "prefs_proxy.h"
94 #include "prefs_logging.h"
95 #include "prefs_send.h"
96 #include "prefs_wrapping.h"
97 #include "prefs_compose_writing.h"
98 #include "prefs_display_header.h"
103 #include "send_message.h"
106 #include "manage_window.h"
107 #include "alertpanel.h"
108 #include "statusbar.h"
109 #ifndef USE_ALT_ADDRBOOK
110 #include "addressbook.h"
112 #include "addressbook-dbus.h"
116 #include "folder_item_prefs.h"
119 #include "gtkutils.h"
122 #include "prefs_toolbar.h"
125 #include "imap_gtk.h"
126 #include "news_gtk.h"
131 #include "quicksearch.h"
132 #include "advsearch.h"
134 #include "passwordstore.h"
135 #include "file-utils.h"
138 #include "imap-thread.h"
139 #include "nntp-thread.h"
141 #include "stock_pixmap.h"
152 #ifdef HAVE_NETWORKMANAGER_SUPPORT
153 /* Went offline due to NetworkManager */
154 static gboolean went_offline_nm;
158 #ifdef HAVE_DBUS_GLIB
159 static DBusGProxy *awn_proxy = NULL;
163 #if (defined HAVE_LIBSM || defined CRASH_DIALOG)
167 #ifdef HAVE_STARTUP_NOTIFICATION
168 static SnLauncheeContext *sn_context = NULL;
169 static SnDisplay *sn_display = NULL;
172 static gint lock_socket = -1;
173 static gint lock_socket_tag = 0;
175 static gchar *x_display = NULL;
179 ONLINE_MODE_DONT_CHANGE,
184 static struct RemoteCmd {
186 gboolean receive_all;
187 gboolean cancel_receiving;
188 gboolean cancel_sending;
190 const gchar *compose_mailto;
193 const gchar *search_folder;
194 const gchar *search_type;
195 const gchar *search_request;
196 gboolean search_recursive;
198 gboolean status_full;
200 gboolean reset_statistics;
201 GPtrArray *status_folders;
202 GPtrArray *status_full_folders;
209 const gchar *subscribe_uri;
212 const gchar *geometry;
215 SessionStats session_stats;
217 static void reset_statistics(void);
219 static void parse_cmd_opt(int argc, char *argv[]);
221 static gint prohibit_duplicate_launch (void);
222 static gchar * get_crashfile_name (void);
223 static gint lock_socket_remove (void);
224 static void lock_socket_input_cb (gpointer data,
226 GIOCondition condition);
228 static void open_compose_new (const gchar *address,
229 GList *attach_files);
231 static void send_queue (void);
232 static void initial_processing (FolderItem *item, gpointer data);
233 static void quit_signal_handler (int sig);
234 static void install_basic_sighandlers (void);
235 #if (defined linux && defined SIGIO)
236 static void install_memory_sighandler (void);
238 static void exit_claws (MainWindow *mainwin);
240 #ifdef HAVE_NETWORKMANAGER_SUPPORT
241 static void networkmanager_state_change_cb(DBusGProxy *proxy, gchar *dev,
245 #define MAKE_DIR_IF_NOT_EXIST(dir) \
247 if (!is_dir_exist(dir)) { \
248 if (is_file_exist(dir)) { \
250 (_("File '%s' already exists.\n" \
251 "Can't create folder."), \
255 if (make_dir(dir) < 0) \
260 #define STRNCMP(S1, S2) (strncmp((S1), (S2), sizeof((S2)) - 1))
262 #define CM_FD_WRITE(S) fd_write(sock, (S), strlen((S)))
263 #define CM_FD_WRITE_ALL(S) fd_write_all(sock, (S), strlen((S)))
265 static MainWindow *static_mainwindow;
267 static gboolean emergency_exit = FALSE;
269 #ifdef HAVE_STARTUP_NOTIFICATION
270 static void sn_error_trap_push(SnDisplay *display, Display *xdisplay)
272 gdk_error_trap_push();
275 static void sn_error_trap_pop(SnDisplay *display, Display *xdisplay)
277 gdk_error_trap_pop();
280 static void startup_notification_complete(gboolean with_window)
283 GtkWidget *hack = NULL;
286 /* this is needed to make the startup notification leave,
287 * if we have been launched from a menu.
288 * We have to display a window, so let it be very little */
289 hack = gtk_window_new(GTK_WINDOW_POPUP);
290 gtk_window_move(GTK_WINDOW(hack), 0, 0);
291 gtk_widget_set_size_request(hack, 1, 1);
292 gtk_widget_show(hack);
295 xdisplay = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
296 sn_display = sn_display_new(xdisplay,
299 sn_context = sn_launchee_context_new_from_environment(sn_display,
300 DefaultScreen(xdisplay));
302 if (sn_context != NULL) {
303 sn_launchee_context_complete(sn_context);
304 sn_launchee_context_unref(sn_context);
305 sn_display_unref(sn_display);
308 gtk_widget_destroy(hack);
311 #endif /* HAVE_STARTUP_NOTIFICATION */
313 static void claws_gtk_idle(void)
315 while(gtk_events_pending()) {
316 gtk_main_iteration();
321 static gboolean sc_starting = FALSE;
323 static gboolean defer_check_all(void *data)
325 gboolean autochk = GPOINTER_TO_INT(data);
328 inc_all_account_mail(static_mainwindow, autochk, FALSE,
329 prefs_common.newmail_notify_manu);
332 inc_all_account_mail(static_mainwindow, FALSE,
333 prefs_common.chk_on_startup,
334 prefs_common.newmail_notify_manu);
336 main_window_set_menu_sensitive(static_mainwindow);
337 toolbar_main_set_sensitive(static_mainwindow);
342 static gboolean defer_check(void *data)
344 inc_mail(static_mainwindow, prefs_common.newmail_notify_manu);
348 main_window_set_menu_sensitive(static_mainwindow);
349 toolbar_main_set_sensitive(static_mainwindow);
354 static gboolean defer_jump(void *data)
356 if (cmd.receive_all) {
357 defer_check_all(GINT_TO_POINTER(FALSE));
358 } else if (prefs_common.chk_on_startup) {
359 defer_check_all(GINT_TO_POINTER(TRUE));
360 } else if (cmd.receive) {
363 mainwindow_jump_to(data, FALSE);
366 main_window_set_menu_sensitive(static_mainwindow);
367 toolbar_main_set_sensitive(static_mainwindow);
372 static void chk_update_val(GtkWidget *widget, gpointer data)
374 gboolean *val = (gboolean *)data;
375 *val = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget));
378 static gboolean migrate_old_config(const gchar *old_cfg_dir, const gchar *new_cfg_dir, const gchar *oldversion)
380 gchar *message = g_strdup_printf(_("Configuration for %s found.\n"
381 "Do you want to migrate this configuration?"), oldversion);
383 if (!strcmp(oldversion, "Sylpheed")) {
384 gchar *message2 = g_strdup_printf(_("\n\nYour Sylpheed filtering rules can be converted by a\n"
385 "script available at %s."), TOOLS_URI);
386 gchar *tmp = g_strconcat(message, message2, NULL);
393 GtkWidget *window = NULL;
394 GtkWidget *keep_backup_chk;
395 gboolean backup = TRUE;
397 keep_backup_chk = gtk_check_button_new_with_label (_("Keep old configuration"));
398 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(keep_backup_chk), TRUE);
399 CLAWS_SET_TIP(keep_backup_chk,
400 _("Keeping a backup will allow you to go back to an "
401 "older version, but may take a while if you have "
402 "cached IMAP or News data, and will take some extra "
403 "room on your disk."));
405 g_signal_connect(G_OBJECT(keep_backup_chk), "toggled",
406 G_CALLBACK(chk_update_val), &backup);
408 if (alertpanel_full(_("Migration of configuration"), message,
409 GTK_STOCK_NO, GTK_STOCK_YES, NULL, ALERTFOCUS_SECOND, FALSE,
410 keep_backup_chk, ALERT_QUESTION) != G_ALERTALTERNATE) {
414 /* we can either do a fast migration requiring not any extra disk
415 * space, or a slow one that copies the old configuration and leaves
419 window = label_window_create(_("Copying configuration... This may take a while..."));
422 r = copy_dir(old_cfg_dir, new_cfg_dir);
423 label_window_destroy(window);
425 /* if copy failed, we'll remove the partially copied
428 alertpanel_error(_("Migration failed!"));
429 remove_dir_recursive(new_cfg_dir);
432 /* fast mode failed, but we don't want backup */
433 remove_dir_recursive(old_cfg_dir);
437 window = label_window_create(_("Migrating configuration..."));
440 r = g_rename(old_cfg_dir, new_cfg_dir);
441 label_window_destroy(window);
443 /* if g_rename failed, we'll try to copy */
445 FILE_OP_ERROR(new_cfg_dir, "g_rename");
446 debug_print("rename failed, trying copy\n");
453 static int migrate_common_rc(const gchar *old_rc, const gchar *new_rc)
456 gchar *plugin_path, *old_plugin_path, *new_plugin_path;
458 gboolean err = FALSE;
460 oldfp = claws_fopen(old_rc, "r");
463 newfp = claws_fopen(new_rc, "w");
469 plugin_path = g_strdup(get_plugin_dir());
470 new_plugin_path = g_strdup(plugin_path);
472 if (strstr(plugin_path, "/claws-mail/")) {
473 gchar *end = g_strdup(strstr(plugin_path, "/claws-mail/")+strlen("/claws-mail/"));
474 *(strstr(plugin_path, "/claws-mail/")) = '\0';
475 old_plugin_path = g_strconcat(plugin_path, "/sylpheed-claws/", end, NULL);
478 old_plugin_path = g_strdup(new_plugin_path);
480 debug_print("replacing %s with %s\n", old_plugin_path, new_plugin_path);
481 while (claws_fgets(buf, sizeof(buf), oldfp)) {
482 if (STRNCMP(buf, old_plugin_path)) {
483 err |= (claws_fputs(buf, newfp) == EOF);
485 debug_print("->replacing %s\n", buf);
486 debug_print(" with %s%s\n", new_plugin_path, buf+strlen(old_plugin_path));
487 err |= (claws_fputs(new_plugin_path, newfp) == EOF);
488 err |= (claws_fputs(buf+strlen(old_plugin_path), newfp) == EOF);
492 g_free(new_plugin_path);
493 g_free(old_plugin_path);
495 if (claws_safe_fclose(newfp) == EOF)
503 sc_client_set_value (MainWindow *mainwin,
514 prop.num_vals = num_vals;
518 if (mainwin->smc_conn)
519 SmcSetProperties ((SmcConn) mainwin->smc_conn, 1, proplist);
522 static void sc_die_callback (SmcConn smc_conn, SmPointer client_data)
527 static void sc_save_complete_callback(SmcConn smc_conn, SmPointer client_data)
531 static void sc_shutdown_cancelled_callback (SmcConn smc_conn, SmPointer client_data)
533 MainWindow *mainwin = (MainWindow *)client_data;
534 if (mainwin->smc_conn)
535 SmcSaveYourselfDone ((SmcConn) mainwin->smc_conn, TRUE);
538 static void sc_save_yourself_callback (SmcConn smc_conn,
539 SmPointer client_data,
545 MainWindow *mainwin = (MainWindow *)client_data;
546 if (mainwin->smc_conn)
547 SmcSaveYourselfDone ((SmcConn) mainwin->smc_conn, TRUE);
550 static IceIOErrorHandler sc_ice_installed_handler;
552 static void sc_ice_io_error_handler (IceConn connection)
554 if (sc_ice_installed_handler)
555 (*sc_ice_installed_handler) (connection);
557 static gboolean sc_process_ice_messages (GIOChannel *source,
558 GIOCondition condition,
561 IceConn connection = (IceConn) data;
562 IceProcessMessagesStatus status;
564 status = IceProcessMessages (connection, NULL, NULL);
566 if (status == IceProcessMessagesIOError) {
567 IcePointer context = IceGetConnectionContext (connection);
569 if (context && G_IS_OBJECT(context)) {
570 guint disconnect_id = g_signal_lookup ("disconnect", G_OBJECT_TYPE (context));
572 if (disconnect_id > 0)
573 g_signal_emit (context, disconnect_id, 0);
575 IceSetShutdownNegotiation (connection, False);
576 IceCloseConnection (connection);
583 static void new_ice_connection (IceConn connection, IcePointer client_data, Bool opening,
584 IcePointer *watch_data)
590 /* Make sure we don't pass on these file descriptors to any
592 fcntl(IceConnectionNumber(connection),F_SETFD,
593 fcntl(IceConnectionNumber(connection),F_GETFD,0) | FD_CLOEXEC);
595 channel = g_io_channel_unix_new (IceConnectionNumber (connection));
596 input_id = g_io_add_watch (channel,
597 G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_PRI,
598 sc_process_ice_messages,
600 g_io_channel_unref (channel);
602 *watch_data = (IcePointer) GUINT_TO_POINTER (input_id);
604 input_id = GPOINTER_TO_UINT ((gpointer) *watch_data);
605 g_source_remove (input_id);
609 static void sc_session_manager_connect(MainWindow *mainwin)
611 static gboolean connected = FALSE;
612 SmcCallbacks callbacks;
614 IceIOErrorHandler default_handler;
621 sc_ice_installed_handler = IceSetIOErrorHandler (NULL);
622 default_handler = IceSetIOErrorHandler (sc_ice_io_error_handler);
624 if (sc_ice_installed_handler == default_handler)
625 sc_ice_installed_handler = NULL;
627 IceAddConnectionWatch (new_ice_connection, NULL);
630 callbacks.save_yourself.callback = sc_save_yourself_callback;
631 callbacks.die.callback = sc_die_callback;
632 callbacks.save_complete.callback = sc_save_complete_callback;
633 callbacks.shutdown_cancelled.callback = sc_shutdown_cancelled_callback;
635 callbacks.save_yourself.client_data =
636 callbacks.die.client_data =
637 callbacks.save_complete.client_data =
638 callbacks.shutdown_cancelled.client_data = (SmPointer) mainwin;
639 if (g_getenv ("SESSION_MANAGER")) {
640 gchar error_string_ret[256] = "";
642 mainwin->smc_conn = (gpointer)
643 SmcOpenConnection (NULL, mainwin,
644 SmProtoMajor, SmProtoMinor,
645 SmcSaveYourselfProcMask | SmcDieProcMask |
646 SmcSaveCompleteProcMask |
647 SmcShutdownCancelledProcMask,
650 256, error_string_ret);
652 /* From https://www.x.org/releases/X11R7.7/doc/libSM/SMlib.txt:
653 * If SmcOpenConnection succeeds, it returns an opaque connection
654 * pointer of type SmcConn and the client_id_ret argument contains
655 * the client ID to be used for this session. The client_id_ret
656 * should be freed with a call to free when no longer needed. On
657 * failure, SmcOpenConnection returns NULL, and the reason for
658 * failure is returned in error_string_ret. */
659 if (mainwin->smc_conn != NULL)
662 if (error_string_ret[0] || mainwin->smc_conn == NULL)
663 g_warning("while connecting to session manager: %s",
667 vals = g_new (SmPropValue, 1);
668 vals[0].length = strlen(argv0);
669 vals[0].value = argv0;
670 sc_client_set_value (mainwin, SmCloneCommand, SmLISTofARRAY8, 1, vals);
671 sc_client_set_value (mainwin, SmRestartCommand, SmLISTofARRAY8, 1, vals);
672 sc_client_set_value (mainwin, SmProgram, SmARRAY8, 1, vals);
674 vals[0].length = strlen(g_get_user_name()?g_get_user_name():"");
675 vals[0].value = g_strdup(g_get_user_name()?g_get_user_name():"");
676 sc_client_set_value (mainwin, SmUserID, SmARRAY8, 1, vals);
678 g_free(vals[0].value);
685 static gboolean sc_exiting = FALSE;
686 static gboolean show_at_startup = TRUE;
687 static gboolean claws_crashed_bool = FALSE;
689 gboolean claws_crashed(void) {
690 return claws_crashed_bool;
693 void main_set_show_at_startup(gboolean show)
695 show_at_startup = show;
699 static HANDLE win32_debug_log = NULL;
700 static guint win32_log_handler_app_id;
701 static guint win32_log_handler_glib_id;
702 static guint win32_log_handler_gtk_id;
704 static void win32_log_WriteFile(const gchar *string)
709 ret = WriteFile(win32_debug_log, string, strlen(string), &bytes_written, NULL);
711 DWORD err = GetLastError();
714 tmp = g_strdup_printf("Error: WriteFile in failed with error 0x%lx. Buffer contents:\n%s", err, string);
715 OutputDebugString(tmp);
720 static void win32_print_stdout(const gchar *string)
722 if (win32_debug_log) {
723 win32_log_WriteFile(string);
727 static void win32_print_stderr(const gchar *string)
729 if (win32_debug_log) {
730 win32_log_WriteFile(string);
734 GLogWriterOutput win32_log_writer(GLogLevelFlags log_level, const GLogField *fields, gsize n_fields, gpointer user_data)
739 g_return_val_if_fail(win32_debug_log != NULL, G_LOG_WRITER_UNHANDLED);
740 g_return_val_if_fail(fields != NULL, G_LOG_WRITER_UNHANDLED);
741 g_return_val_if_fail(n_fields > 0, G_LOG_WRITER_UNHANDLED);
743 formatted = g_log_writer_format_fields(log_level, fields, n_fields, FALSE);
744 out = g_strdup_printf("%s\n", formatted);
746 win32_log_WriteFile(out);
751 return G_LOG_WRITER_HANDLED;
754 static void win32_log(const gchar *log_domain, GLogLevelFlags log_level, const gchar* message, gpointer user_data)
758 if (win32_debug_log) {
761 switch(log_level & G_LOG_LEVEL_MASK)
763 case G_LOG_LEVEL_ERROR:
766 case G_LOG_LEVEL_CRITICAL:
769 case G_LOG_LEVEL_WARNING:
772 case G_LOG_LEVEL_MESSAGE:
775 case G_LOG_LEVEL_INFO:
778 case G_LOG_LEVEL_DEBUG:
786 out = g_strdup_printf("%s: %s: %s", log_domain, type, message);
788 out = g_strdup_printf("%s: %s", type, message);
790 win32_log_WriteFile(out);
796 static void win32_open_log(void)
798 gchar *logfile = win32_debug_log_path();
799 gchar *oldlogfile = g_strconcat(logfile, ".bak", NULL);
801 if (is_file_exist(logfile)) {
802 if (rename_force(logfile, oldlogfile) < 0)
803 FILE_OP_ERROR(logfile, "rename");
806 win32_debug_log = CreateFile(logfile,
811 FILE_ATTRIBUTE_NORMAL,
814 if (win32_debug_log == INVALID_HANDLE_VALUE) {
815 win32_debug_log = NULL;
821 if (win32_debug_log) {
822 g_set_print_handler(win32_print_stdout);
823 g_set_printerr_handler(win32_print_stdout);
825 win32_log_handler_app_id = g_log_set_handler(NULL, G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
826 | G_LOG_FLAG_RECURSION, win32_log, NULL);
827 win32_log_handler_glib_id = g_log_set_handler("GLib", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
828 | G_LOG_FLAG_RECURSION, win32_log, NULL);
829 win32_log_handler_gtk_id = g_log_set_handler("Gtk", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
830 | G_LOG_FLAG_RECURSION, win32_log, NULL);
832 g_log_set_writer_func(&win32_log_writer, NULL, NULL);
836 static void win32_close_log(void)
838 if (win32_debug_log) {
839 g_log_remove_handler("", win32_log_handler_app_id);
840 g_log_remove_handler("GLib", win32_log_handler_glib_id);
841 g_log_remove_handler("Gtk", win32_log_handler_gtk_id);
842 CloseHandle(win32_debug_log);
843 win32_debug_log = NULL;
848 static void main_dump_features_list(gboolean show_debug_only)
849 /* display compiled-in features list */
851 if (show_debug_only && !debug_get_mode())
855 debug_print("runtime GTK+ %d.%d.%d / GLib %d.%d.%d\n",
856 gtk_major_version, gtk_minor_version, gtk_micro_version,
857 glib_major_version, glib_minor_version, glib_micro_version);
859 g_print("runtime GTK+ %d.%d.%d / GLib %d.%d.%d\n",
860 gtk_major_version, gtk_minor_version, gtk_micro_version,
861 glib_major_version, glib_minor_version, glib_micro_version);
863 debug_print("buildtime GTK+ %d.%d.%d / GLib %d.%d.%d\n",
864 GTK_MAJOR_VERSION, GTK_MINOR_VERSION, GTK_MICRO_VERSION,
865 GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION);
867 g_print("buildtime GTK+ %d.%d.%d / GLib %d.%d.%d\n",
868 GTK_MAJOR_VERSION, GTK_MINOR_VERSION, GTK_MICRO_VERSION,
869 GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION);
872 debug_print("Compiled-in features:\n");
874 g_print("Compiled-in features:\n");
877 debug_print(" compface\n");
879 g_print(" compface\n");
883 debug_print(" Enchant\n");
885 g_print(" Enchant\n");
889 debug_print(" GnuTLS\n");
891 g_print(" GnuTLS\n");
895 debug_print(" IPv6\n");
901 debug_print(" iconv\n");
907 debug_print(" JPilot\n");
909 g_print(" JPilot\n");
913 debug_print(" LDAP\n");
919 debug_print(" libetpan %d.%d\n", LIBETPAN_VERSION_MAJOR, LIBETPAN_VERSION_MINOR);
921 g_print(" libetpan %d.%d\n", LIBETPAN_VERSION_MAJOR, LIBETPAN_VERSION_MINOR);
925 debug_print(" libSM\n");
929 #if HAVE_NETWORKMANAGER_SUPPORT
931 debug_print(" NetworkManager\n");
933 g_print(" NetworkManager\n");
937 debug_print(" librSVG " LIBRSVG_VERSION "\n");
939 g_print(" librSVG " LIBRSVG_VERSION "\n");
943 #ifdef HAVE_DBUS_GLIB
944 static gulong dbus_item_hook_id = HOOK_NONE;
945 static gulong dbus_folder_hook_id = HOOK_NONE;
947 static void uninstall_dbus_status_handler(void)
950 g_object_unref(awn_proxy);
952 if (dbus_item_hook_id != HOOK_NONE)
953 hooks_unregister_hook(FOLDER_ITEM_UPDATE_HOOKLIST, dbus_item_hook_id);
954 if (dbus_folder_hook_id != HOOK_NONE)
955 hooks_unregister_hook(FOLDER_UPDATE_HOOKLIST, dbus_folder_hook_id);
958 static void dbus_update(FolderItem *removed_item)
960 guint new, unread, unreadmarked, marked, total;
961 guint replied, forwarded, locked, ignored, watched;
963 GError *error = NULL;
965 folder_count_total_msgs(&new, &unread, &unreadmarked, &marked, &total,
966 &replied, &forwarded, &locked, &ignored,
969 total -= removed_item->total_msgs;
970 new -= removed_item->new_msgs;
971 unread -= removed_item->unread_msgs;
975 buf = g_strdup_printf("%d", new);
976 dbus_g_proxy_call(awn_proxy, "SetInfoByName", &error,
977 G_TYPE_STRING, "claws-mail",
979 G_TYPE_INVALID, G_TYPE_INVALID);
983 dbus_g_proxy_call(awn_proxy, "UnsetInfoByName", &error, G_TYPE_STRING,
984 "claws-mail", G_TYPE_INVALID, G_TYPE_INVALID);
987 debug_print("%s\n", error->message);
992 static gboolean dbus_status_update_folder_hook(gpointer source, gpointer data)
994 FolderUpdateData *hookdata;
996 if (hookdata->update_flags & FOLDER_REMOVE_FOLDERITEM)
997 dbus_update(hookdata->item);
1004 static gboolean dbus_status_update_item_hook(gpointer source, gpointer data)
1011 static void install_dbus_status_handler(void)
1013 GError *tmp_error = NULL;
1014 DBusGConnection *connection = dbus_g_bus_get(DBUS_BUS_SESSION, &tmp_error);
1017 /* If calling code doesn't do error checking, at least print some debug */
1018 debug_print("Failed to open connection to session bus: %s\n",
1019 tmp_error->message);
1020 g_error_free(tmp_error);
1023 awn_proxy = dbus_g_proxy_new_for_name(connection,
1024 "com.google.code.Awn",
1025 "/com/google/code/Awn",
1026 "com.google.code.Awn");
1027 dbus_item_hook_id = hooks_register_hook (FOLDER_ITEM_UPDATE_HOOKLIST, dbus_status_update_item_hook, NULL);
1028 if (dbus_item_hook_id == HOOK_NONE) {
1029 g_warning("failed to register folder item update hook");
1030 uninstall_dbus_status_handler();
1034 dbus_folder_hook_id = hooks_register_hook (FOLDER_UPDATE_HOOKLIST, dbus_status_update_folder_hook, NULL);
1035 if (dbus_folder_hook_id == HOOK_NONE) {
1036 g_warning("failed to register folder update hook");
1037 uninstall_dbus_status_handler();
1043 static void reset_statistics(void)
1045 /* (re-)initialize session statistics */
1046 session_stats.received = 0;
1047 session_stats.sent = 0;
1048 session_stats.replied = 0;
1049 session_stats.forwarded = 0;
1050 session_stats.time_started = time(NULL);
1053 int main(int argc, char *argv[])
1055 #ifdef HAVE_DBUS_GLIB
1056 DBusGConnection *connection;
1059 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1060 DBusGProxy *nm_proxy;
1063 MainWindow *mainwin;
1064 FolderView *folderview;
1066 gboolean crash_file_present = FALSE;
1067 guint num_folder_class = 0;
1068 gboolean asked_for_migration = FALSE;
1069 gboolean start_done = TRUE;
1070 GSList *plug_list = NULL;
1071 gboolean never_ran = FALSE;
1072 gboolean mainwin_shown = FALSE;
1075 START_TIMING("startup");
1082 if (!claws_init(&argc, &argv)) {
1089 prog_version = PROG_VERSION;
1090 #if (defined HAVE_LIBSM || defined CRASH_DIALOG)
1091 argv0 = g_strdup(argv[0]);
1094 parse_cmd_opt(argc, argv);
1098 /* check and create unix domain socket for remote operation */
1099 lock_socket = prohibit_duplicate_launch();
1100 if (lock_socket < 0) {
1101 #ifdef HAVE_STARTUP_NOTIFICATION
1102 if(gtk_init_check(&argc, &argv))
1103 startup_notification_complete(TRUE);
1108 main_dump_features_list(TRUE);
1109 prefs_prepare_cache();
1114 gtk_init(&argc, &argv);
1115 crash_main(cmd.crash_params);
1121 crash_install_handlers();
1123 install_basic_sighandlers();
1124 #if (defined linux && defined SIGIO)
1125 install_memory_sighandler();
1128 if (cmd.status || cmd.status_full || cmd.search ||
1129 cmd.statistics || cmd.reset_statistics ||
1130 cmd.cancel_receiving || cmd.cancel_sending ||
1132 puts("0 Claws Mail not running.");
1133 lock_socket_remove();
1139 #if !GLIB_CHECK_VERSION(2,32,0)
1140 if (!g_thread_supported())
1141 g_thread_init(NULL);
1147 gtk_init(&argc, &argv);
1150 gtk_settings_set_string_property(gtk_settings_get_default(),
1154 gtk_settings_set_long_property(gtk_settings_get_default(),
1155 "gtk-auto-mnemonics",
1158 gtk_settings_set_long_property(gtk_settings_get_default(),
1159 "gtk-button-images",
1164 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1165 went_offline_nm = FALSE;
1168 #ifdef HAVE_DBUS_GLIB
1170 connection = dbus_g_bus_get(DBUS_BUS_SYSTEM, &error);
1173 debug_print("Failed to open connection to system bus: %s\n", error->message);
1174 g_error_free(error);
1177 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1178 nm_proxy = dbus_g_proxy_new_for_name(connection,
1179 "org.freedesktop.NetworkManager",
1180 "/org/freedesktop/NetworkManager",
1181 "org.freedesktop.NetworkManager");
1183 dbus_g_proxy_add_signal(nm_proxy, "StateChanged", G_TYPE_UINT, G_TYPE_INVALID);
1184 dbus_g_proxy_connect_signal(nm_proxy, "StateChanged",
1185 G_CALLBACK(networkmanager_state_change_cb),
1189 install_dbus_status_handler();
1193 gtk_widget_set_default_colormap(
1194 gdk_screen_get_system_colormap(
1195 gdk_screen_get_default()));
1197 gtkut_create_ui_manager();
1199 /* Create container for all the menus we will be adding */
1200 MENUITEM_ADDUI("/", "Menus", NULL, GTK_UI_MANAGER_MENUBAR);
1202 #if !GLIB_CHECK_VERSION(2,32,0)
1203 if (!g_thread_supported()) {
1204 g_error("g_thread is not supported by glib");
1209 CHDIR_EXEC_CODE_RETURN_VAL_IF_FAIL(get_home_dir(), 1, win32_close_log(););
1211 CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
1214 /* no config dir exists. See if we can migrate an old config. */
1215 if (!is_dir_exist(get_rc_dir())) {
1216 prefs_destroy_cache();
1219 /* if one of the old dirs exist, we'll ask if the user
1220 * want to migrates, and r will be TRUE if he said yes
1221 * and migration succeeded, and FALSE otherwise.
1223 if (is_dir_exist(OLD_GTK2_RC_DIR)) {
1224 r = migrate_old_config(OLD_GTK2_RC_DIR, get_rc_dir(),
1225 g_strconcat("Sylpheed-Claws 2.6.0 ", _("(or older)"), NULL));
1226 asked_for_migration = TRUE;
1227 } else if (is_dir_exist(OLDER_GTK2_RC_DIR)) {
1228 r = migrate_old_config(OLDER_GTK2_RC_DIR, get_rc_dir(),
1229 g_strconcat("Sylpheed-Claws 1.9.15 ",_("(or older)"), NULL));
1230 asked_for_migration = TRUE;
1231 } else if (is_dir_exist(OLD_GTK1_RC_DIR)) {
1232 r = migrate_old_config(OLD_GTK1_RC_DIR, get_rc_dir(),
1233 g_strconcat("Sylpheed-Claws 1.0.5 ",_("(or older)"), NULL));
1234 asked_for_migration = TRUE;
1235 } else if (is_dir_exist(SYLPHEED_RC_DIR)) {
1236 r = migrate_old_config(SYLPHEED_RC_DIR, get_rc_dir(), "Sylpheed");
1237 asked_for_migration = TRUE;
1240 /* If migration failed or the user didn't want to do it,
1241 * we create a new one (and we'll hit wizard later).
1243 if (r == FALSE && !is_dir_exist(get_rc_dir())) {
1245 if (copy_dir(SYSCONFDIR "/skel/.claws-mail", get_rc_dir()) < 0) {
1247 if (!is_dir_exist(get_rc_dir()) && make_dir(get_rc_dir()) < 0) {
1260 if (!is_file_exist(RC_DIR G_DIR_SEPARATOR_S COMMON_RC) &&
1261 is_file_exist(RC_DIR G_DIR_SEPARATOR_S OLD_COMMON_RC)) {
1262 /* post 2.6 name change */
1263 migrate_common_rc(RC_DIR G_DIR_SEPARATOR_S OLD_COMMON_RC,
1264 RC_DIR G_DIR_SEPARATOR_S COMMON_RC);
1268 plugin_load_all("Common");
1270 userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, "gtkrc-2.0", NULL);
1271 gtk_rc_parse(userrc);
1274 userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
1275 gtk_accel_map_load (userrc);
1279 CHDIR_EXEC_CODE_RETURN_VAL_IF_FAIL(get_rc_dir(), 1, win32_close_log(););
1281 CHDIR_RETURN_VAL_IF_FAIL(get_rc_dir(), 1);
1284 MAKE_DIR_IF_NOT_EXIST(get_mail_base_dir());
1285 MAKE_DIR_IF_NOT_EXIST(get_imap_cache_dir());
1286 MAKE_DIR_IF_NOT_EXIST(get_news_cache_dir());
1287 MAKE_DIR_IF_NOT_EXIST(get_mime_tmp_dir());
1288 MAKE_DIR_IF_NOT_EXIST(get_tmp_dir());
1289 MAKE_DIR_IF_NOT_EXIST(UIDL_DIR);
1291 crash_file_present = is_file_exist(get_crashfile_name());
1292 /* remove temporary files */
1293 remove_all_files(get_tmp_dir());
1294 remove_all_files(get_mime_tmp_dir());
1296 if (!cmd.crash && crash_file_present)
1297 claws_crashed_bool = TRUE;
1299 if (is_file_exist("claws.log")) {
1300 if (rename_force("claws.log", "claws.log.bak") < 0)
1301 FILE_OP_ERROR("claws.log", "rename");
1303 set_log_file(LOG_PROTOCOL, "claws.log");
1305 if (is_file_exist("filtering.log")) {
1306 if (rename_force("filtering.log", "filtering.log.bak") < 0)
1307 FILE_OP_ERROR("filtering.log", "rename");
1309 set_log_file(LOG_DEBUG_FILTERING, "filtering.log");
1312 CHDIR_EXEC_CODE_RETURN_VAL_IF_FAIL(get_home_dir(), 1, win32_close_log(););
1314 CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
1317 folder_system_init();
1318 prefs_common_read_config();
1320 if (prefs_update_config_version_common() < 0) {
1321 debug_print("Main configuration file version upgrade failed, exiting\n");
1328 prefs_themes_init();
1330 prefs_ext_prog_init();
1331 prefs_wrapping_init();
1332 prefs_compose_writing_init();
1333 prefs_msg_colors_init();
1334 image_viewer_init();
1335 prefs_image_viewer_init();
1337 prefs_summaries_init();
1338 prefs_message_init();
1341 prefs_logging_init();
1342 prefs_receive_init();
1347 gtkaspell_checkers_init();
1348 prefs_spelling_init();
1351 codeconv_set_allow_jisx0201_kana(prefs_common.allow_jisx0201_kana);
1352 codeconv_set_broken_are_utf8(prefs_common.broken_are_utf8);
1355 if(prefs_common.gtk_theme && strcmp(prefs_common.gtk_theme, DEFAULT_W32_GTK_THEME))
1356 gtk_settings_set_string_property(gtk_settings_get_default(),
1358 prefs_common.gtk_theme,
1363 sock_set_io_timeout(prefs_common.io_timeout_secs);
1364 prefs_actions_read_config();
1365 prefs_display_header_read_config();
1366 /* prefs_filtering_read_config(); */
1367 #ifndef USE_ALT_ADDRBOOK
1368 addressbook_read_file();
1370 g_clear_error(&error);
1371 if (! addressbook_start_service(&error)) {
1372 g_warning("%s", error->message);
1373 g_clear_error(&error);
1376 addressbook_install_hooks(&error);
1379 gtkut_widget_init();
1380 stock_pixbuf_gdk(STOCK_PIXMAP_CLAWS_MAIL_ICON, &icon);
1381 gtk_window_set_default_icon(icon);
1383 folderview_initialize();
1389 mainwin = main_window_create();
1391 if (!check_file_integrity())
1394 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1395 networkmanager_state_change_cb(nm_proxy,NULL,mainwin);
1398 manage_window_focus_in(mainwin->window, NULL, NULL);
1399 folderview = mainwin->folderview;
1401 folderview_freeze(mainwin->folderview);
1402 folder_item_update_freeze();
1404 if ((ret = passwd_store_read_config()) < 0) {
1405 debug_print("Password store configuration file version upgrade failed (%d), exiting\n", ret);
1412 prefs_account_init();
1413 account_read_config_all();
1415 if (prefs_update_config_version_accounts() < 0) {
1416 debug_print("Accounts configuration file version upgrade failed, exiting\n");
1423 #ifdef HAVE_LIBETPAN
1424 imap_main_init(prefs_common.skip_ssl_cert_check);
1425 imap_main_set_timeout(prefs_common.io_timeout_secs);
1426 nntp_main_init(prefs_common.skip_ssl_cert_check);
1428 /* If we can't read a folder list or don't have accounts,
1429 * it means the configuration's not done. Either this is
1430 * a brand new install, a failed/refused migration,
1431 * or a failed config_version upgrade.
1433 if ((ret = folder_read_list()) < 0) {
1434 debug_print("Folderlist read failed (%d)\n", ret);
1435 prefs_destroy_cache();
1438 /* config_version update failed in folder_read_list(). We
1439 * do not want to run the wizard, just exit. */
1440 debug_print("Folderlist version upgrade failed, exiting\n");
1447 /* if run_wizard returns FALSE it's because it's
1448 * been cancelled. We can't do much but exit.
1449 * however, if the user was asked for a migration,
1450 * we remove the newly created directory so that
1451 * he's asked again for migration on next launch.*/
1452 if (!run_wizard(mainwin, TRUE)) {
1453 if (asked_for_migration)
1454 remove_dir_recursive(RC_DIR);
1460 main_window_reflect_prefs_all_now();
1461 folder_write_list();
1465 if (!account_get_list()) {
1466 prefs_destroy_cache();
1467 if (!run_wizard(mainwin, FALSE)) {
1468 if (asked_for_migration)
1469 remove_dir_recursive(RC_DIR);
1475 if(!account_get_list()) {
1476 exit_claws(mainwin);
1483 toolbar_main_set_sensitive(mainwin);
1484 main_window_set_menu_sensitive(mainwin);
1486 /* if crashed, show window early so that the user
1487 * sees what's happening */
1488 if (claws_crashed()) {
1489 main_window_popup(mainwin);
1490 mainwin_shown = TRUE;
1493 account_set_missing_folder();
1494 folder_set_missing_folders();
1495 folderview_set(folderview);
1497 prefs_matcher_read_config();
1498 quicksearch_set_search_strings(mainwin->summaryview->quicksearch);
1500 /* make one all-folder processing before using claws */
1501 main_window_cursor_wait(mainwin);
1502 folder_func_to_all_folders(initial_processing, (gpointer *)mainwin);
1504 /* if claws crashed, rebuild caches */
1505 if (claws_crashed()) {
1507 debug_print("Claws Mail crashed, checking for new messages in local folders\n");
1508 folder_item_update_thaw();
1509 folderview_check_new(NULL);
1510 folder_clean_cache_memory_force();
1511 folder_item_update_freeze();
1513 /* make the crash-indicator file */
1514 if (str_write_to_file("foo", get_crashfile_name(), FALSE) < 0) {
1515 g_warning("can't create the crash-indicator file");
1518 inc_autocheck_timer_init(mainwin);
1520 /* ignore SIGPIPE signal for preventing sudden death of program */
1522 signal(SIGPIPE, SIG_IGN);
1524 if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
1525 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
1527 if (cmd.online_mode == ONLINE_MODE_ONLINE) {
1528 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
1531 if (cmd.status_folders) {
1532 g_ptr_array_free(cmd.status_folders, TRUE);
1533 cmd.status_folders = NULL;
1535 if (cmd.status_full_folders) {
1536 g_ptr_array_free(cmd.status_full_folders, TRUE);
1537 cmd.status_full_folders = NULL;
1540 claws_register_idle_function(claws_gtk_idle);
1543 prefs_toolbar_init();
1545 num_folder_class = g_list_length(folder_get_list());
1547 plugin_load_all("GTK2");
1549 if (g_list_length(folder_get_list()) != num_folder_class) {
1550 debug_print("new folders loaded, reloading processing rules\n");
1551 prefs_matcher_read_config();
1554 if ((plug_list = plugin_get_unloaded_list()) != NULL) {
1557 gint num_plugins = 0;
1558 for (cur = plug_list; cur; cur = cur->next) {
1559 Plugin *plugin = (Plugin *)cur->data;
1560 gchar *tmp = g_strdup_printf("%s\n%s",
1562 plugin_get_name(plugin));
1567 main_window_cursor_normal(mainwin);
1568 main_window_popup(mainwin);
1569 mainwin_shown = TRUE;
1570 alertpanel_warning(ngettext(
1571 "The following plugin failed to load. "
1572 "Check the Plugins configuration "
1573 "for more information:\n%s",
1574 "The following plugins failed to load. "
1575 "Check the Plugins configuration "
1576 "for more information:\n%s",
1579 main_window_cursor_wait(mainwin);
1581 g_slist_free(plug_list);
1585 prefs_common_write_config();
1586 plugin_load_standard_plugins ();
1589 /* if not crashed, show window now */
1590 if (!mainwin_shown) {
1591 /* apart if something told not to show */
1592 if (show_at_startup)
1593 main_window_popup(mainwin);
1596 if (cmd.geometry != NULL) {
1597 if (!gtk_window_parse_geometry(GTK_WINDOW(mainwin->window), cmd.geometry))
1598 g_warning("failed to parse geometry '%s'", cmd.geometry);
1602 if (sscanf(cmd.geometry, "%ux%u+", &width, &height) == 2)
1603 gtk_window_resize(GTK_WINDOW(mainwin->window), width, height);
1605 g_warning("failed to parse geometry's width/height");
1609 if (!folder_have_mailbox()) {
1610 prefs_destroy_cache();
1611 main_window_cursor_normal(mainwin);
1612 if (folder_get_list() != NULL) {
1613 alertpanel_error(_("Claws Mail has detected a configured "
1614 "mailbox, but it is incomplete. It is "
1615 "possibly due to a failing IMAP account. Use "
1616 "\"Rebuild folder tree\" on the mailbox parent "
1617 "folder's context menu to try to fix it."));
1619 alertpanel_error(_("Claws Mail has detected a configured "
1620 "mailbox, but could not load it. It is "
1621 "probably provided by an out-of-date "
1622 "external plugin. Please reinstall the "
1623 "plugin and try again."));
1624 exit_claws(mainwin);
1629 static_mainwindow = mainwin;
1631 #ifdef HAVE_STARTUP_NOTIFICATION
1632 startup_notification_complete(FALSE);
1635 sc_session_manager_connect(mainwin);
1638 folder_item_update_thaw();
1639 folderview_thaw(mainwin->folderview);
1640 main_window_cursor_normal(mainwin);
1642 if (!cmd.target && prefs_common.goto_last_folder_on_startup &&
1643 folder_find_item_from_identifier(prefs_common.last_opened_folder) != NULL &&
1645 cmd.target = prefs_common.last_opened_folder;
1648 if (cmd.receive_all && !cmd.target) {
1650 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(FALSE));
1651 } else if (prefs_common.chk_on_startup && !cmd.target) {
1653 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(TRUE));
1654 } else if (cmd.receive && !cmd.target) {
1656 g_timeout_add(1000, defer_check, NULL);
1658 folderview_grab_focus(folderview);
1661 open_compose_new(cmd.compose_mailto, cmd.attach_files);
1663 if (cmd.attach_files) {
1664 list_free_strings_full(cmd.attach_files);
1665 cmd.attach_files = NULL;
1667 if (cmd.subscribe) {
1668 folder_subscribe(cmd.subscribe_uri);
1677 g_timeout_add(500, defer_jump, (gpointer)cmd.target);
1680 prefs_destroy_cache();
1682 compose_reopen_exit_drafts();
1685 sc_starting = FALSE;
1686 main_window_set_menu_sensitive(mainwin);
1687 toolbar_main_set_sensitive(mainwin);
1690 /* register the callback of unix domain socket input */
1691 lock_socket_tag = claws_input_add(lock_socket,
1692 G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_PRI,
1693 lock_socket_input_cb,
1700 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1702 g_object_unref(nm_proxy);
1704 #ifdef HAVE_DBUS_GLIB
1705 uninstall_dbus_status_handler();
1707 dbus_g_connection_unref(connection);
1710 exit_claws(mainwin);
1715 static void save_all_caches(FolderItem *item, gpointer data)
1722 folder_item_close(item);
1725 folder_item_free_cache(item, TRUE);
1728 static void exit_claws(MainWindow *mainwin)
1731 gboolean have_connectivity;
1736 debug_print("shutting down\n");
1737 inc_autocheck_timer_remove();
1739 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1740 if (prefs_common.work_offline && went_offline_nm)
1741 prefs_common.work_offline = FALSE;
1744 /* save prefs for opened folder */
1745 if((item = folderview_get_opened_item(mainwin->folderview)) != NULL) {
1746 summary_save_prefs_to_folderitem(
1747 mainwin->summaryview, item);
1748 if (prefs_common.last_opened_folder != NULL)
1749 g_free(prefs_common.last_opened_folder);
1750 prefs_common.last_opened_folder =
1751 !prefs_common.goto_last_folder_on_startup ? NULL :
1752 folder_item_get_identifier(item);
1755 /* save all state before exiting */
1756 folder_func_to_all_folders(save_all_caches, NULL);
1757 folder_write_list();
1759 main_window_get_size(mainwin);
1760 main_window_get_position(mainwin);
1762 prefs_common_write_config();
1763 account_write_config_all();
1764 passwd_store_write_config();
1765 #ifndef USE_ALT_ADDRBOOK
1766 addressbook_export_to_file();
1768 filename = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
1769 gtk_accel_map_save(filename);
1772 /* delete temporary files */
1773 remove_all_files(get_tmp_dir());
1774 remove_all_files(get_mime_tmp_dir());
1776 close_log_file(LOG_PROTOCOL);
1777 close_log_file(LOG_DEBUG_FILTERING);
1779 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1780 have_connectivity = networkmanager_is_online(NULL);
1782 have_connectivity = TRUE;
1784 #ifdef HAVE_LIBETPAN
1785 imap_main_done(have_connectivity);
1786 nntp_main_done(have_connectivity);
1788 /* delete crashfile */
1790 claws_unlink(get_crashfile_name());
1792 lock_socket_remove();
1795 if (mainwin->smc_conn)
1796 SmcCloseConnection ((SmcConn)mainwin->smc_conn, 0, NULL);
1797 mainwin->smc_conn = NULL;
1800 main_window_destroy_all();
1802 plugin_unload_all("GTK2");
1805 prefs_toolbar_done();
1808 #ifndef USE_ALT_ADDRBOOK
1809 addressbook_destroy();
1811 prefs_themes_done();
1813 prefs_ext_prog_done();
1814 prefs_wrapping_done();
1815 prefs_compose_writing_done();
1816 prefs_msg_colors_done();
1817 prefs_image_viewer_done();
1818 image_viewer_done();
1820 prefs_summaries_done();
1821 prefs_message_done();
1824 prefs_receive_done();
1825 prefs_logging_done();
1829 prefs_spelling_done();
1830 gtkaspell_checkers_quit();
1832 plugin_unload_all("Common");
1839 #define G_PRINT_EXIT(msg) \
1845 static void parse_cmd_compose_from_file(const gchar *fn, GString *body)
1847 GString *headers = g_string_new(NULL);
1855 if (fn == NULL || *fn == '\0')
1856 G_PRINT_EXIT(_("Missing filename\n"));
1857 isstdin = (*fn == '-' && *(fn + 1) == '\0');
1861 fp = claws_fopen(fn, "r");
1863 G_PRINT_EXIT(_("Cannot open filename for reading\n"));
1866 while (claws_fgets(fb, sizeof(fb), fp)) {
1872 while (*h && *h != ':') { ++h; } /* search colon */
1874 G_PRINT_EXIT(_("Malformed header\n"));
1876 while (*v && *v == ' ') { ++v; } /* trim value start */
1878 tmp = g_ascii_strdown(fb, -1); /* get header name */
1879 if (!strcmp(tmp, "to")) {
1881 G_PRINT_EXIT(_("Duplicated 'To:' header\n"));
1884 g_string_append_c(headers, '&');
1885 g_string_append(headers, tmp);
1886 g_string_append_c(headers, '=');
1887 g_string_append_uri_escaped(headers, v, NULL, TRUE);
1892 G_PRINT_EXIT(_("Missing required 'To:' header\n"));
1893 g_string_append(body, to);
1895 g_string_append(body, "?body=");
1896 while (claws_fgets(fb, sizeof(fb), fp)) {
1897 g_string_append_uri_escaped(body, fb, NULL, TRUE);
1901 /* append the remaining headers */
1902 g_string_append(body, headers->str);
1903 g_string_free(headers, TRUE);
1908 static void parse_cmd_opt_error(char *errstr, char* optstr)
1912 cm_return_if_fail(errstr != NULL);
1913 cm_return_if_fail(optstr != NULL);
1915 g_snprintf(tmp, sizeof(tmp), errstr, optstr);
1916 g_print(_("%s. Try -h or --help for usage.\n"), tmp);
1920 static GString mailto; /* used to feed cmd.compose_mailto when --compose-from-file is used */
1922 static void parse_cmd_opt(int argc, char *argv[])
1927 for (i = 1; i < argc; i++) {
1928 if (!strcmp(argv[i], "--receive-all")) {
1929 cmd.receive_all = TRUE;
1930 } else if (!strcmp(argv[i], "--receive")) {
1932 } else if (!strcmp(argv[i], "--cancel-receiving")) {
1933 cmd.cancel_receiving = TRUE;
1934 } else if (!strcmp(argv[i], "--cancel-sending")) {
1935 cmd.cancel_sending = TRUE;
1936 } else if (!strcmp(argv[i], "--compose-from-file")) {
1938 const gchar *p = argv[i+1];
1940 parse_cmd_compose_from_file(p, &mailto);
1942 cmd.compose_mailto = mailto.str;
1945 parse_cmd_opt_error(_("Missing file argument for option %s"), argv[i]);
1947 } else if (!strcmp(argv[i], "--compose")) {
1948 const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
1951 cmd.compose_mailto = NULL;
1952 if (p && *p != '\0' && *p != '-') {
1953 if (!STRNCMP(p, "mailto:")) {
1954 cmd.compose_mailto = p + 7;
1956 cmd.compose_mailto = p;
1960 } else if (!strcmp(argv[i], "--subscribe")) {
1962 const gchar *p = argv[i+1];
1963 if (p && *p != '\0' && *p != '-') {
1964 cmd.subscribe = TRUE;
1965 cmd.subscribe_uri = p;
1967 parse_cmd_opt_error(_("Missing or empty uri argument for option %s"), argv[i]);
1970 parse_cmd_opt_error(_("Missing uri argument for option %s"), argv[i]);
1972 } else if (!strcmp(argv[i], "--attach") ||
1973 !strcmp(argv[i], "--insert")) {
1975 const gchar *p = argv[i+1];
1978 gboolean insert = !strcmp(argv[i], "--insert");
1980 while (p && *p != '\0' && *p != '-') {
1981 if ((file = g_filename_from_uri(p, NULL, NULL)) != NULL) {
1982 if (!is_file_exist(file)) {
1987 if (file == NULL && *p != G_DIR_SEPARATOR) {
1988 file = g_strconcat(claws_get_startup_dir(),
1991 } else if (file == NULL) {
1995 ainfo = g_new0(AttachInfo, 1);
1997 ainfo->insert = insert;
1998 cmd.attach_files = g_list_append(cmd.attach_files, ainfo);
2000 p = (ii+1 < argc)?argv[ii+1]:NULL;
2003 parse_cmd_opt_error(_("Missing at least one non-empty file argument for option %s"), argv[i]);
2008 parse_cmd_opt_error(_("Missing file argument for option %s"), argv[i]);
2010 } else if (!strcmp(argv[i], "--send")) {
2012 } else if (!strcmp(argv[i], "--version-full") ||
2013 !strcmp(argv[i], "-V")) {
2014 g_print("Claws Mail version " VERSION_GIT_FULL "\n");
2015 main_dump_features_list(FALSE);
2017 } else if (!strcmp(argv[i], "--version") ||
2018 !strcmp(argv[i], "-v")) {
2019 g_print("Claws Mail version " VERSION "\n");
2021 } else if (!strcmp(argv[i], "--status-full")) {
2022 const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
2024 cmd.status_full = TRUE;
2025 while (p && *p != '\0' && *p != '-') {
2026 if (!cmd.status_full_folders) {
2027 cmd.status_full_folders =
2030 g_ptr_array_add(cmd.status_full_folders,
2033 p = (i+1 < argc)?argv[i+1]:NULL;
2035 } else if (!strcmp(argv[i], "--status")) {
2036 const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
2039 while (p && *p != '\0' && *p != '-') {
2040 if (!cmd.status_folders)
2041 cmd.status_folders = g_ptr_array_new();
2042 g_ptr_array_add(cmd.status_folders,
2045 p = (i+1 < argc)?argv[i+1]:NULL;
2047 } else if (!strcmp(argv[i], "--search")) {
2048 if (i+3 < argc) { /* 3 first arguments are mandatory */
2050 /* only set search parameters if they are valid */
2052 cmd.search_folder = (p && *p != '\0' && *p != '-')?p:NULL;
2054 cmd.search_type = (p && *p != '\0' && *p != '-')?p:NULL;
2056 cmd.search_request = (p && *p != '\0' && *p != '-')?p:NULL;
2057 p = (i+4 < argc)?argv[i+4]:NULL;
2058 const char* rec = (p && *p != '\0' && *p != '-')?p:NULL;
2059 cmd.search_recursive = TRUE;
2062 if (tolower(*rec)=='n' || tolower(*rec)=='f' || *rec=='0')
2063 cmd.search_recursive = FALSE;
2065 if (cmd.search_folder && cmd.search_type && cmd.search_request) {
2072 parse_cmd_opt_error(_("Missing folder, type and request arguments for option %s"), argv[i]);
2075 parse_cmd_opt_error(_("Missing type and request arguments for option %s"), argv[i]);
2078 parse_cmd_opt_error(_("Missing request argument for option %s"), argv[i]);
2081 } else if (!strcmp(argv[i], "--online")) {
2082 cmd.online_mode = ONLINE_MODE_ONLINE;
2083 } else if (!strcmp(argv[i], "--offline")) {
2084 cmd.online_mode = ONLINE_MODE_OFFLINE;
2085 } else if (!strcmp(argv[i], "--toggle-debug")) {
2087 } else if (!strcmp(argv[i], "--statistics")) {
2088 cmd.statistics = TRUE;
2089 } else if (!strcmp(argv[i], "--reset-statistics")) {
2090 cmd.reset_statistics = TRUE;
2091 } else if (!strcmp(argv[i], "--help") ||
2092 !strcmp(argv[i], "-h")) {
2093 gchar *base = g_path_get_basename(argv[0]);
2094 g_print(_("Usage: %s [OPTION]...\n"), base);
2096 g_print("%s\n", _(" --compose [address] open composition window"));
2097 g_print("%s\n", _(" --compose-from-file file\n"
2098 " open composition window with data from given file;\n"
2099 " use - as file name for reading from standard input;\n"
2100 " content format: headers first (To: required) until an\n"
2101 " empty line, then mail body until end of file."));
2102 g_print("%s\n", _(" --subscribe uri subscribe to the given URI if possible"));
2103 g_print("%s\n", _(" --attach file1 [file2]...\n"
2104 " open composition window with specified files\n"
2106 g_print("%s\n", _(" --insert file1 [file2]...\n"
2107 " open composition window with specified files\n"
2109 g_print("%s\n", _(" --receive receive new messages"));
2110 g_print("%s\n", _(" --receive-all receive new messages of all accounts"));
2111 g_print("%s\n", _(" --cancel-receiving cancel receiving of messages"));
2112 g_print("%s\n", _(" --cancel-sending cancel sending of messages"));
2113 g_print("%s\n", _(" --search folder type request [recursive]\n"
2115 " folder ex.: \"#mh/Mailbox/inbox\" or \"Mail\"\n"
2116 " type: s[ubject],f[rom],t[o],e[xtended],m[ixed] or g: tag\n"
2117 " request: search string\n"
2118 " recursive: false if arg. starts with 0, n, N, f or F"));
2120 g_print("%s\n", _(" --send send all queued messages"));
2121 g_print("%s\n", _(" --status [folder]... show the total number of messages"));
2122 g_print("%s\n", _(" --status-full [folder]...\n"
2123 " show the status of each folder"));
2124 g_print("%s\n", _(" --statistics show session statistics"));
2125 g_print("%s\n", _(" --reset-statistics reset session statistics"));
2126 g_print("%s\n", _(" --select folder[/msg] jump to the specified folder/message\n"
2127 " folder is a folder id like 'folder/sub_folder', a file:// uri or an absolute path"));
2128 g_print("%s\n", _(" --online switch to online mode"));
2129 g_print("%s\n", _(" --offline switch to offline mode"));
2130 g_print("%s\n", _(" --exit --quit -q exit Claws Mail"));
2131 g_print("%s\n", _(" --debug -d debug mode"));
2132 g_print("%s\n", _(" --toggle-debug toggle debug mode"));
2133 g_print("%s\n", _(" --help -h display this help"));
2134 g_print("%s\n", _(" --version -v output version information"));
2135 g_print("%s\n", _(" --version-full -V output version and built-in features information"));
2136 g_print("%s\n", _(" --config-dir output configuration directory"));
2137 g_print("%s\n", _(" --alternate-config-dir directory\n"
2138 " use specified configuration directory"));
2139 g_print("%s\n", _(" --geometry -geometry [WxH][+X+Y]\n"
2140 " set geometry for main window"));
2144 } else if (!strcmp(argv[i], "--crash")) {
2146 cmd.crash_params = g_strdup((i+1 < argc)?argv[i+1]:NULL);
2148 } else if (!strcmp(argv[i], "--config-dir")) {
2149 g_print(RC_DIR "\n");
2151 } else if (!strcmp(argv[i], "--alternate-config-dir")) {
2153 set_rc_dir(argv[i+1]);
2156 parse_cmd_opt_error(_("Missing directory argument for option %s"), argv[i]);
2158 } else if (!strcmp(argv[i], "--geometry") ||
2159 !strcmp(argv[i], "-geometry")) {
2161 cmd.geometry = argv[i+1];
2164 parse_cmd_opt_error(_("Missing geometry argument for option %s"), argv[i]);
2166 } else if (!strcmp(argv[i], "--exit") ||
2167 !strcmp(argv[i], "--quit") ||
2168 !strcmp(argv[i], "-q")) {
2170 } else if (!strcmp(argv[i], "--select")) {
2172 cmd.target = argv[i+1];
2175 parse_cmd_opt_error(_("Missing folder argument for option %s"), argv[i]);
2177 } else if (i == 1 && argc == 2) {
2178 /* only one parameter. Do something intelligent about it */
2179 if ((strstr(argv[i], "@") || !STRNCMP(argv[i], "mailto:")) && !strstr(argv[i], "://")) {
2180 const gchar *p = argv[i];
2183 cmd.compose_mailto = NULL;
2184 if (p && *p != '\0' && *p != '-') {
2185 if (!STRNCMP(p, "mailto:")) {
2186 cmd.compose_mailto = p + 7;
2188 cmd.compose_mailto = p;
2191 } else if (!STRNCMP(argv[i], "file://")) {
2192 cmd.target = argv[i];
2193 } else if (!STRNCMP(argv[i], "?attach=file://")) {
2194 /* Thunar support as per 3.3.0cvs19 */
2196 cmd.compose_mailto = argv[i];
2197 } else if (strstr(argv[i], "://")) {
2198 const gchar *p = argv[i];
2199 if (p && *p != '\0' && *p != '-') {
2200 cmd.subscribe = TRUE;
2201 cmd.subscribe_uri = p;
2203 } else if (!strcmp(argv[i], "--sync")) {
2205 } else if (is_dir_exist(argv[i]) || is_file_exist(argv[i])) {
2206 cmd.target = argv[i];
2208 parse_cmd_opt_error(_("Unknown option %s"), argv[i]);
2211 parse_cmd_opt_error(_("Unknown option %s"), argv[i]);
2215 if (cmd.attach_files && cmd.compose == FALSE) {
2217 cmd.compose_mailto = NULL;
2221 static void initial_processing(FolderItem *item, gpointer data)
2223 MainWindow *mainwin = (MainWindow *)data;
2226 cm_return_if_fail(item);
2227 buf = g_strdup_printf(_("Processing (%s)..."),
2230 : _("top level folder"));
2233 if (folder_item_parent(item) != NULL && item->prefs->enable_processing) {
2234 item->processing_pending = TRUE;
2235 folder_item_apply_processing(item);
2236 item->processing_pending = FALSE;
2239 STATUSBAR_POP(mainwin);
2242 static gboolean draft_all_messages(void)
2244 const GList *compose_list = NULL;
2246 compose_clear_exit_drafts();
2247 compose_list = compose_get_compose_list();
2248 while (compose_list != NULL) {
2249 Compose *c = (Compose*)compose_list->data;
2250 if (!compose_draft(c, COMPOSE_DRAFT_FOR_EXIT))
2252 compose_list = compose_get_compose_list();
2256 gboolean clean_quit(gpointer data)
2258 static gboolean firstrun = TRUE;
2265 /*!< Good idea to have the main window stored in a
2266 * static variable so we can check that variable
2267 * to see if we're really allowed to do things
2268 * that actually the spawner is supposed to
2269 * do (like: sending mail, composing messages).
2270 * Because, really, if we're the spawnee, and
2271 * we touch GTK stuff, we're hosed. See the
2274 /* FIXME: Use something else to signal that we're
2275 * in the original spawner, and not in a spawned
2277 if (!static_mainwindow) {
2281 draft_all_messages();
2282 emergency_exit = TRUE;
2283 exit_claws(static_mainwindow);
2289 void app_will_exit(GtkWidget *widget, gpointer data)
2291 MainWindow *mainwin = data;
2293 if (gtk_main_level() == 0) {
2294 debug_print("not even started\n");
2297 if (sc_exiting == TRUE) {
2298 debug_print("exit pending\n");
2302 debug_print("exiting\n");
2303 if (compose_get_compose_list()) {
2304 if (!draft_all_messages()) {
2305 main_window_popup(mainwin);
2311 if (prefs_common.warn_queued_on_exit && procmsg_have_queued_mails_fast()) {
2312 if (alertpanel(_("Queued messages"),
2313 _("Some unsent messages are queued. Exit now?"),
2314 GTK_STOCK_CANCEL, GTK_STOCK_OK, NULL, ALERTFOCUS_FIRST)
2315 != G_ALERTALTERNATE) {
2316 main_window_popup(mainwin);
2320 manage_window_focus_in(mainwin->window, NULL, NULL);
2324 #ifdef HAVE_VALGRIND
2325 if (RUNNING_ON_VALGRIND) {
2326 summary_clear_list(mainwin->summaryview);
2329 if (folderview_get_selected_item(mainwin->folderview))
2330 folder_item_close(folderview_get_selected_item(mainwin->folderview));
2334 gboolean claws_is_exiting(void)
2339 gboolean claws_is_starting(void)
2346 * CLAWS: want this public so crash dialog can delete the
2349 gchar *claws_get_socket_name(void)
2351 static gchar *filename = NULL;
2352 gchar *socket_dir = NULL;
2355 if (filename == NULL) {
2359 socket_dir = g_strdup_printf("%s%cclaws-mail",
2360 g_get_user_runtime_dir(), G_DIR_SEPARATOR);
2361 stat_ok = g_stat(socket_dir, &st);
2362 if (stat_ok < 0 && errno != ENOENT) {
2363 g_print("Error stat'ing socket_dir %s: %s\n",
2364 socket_dir, g_strerror(errno));
2365 } else if (stat_ok == 0 && S_ISSOCK(st.st_mode)) {
2366 /* old versions used a sock in $TMPDIR/claws-mail-$UID */
2367 debug_print("Using legacy socket %s\n", socket_dir);
2368 filename = g_strdup(socket_dir);
2372 if (!is_dir_exist(socket_dir) && make_dir(socket_dir) < 0) {
2373 g_print("Error creating socket_dir %s: %s\n",
2374 socket_dir, g_strerror(errno));
2377 md5_hex_digest(md5sum, get_rc_dir());
2379 filename = g_strdup_printf("%s%c%s", socket_dir, G_DIR_SEPARATOR,
2382 debug_print("Using control socket %s\n", filename);
2389 static gchar *get_crashfile_name(void)
2391 static gchar *filename = NULL;
2393 if (filename == NULL) {
2394 filename = g_strdup_printf("%s%cclaws-crashed",
2395 get_tmp_dir(), G_DIR_SEPARATOR);
2401 static gint prohibit_duplicate_launch(void)
2408 path = claws_get_socket_name();
2409 /* Try to connect to the control socket */
2410 sock = fd_connect_unix(path);
2412 if (x_display == NULL)
2413 x_display = g_strdup(g_getenv("DISPLAY"));
2420 /* If connect failed, no other process is running.
2421 * Unlink the potentially existing socket, then
2422 * open it. This has to be done locking a temporary
2423 * file to avoid the race condition where another
2424 * process could have created the socket just in
2427 socket_lock = g_strconcat(path, ".lock",
2429 lock_fd = g_open(socket_lock, O_RDWR|O_CREAT, 0);
2431 debug_print("Couldn't open %s: %s (%d)\n", socket_lock,
2432 g_strerror(errno), errno);
2433 g_free(socket_lock);
2436 if (flock(lock_fd, LOCK_EX) < 0) {
2437 debug_print("Couldn't lock %s: %s (%d)\n", socket_lock,
2438 g_strerror(errno), errno);
2440 g_free(socket_lock);
2446 debug_print("Opening socket %s\n", path);
2447 ret = fd_open_unix(path);
2449 flock(lock_fd, LOCK_UN);
2451 claws_unlink(socket_lock);
2452 g_free(socket_lock);
2459 hmutex = CreateMutexA(NULL, FALSE, "ClawsMail");
2461 debug_print("cannot create Mutex\n");
2464 if (GetLastError() != ERROR_ALREADY_EXISTS) {
2465 sock = fd_open_inet(50216);
2471 sock = fd_connect_inet(50216);
2475 /* remote command mode */
2477 debug_print("another Claws Mail instance is already running.\n");
2479 if (cmd.receive_all) {
2480 CM_FD_WRITE_ALL("receive_all\n");
2481 } else if (cmd.receive) {
2482 CM_FD_WRITE_ALL("receive\n");
2483 } else if (cmd.cancel_receiving) {
2484 CM_FD_WRITE_ALL("cancel_receiving\n");
2485 } else if (cmd.cancel_sending) {
2486 CM_FD_WRITE_ALL("cancel_sending\n");
2487 } else if (cmd.compose && cmd.attach_files) {
2488 gchar *str, *compose_str;
2490 if (cmd.compose_mailto) {
2491 compose_str = g_strdup_printf("compose_attach %s\n",
2492 cmd.compose_mailto);
2494 compose_str = g_strdup("compose_attach\n");
2497 CM_FD_WRITE_ALL(compose_str);
2498 g_free(compose_str);
2500 for (curr = cmd.attach_files; curr != NULL ; curr = curr->next) {
2501 str = (gchar *) ((AttachInfo *)curr->data)->file;
2502 if (((AttachInfo *)curr->data)->insert)
2503 CM_FD_WRITE_ALL("insert ");
2505 CM_FD_WRITE_ALL("attach ");
2506 CM_FD_WRITE_ALL(str);
2507 CM_FD_WRITE_ALL("\n");
2510 CM_FD_WRITE_ALL(".\n");
2511 } else if (cmd.compose) {
2514 if (cmd.compose_mailto) {
2515 compose_str = g_strdup_printf
2516 ("compose %s\n", cmd.compose_mailto);
2518 compose_str = g_strdup("compose\n");
2521 CM_FD_WRITE_ALL(compose_str);
2522 g_free(compose_str);
2523 } else if (cmd.subscribe) {
2524 gchar *str = g_strdup_printf("subscribe %s\n", cmd.subscribe_uri);
2525 CM_FD_WRITE_ALL(str);
2527 } else if (cmd.send) {
2528 CM_FD_WRITE_ALL("send\n");
2529 } else if (cmd.online_mode == ONLINE_MODE_ONLINE) {
2530 CM_FD_WRITE("online\n");
2531 } else if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
2532 CM_FD_WRITE("offline\n");
2533 } else if (cmd.debug) {
2534 CM_FD_WRITE("debug\n");
2535 } else if (cmd.status || cmd.status_full) {
2536 gchar buf[BUFFSIZE];
2538 const gchar *command;
2542 command = cmd.status_full ? "status-full\n" : "status\n";
2543 folders = cmd.status_full ? cmd.status_full_folders :
2546 CM_FD_WRITE_ALL(command);
2547 for (i = 0; folders && i < folders->len; ++i) {
2548 folder = g_ptr_array_index(folders, i);
2549 CM_FD_WRITE_ALL(folder);
2550 CM_FD_WRITE_ALL("\n");
2552 CM_FD_WRITE_ALL(".\n");
2554 fd_gets(sock, buf, sizeof(buf) - 1);
2555 buf[sizeof(buf) - 1] = '\0';
2556 if (!STRNCMP(buf, ".\n")) break;
2557 if (claws_fputs(buf, stdout) == EOF) {
2558 g_warning("writing to stdout failed");
2562 } else if (cmd.exit) {
2563 CM_FD_WRITE_ALL("exit\n");
2564 } else if (cmd.statistics) {
2566 CM_FD_WRITE("statistics\n");
2568 fd_gets(sock, buf, sizeof(buf) - 1);
2569 buf[sizeof(buf) - 1] = '\0';
2570 if (!STRNCMP(buf, ".\n")) break;
2571 if (claws_fputs(buf, stdout) == EOF) {
2572 g_warning("writing to stdout failed");
2576 } else if (cmd.reset_statistics) {
2577 CM_FD_WRITE("reset_statistics\n");
2578 } else if (cmd.target) {
2579 gchar *str = g_strdup_printf("select %s\n", cmd.target);
2580 CM_FD_WRITE_ALL(str);
2582 } else if (cmd.search) {
2583 gchar buf[BUFFSIZE];
2585 g_strdup_printf("search %s\n%s\n%s\n%c\n",
2586 cmd.search_folder, cmd.search_type, cmd.search_request,
2587 (cmd.search_recursive==TRUE)?'1':'0');
2588 CM_FD_WRITE_ALL(str);
2591 fd_gets(sock, buf, sizeof(buf) - 1);
2592 buf[sizeof(buf) - 1] = '\0';
2593 if (!STRNCMP(buf, ".\n")) break;
2594 if (claws_fputs(buf, stdout) == EOF) {
2595 g_warning("writing to stdout failed");
2602 CM_FD_WRITE_ALL("get_display\n");
2603 memset(buf, 0, sizeof(buf));
2604 fd_gets(sock, buf, sizeof(buf) - 1);
2605 buf[sizeof(buf) - 1] = '\0';
2606 if (g_strcmp0(buf, x_display)) {
2607 g_print("Claws Mail is already running on display %s.\n",
2611 sock = fd_connect_unix(path);
2612 CM_FD_WRITE_ALL("popup\n");
2615 CM_FD_WRITE_ALL("popup\n");
2623 static gint lock_socket_remove(void)
2626 gchar *filename, *dirname;
2628 if (lock_socket < 0) {
2632 if (lock_socket_tag > 0) {
2633 g_source_remove(lock_socket_tag);
2635 fd_close(lock_socket);
2638 filename = claws_get_socket_name();
2639 dirname = g_path_get_dirname(filename);
2640 if (claws_unlink(filename) < 0)
2641 FILE_OP_ERROR(filename, "claws_unlink");
2649 static GPtrArray *get_folder_item_list(gint sock)
2651 gchar buf[BUFFSIZE];
2653 GPtrArray *folders = NULL;
2656 fd_gets(sock, buf, sizeof(buf) - 1);
2657 buf[sizeof(buf) - 1] = '\0';
2658 if (!STRNCMP(buf, ".\n")) {
2663 folders = g_ptr_array_new();
2665 item = folder_find_item_from_identifier(buf);
2667 g_ptr_array_add(folders, item);
2669 g_warning("no such folder: %s", buf);
2676 static void lock_socket_input_cb(gpointer data,
2678 GIOCondition condition)
2680 MainWindow *mainwin = (MainWindow *)data;
2682 gchar buf[BUFFSIZE];
2684 sock = fd_accept(source);
2688 fd_gets(sock, buf, sizeof(buf) - 1);
2689 buf[sizeof(buf) - 1] = '\0';
2691 if (!STRNCMP(buf, "popup")) {
2692 main_window_popup(mainwin);
2694 } else if (!STRNCMP(buf, "get_display")) {
2695 CM_FD_WRITE_ALL(x_display);
2697 } else if (!STRNCMP(buf, "receive_all")) {
2698 inc_all_account_mail(mainwin, FALSE, FALSE,
2699 prefs_common.newmail_notify_manu);
2700 } else if (!STRNCMP(buf, "receive")) {
2701 inc_mail(mainwin, prefs_common.newmail_notify_manu);
2702 } else if (!STRNCMP(buf, "cancel_receiving")) {
2705 } else if (!STRNCMP(buf, "cancel_sending")) {
2707 } else if (!STRNCMP(buf, "compose_attach")) {
2708 GList *files = NULL, *curr;
2712 mailto = g_strdup(buf + strlen("compose_attach") + 1);
2713 while (fd_gets(sock, buf, sizeof(buf) - 1) > 0) {
2714 buf[sizeof(buf) - 1] = '\0';
2716 if (!g_strcmp0(buf, "."))
2719 ainfo = g_new0(AttachInfo, 1);
2720 ainfo->file = g_strdup(strstr(buf, " ") + 1);
2721 ainfo->insert = !STRNCMP(buf, "insert ");
2722 files = g_list_append(files, ainfo);
2724 open_compose_new(mailto, files);
2726 curr = g_list_first(files);
2727 while (curr != NULL) {
2728 ainfo = (AttachInfo *)curr->data;
2729 g_free(ainfo->file);
2735 } else if (!STRNCMP(buf, "compose")) {
2736 open_compose_new(buf + strlen("compose") + 1, NULL);
2737 } else if (!STRNCMP(buf, "subscribe")) {
2738 main_window_popup(mainwin);
2739 folder_subscribe(buf + strlen("subscribe") + 1);
2740 } else if (!STRNCMP(buf, "send")) {
2742 } else if (!STRNCMP(buf, "online")) {
2743 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
2744 } else if (!STRNCMP(buf, "offline")) {
2745 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
2746 } else if (!STRNCMP(buf, "debug")) {
2747 debug_set_mode(debug_get_mode() ? FALSE : TRUE);
2748 } else if (!STRNCMP(buf, "status-full") ||
2749 !STRNCMP(buf, "status")) {
2753 folders = get_folder_item_list(sock);
2754 status = folder_get_status
2755 (folders, !STRNCMP(buf, "status-full"));
2756 CM_FD_WRITE_ALL(status);
2757 CM_FD_WRITE_ALL(".\n");
2759 if (folders) g_ptr_array_free(folders, TRUE);
2760 } else if (!STRNCMP(buf, "statistics")) {
2763 g_snprintf(tmp, sizeof(tmp), _("Session statistics\n"));
2764 CM_FD_WRITE_ALL(tmp);
2766 if (prefs_common.date_format) {
2771 lt = localtime(&session_stats.time_started);
2772 fast_strftime(date, len, prefs_common.date_format, lt);
2773 g_snprintf(tmp, sizeof(tmp), _("Started: %s\n"),
2774 lt ? date : ctime(&session_stats.time_started));
2776 g_snprintf(tmp, sizeof(tmp), _("Started: %s\n"),
2777 ctime(&session_stats.time_started));
2778 CM_FD_WRITE_ALL(tmp);
2780 CM_FD_WRITE_ALL("\n");
2782 g_snprintf(tmp, sizeof(tmp), _("Incoming traffic\n"));
2783 CM_FD_WRITE_ALL(tmp);
2785 g_snprintf(tmp, sizeof(tmp), _("Received messages: %d\n"),
2786 session_stats.received);
2787 CM_FD_WRITE_ALL(tmp);
2789 CM_FD_WRITE_ALL("\n");
2791 g_snprintf(tmp, sizeof(tmp), _("Outgoing traffic\n"));
2792 CM_FD_WRITE_ALL(tmp);
2794 g_snprintf(tmp, sizeof(tmp), _("New/redirected messages: %d\n"),
2795 session_stats.sent);
2796 CM_FD_WRITE_ALL(tmp);
2798 g_snprintf(tmp, sizeof(tmp), _("Replied messages: %d\n"),
2799 session_stats.replied);
2800 CM_FD_WRITE_ALL(tmp);
2802 g_snprintf(tmp, sizeof(tmp), _("Forwarded messages: %d\n"),
2803 session_stats.forwarded);
2804 CM_FD_WRITE_ALL(tmp);
2806 g_snprintf(tmp, sizeof(tmp), _("Total outgoing messages: %d\n"),
2807 (session_stats.sent + session_stats.replied +
2808 session_stats.forwarded));
2809 CM_FD_WRITE_ALL(tmp);
2811 CM_FD_WRITE_ALL(".\n");
2812 } else if (!STRNCMP(buf, "reset_statistics")) {
2814 } else if (!STRNCMP(buf, "select ")) {
2815 const gchar *target = buf+7;
2816 mainwindow_jump_to(target, TRUE);
2817 } else if (!STRNCMP(buf, "search ")) {
2818 FolderItem* folderItem = NULL;
2819 GSList *messages = NULL;
2820 gchar *folder_name = NULL;
2821 gchar *request = NULL;
2822 AdvancedSearch *search;
2824 AdvancedSearchType searchType = ADVANCED_SEARCH_EXTENDED;
2826 search = advsearch_new();
2828 folder_name = g_strdup(buf+7);
2829 strretchomp(folder_name);
2831 if (fd_gets(sock, buf, sizeof(buf) - 1) <= 0)
2833 buf[sizeof(buf) - 1] = '\0';
2835 switch (toupper(buf[0])) {
2836 case 'S': searchType = ADVANCED_SEARCH_SUBJECT; break;
2837 case 'F': searchType = ADVANCED_SEARCH_FROM; break;
2838 case 'T': searchType = ADVANCED_SEARCH_TO; break;
2839 case 'M': searchType = ADVANCED_SEARCH_MIXED; break;
2840 case 'G': searchType = ADVANCED_SEARCH_TAG; break;
2841 case 'E': searchType = ADVANCED_SEARCH_EXTENDED; break;
2844 if (fd_gets(sock, buf, sizeof(buf) - 1) <= 0)
2847 buf[sizeof(buf) - 1] = '\0';
2848 request = g_strdup(buf);
2849 strretchomp(request);
2852 if (fd_gets(sock, buf, sizeof(buf) - 1) > 0)
2853 recursive = buf[0] != '0';
2855 buf[sizeof(buf) - 1] = '\0';
2857 debug_print("search: %s %i %s %i\n", folder_name, searchType, request, recursive);
2859 folderItem = folder_find_item_from_identifier(folder_name);
2861 if (folderItem == NULL) {
2862 debug_print("Unknown folder item : '%s', searching folder\n",folder_name);
2863 Folder* folder = folder_find_from_path(folder_name);
2865 folderItem = FOLDER_ITEM(folder->node->data);
2867 debug_print("Unknown folder: '%s'\n",folder_name);
2869 debug_print("%s %s\n",folderItem->name, folderItem->path);
2872 if (folderItem != NULL) {
2873 advsearch_set(search, searchType, request);
2874 advsearch_search_msgs_in_folders(search, &messages, folderItem, recursive);
2876 g_print("Folder '%s' not found.\n'", folder_name);
2880 for (cur = messages; cur != NULL; cur = cur->next) {
2881 MsgInfo* msg = (MsgInfo *)cur->data;
2882 gchar *file = procmsg_get_message_file_path(msg);
2883 CM_FD_WRITE_ALL(file);
2884 CM_FD_WRITE_ALL("\n");
2887 CM_FD_WRITE_ALL(".\n");
2890 g_free(folder_name);
2892 advsearch_free(search);
2893 if (messages != NULL)
2894 procmsg_msg_list_free(messages);
2895 } else if (!STRNCMP(buf, "exit")) {
2896 if (prefs_common.clean_on_exit && !prefs_common.ask_on_clean) {
2897 procmsg_empty_all_trash();
2899 app_will_exit(NULL, mainwin);
2905 static void open_compose_new(const gchar *address, GList *attach_files)
2910 Xstrdup_a(addr, address, return);
2914 compose_new(NULL, addr, attach_files);
2917 static void send_queue(void)
2920 gchar *errstr = NULL;
2921 gboolean error = FALSE;
2922 for (list = folder_get_list(); list != NULL; list = list->next) {
2923 Folder *folder = list->data;
2925 if (folder->queue) {
2926 gint res = procmsg_send_queue
2927 (folder->queue, prefs_common.savemsg,
2931 folder_item_scan(folder->queue);
2939 alertpanel_error_log(_("Some errors occurred "
2940 "while sending queued messages:\n%s"), errstr);
2943 alertpanel_error_log("Some errors occurred "
2944 "while sending queued messages.");
2948 static void quit_signal_handler(int sig)
2950 debug_print("Quitting on signal %d\n", sig);
2952 g_timeout_add(0, clean_quit, NULL);
2955 static void install_basic_sighandlers()
2959 struct sigaction act;
2964 sigaddset(&mask, SIGTERM);
2967 sigaddset(&mask, SIGINT);
2970 sigaddset(&mask, SIGHUP);
2973 act.sa_handler = quit_signal_handler;
2978 sigaction(SIGTERM, &act, 0);
2981 sigaction(SIGINT, &act, 0);
2984 sigaction(SIGHUP, &act, 0);
2987 sigprocmask(SIG_UNBLOCK, &mask, 0);
2988 #endif /* !G_OS_WIN32 */
2991 #if (defined linux && defined SIGIO)
2992 static int mem_notify_fd = 0;
2994 static gboolean clean_caches(gpointer unused)
2996 if (static_mainwindow && static_mainwindow->lock_count > 0)
2998 debug_print("/dev/mem_notify: callback: Freeing some memory now!\n");
2999 folder_clean_cache_memory_force();
3003 static void memory_signal_handler(int sig)
3005 debug_print("/dev/mem_notify: Kernel says we should free up some memory!\n");
3006 g_timeout_add(10, clean_caches, NULL);
3009 static void install_memory_sighandler()
3012 struct sigaction act;
3015 mem_notify_fd = g_open("/dev/mem_notify", O_RDONLY|O_NONBLOCK, 0);
3016 if (mem_notify_fd == -1) {
3017 debug_print("/dev/mem_notify not available (%s)\n",
3022 fcntl(mem_notify_fd, F_SETOWN, getpid());
3023 flags = fcntl(mem_notify_fd, F_GETFL);
3024 fcntl(mem_notify_fd, flags|FASYNC);
3028 sigaddset(&mask, SIGIO);
3030 act.sa_handler = memory_signal_handler;
3034 sigaction(SIGIO, &act, 0);
3036 sigprocmask(SIG_UNBLOCK, &mask, 0);
3038 debug_print("/dev/mem_notify: installed handler\n");
3040 #endif /* linux && SIGIO */
3042 #ifdef HAVE_NETWORKMANAGER_SUPPORT
3043 static void networkmanager_state_change_cb(DBusGProxy *proxy, gchar *dev,
3046 MainWindow *mainWin;
3049 if (static_mainwindow)
3050 mainWin = static_mainwindow;
3052 mainWin = (MainWindow*)data;
3054 if (!prefs_common.use_networkmanager)
3058 GError *error = NULL;
3061 online = networkmanager_is_online(&error);
3063 if(online && went_offline_nm) {
3064 went_offline_nm = FALSE;
3065 main_window_toggle_work_offline(mainWin, FALSE, FALSE);
3066 debug_print("NetworkManager: Went online\n");
3067 log_message(LOG_PROTOCOL, _("NetworkManager: network is online.\n"));
3070 went_offline_nm = TRUE;
3071 main_window_toggle_work_offline(mainWin, TRUE, FALSE);
3072 debug_print("NetworkManager: Went offline\n");
3073 log_message(LOG_PROTOCOL, _("NetworkManager: network is offline.\n"));
3077 debug_print("Failed to get online information from NetworkManager: %s\n",
3079 g_error_free(error);
3083 debug_print("NetworkManager: Cannot change connection state because "
3084 "main window does not exist\n");
3087 /* Returns true (and sets error appropriately, if given) in case of error */
3088 gboolean networkmanager_is_online(GError **error)
3090 DBusGConnection *connection;
3092 GError *tmp_error = NULL;
3096 if (!prefs_common.use_networkmanager)
3101 connection = dbus_g_bus_get(DBUS_BUS_SYSTEM, &tmp_error);
3104 /* If calling code doesn't do error checking, at least print some debug */
3105 if((error == NULL) || (*error == NULL))
3106 debug_print("Failed to open connection to system bus: %s\n",
3107 tmp_error->message);
3108 g_propagate_error(error, tmp_error);
3112 proxy = dbus_g_proxy_new_for_name(connection,
3113 "org.freedesktop.NetworkManager",
3114 "/org/freedesktop/NetworkManager",
3115 "org.freedesktop.NetworkManager");
3117 retVal = dbus_g_proxy_call(proxy,"state",&tmp_error, G_TYPE_INVALID,
3118 G_TYPE_UINT, &state, G_TYPE_INVALID);
3121 g_object_unref(proxy);
3123 dbus_g_connection_unref(connection);
3126 /* If calling code doesn't do error checking, at least print some debug */
3127 if((error == NULL) || (*error == NULL))
3128 debug_print("Failed to get state info from NetworkManager: %s\n",
3129 tmp_error->message);
3130 g_propagate_error(error, tmp_error);
3133 return (state == NM_STATE_CONNECTED_LOCAL ||
3134 state == NM_STATE_CONNECTED_SITE ||
3135 state == NM_STATE_CONNECTED_GLOBAL ||
3136 state == NM_STATE_UNKNOWN);