fix bug 4773, 'remove obsolescent AC_C_CONST'
[claws.git] / src / main.c
blob87c9b65495bd88aceb7f93317a14d631438e6565
1 /*
2 * Claws Mail -- a GTK based, lightweight, and fast e-mail client
3 * Copyright (C) 1999-2023 the Claws Mail team and Hiroyuki Yamamoto
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/>.
19 #ifdef HAVE_CONFIG_H
20 # include "config.h"
21 #include "claws-features.h"
22 #endif
24 #include "defs.h"
26 #include <glib.h>
27 #include <glib/gi18n.h>
28 #include <gtk/gtk.h>
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
47 #if HAVE_FLOCK
48 #include <sys/file.h>
49 #endif
51 #include "file_checker.h"
52 #include "wizard.h"
53 #ifdef HAVE_STARTUP_NOTIFICATION
54 #ifdef GDK_WINDOWING_X11
55 # define SN_API_NOT_YET_FROZEN
56 # include <libsn/sn-launchee.h>
57 # include <gdk/gdkx.h>
58 #endif
59 #endif
61 #ifdef HAVE_DBUS_GLIB
62 #include <dbus/dbus-glib.h>
63 #endif
64 #ifdef HAVE_NETWORKMANAGER_SUPPORT
65 #include <NetworkManager.h>
66 #endif
67 #ifdef HAVE_VALGRIND
68 #include <valgrind.h>
69 #endif
70 #ifdef HAVE_SVG
71 #include <librsvg/rsvg.h>
72 #endif
74 #include "claws.h"
75 #include "main.h"
76 #include "mainwindow.h"
77 #include "folderview.h"
78 #include "image_viewer.h"
79 #include "summaryview.h"
80 #include "prefs_common.h"
81 #include "prefs_account.h"
82 #include "prefs_actions.h"
83 #include "prefs_ext_prog.h"
84 #include "prefs_fonts.h"
85 #include "prefs_image_viewer.h"
86 #include "prefs_message.h"
87 #include "prefs_migration.h"
88 #include "prefs_receive.h"
89 #include "prefs_msg_colors.h"
90 #include "prefs_quote.h"
91 #include "prefs_spelling.h"
92 #include "prefs_summaries.h"
93 #include "prefs_themes.h"
94 #include "prefs_other.h"
95 #include "prefs_proxy.h"
96 #include "prefs_logging.h"
97 #include "prefs_send.h"
98 #include "prefs_wrapping.h"
99 #include "prefs_compose_writing.h"
100 #include "prefs_display_header.h"
101 #include "account.h"
102 #include "procmsg.h"
103 #include "inc.h"
104 #include "imap.h"
105 #include "send_message.h"
106 #include "md5.h"
107 #include "import.h"
108 #include "manage_window.h"
109 #include "alertpanel.h"
110 #include "statusbar.h"
111 #ifndef USE_ALT_ADDRBOOK
112 #include "addressbook.h"
113 #else
114 #include "addressbook-dbus.h"
115 #endif
116 #include "compose.h"
117 #include "folder.h"
118 #include "folder_item_prefs.h"
119 #include "setup.h"
120 #include "utils.h"
121 #include "gtkutils.h"
122 #include "socket.h"
123 #include "log.h"
124 #include "prefs_toolbar.h"
125 #include "plugin.h"
126 #include "mh_gtk.h"
127 #include "imap_gtk.h"
128 #include "news_gtk.h"
129 #include "matcher.h"
130 #include "tags.h"
131 #include "hooks.h"
132 #include "menu.h"
133 #include "quicksearch.h"
134 #include "advsearch.h"
135 #include "avatars.h"
136 #include "passwordstore.h"
137 #include "file-utils.h"
139 #ifdef HAVE_LIBETPAN
140 #include "imap-thread.h"
141 #include "nntp-thread.h"
142 #endif
143 #include "stock_pixmap.h"
144 #ifdef USE_GNUTLS
145 # include "ssl.h"
146 #endif
148 #include "version.h"
150 #include "crash.h"
152 #include "timing.h"
154 #ifdef HAVE_NETWORKMANAGER_SUPPORT
155 /* Went offline due to NetworkManager */
156 static gboolean went_offline_nm;
157 #endif
160 #ifdef HAVE_DBUS_GLIB
161 static DBusGProxy *awn_proxy = NULL;
162 #endif
164 gchar *prog_version;
165 #if (defined HAVE_LIBSM || defined CRASH_DIALOG)
166 gchar *argv0;
167 #endif
169 #ifdef HAVE_STARTUP_NOTIFICATION
170 static SnLauncheeContext *sn_context = NULL;
171 static SnDisplay *sn_display = NULL;
172 #endif
174 static gint lock_socket = -1;
175 static gint lock_socket_tag = 0;
177 typedef enum
179 ONLINE_MODE_DONT_CHANGE,
180 ONLINE_MODE_ONLINE,
181 ONLINE_MODE_OFFLINE
182 } OnlineMode;
184 static struct RemoteCmd {
185 gboolean receive;
186 gboolean receive_all;
187 gboolean cancel_receiving;
188 gboolean cancel_sending;
189 gboolean compose;
190 const gchar *compose_mailto;
191 GList *attach_files;
192 gboolean search;
193 const gchar *search_folder;
194 const gchar *search_type;
195 const gchar *search_request;
196 gboolean search_recursive;
197 gboolean status;
198 gboolean status_full;
199 gboolean statistics;
200 gboolean reset_statistics;
201 GPtrArray *status_folders;
202 GPtrArray *status_full_folders;
203 gboolean send;
204 gboolean crash;
205 int online_mode;
206 gchar *crash_params;
207 gboolean exit;
208 gboolean subscribe;
209 const gchar *subscribe_uri;
210 const gchar *target;
211 gboolean debug;
212 const gchar *geometry;
213 } cmd;
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 (int *argc,
222 char ***argv);
223 static gchar * get_crashfile_name (void);
224 static gint lock_socket_remove (void);
225 static void lock_socket_input_cb (gpointer data,
226 gint source,
227 GIOCondition condition);
229 static void open_compose_new (const gchar *address,
230 GList *attach_files);
232 static void send_queue (void);
233 static void initial_processing (FolderItem *item, gpointer data);
234 #ifndef G_OS_WIN32
235 static void quit_signal_handler (int sig);
236 #endif
237 static void install_basic_sighandlers (void);
238 static void exit_claws (MainWindow *mainwin);
240 #ifdef HAVE_NETWORKMANAGER_SUPPORT
241 static void networkmanager_state_change_cb(DBusGProxy *proxy, gchar *dev,
242 gpointer data);
243 #endif
245 #define MAKE_DIR_IF_NOT_EXIST(dir) \
247 if (!is_dir_exist(dir)) { \
248 if (is_file_exist(dir)) { \
249 alertpanel_warning \
250 (_("File '%s' already exists.\n" \
251 "Can't create folder."), \
252 dir); \
253 return 1; \
255 if (make_dir(dir) < 0) \
256 return 1; \
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)
282 Display *xdisplay;
283 GtkWidget *hack = NULL;
285 if (with_window) {
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,
297 sn_error_trap_push,
298 sn_error_trap_pop);
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);
307 if (with_window) {
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();
318 g_usleep(50000);
321 static gboolean sc_starting = FALSE;
323 static gboolean defer_check_all(void *data)
325 gboolean autochk = GPOINTER_TO_INT(data);
327 if (!sc_starting) {
328 inc_all_account_mail(static_mainwindow, autochk, FALSE,
329 prefs_common.newmail_notify_manu);
331 } else {
332 inc_all_account_mail(static_mainwindow, FALSE,
333 prefs_common.chk_on_startup,
334 prefs_common.newmail_notify_manu);
335 sc_starting = FALSE;
336 main_window_set_menu_sensitive(static_mainwindow);
337 toolbar_main_set_sensitive(static_mainwindow);
339 return FALSE;
342 static gboolean defer_check(void *data)
344 inc_mail(static_mainwindow, prefs_common.newmail_notify_manu);
346 if (sc_starting) {
347 sc_starting = FALSE;
348 main_window_set_menu_sensitive(static_mainwindow);
349 toolbar_main_set_sensitive(static_mainwindow);
351 return FALSE;
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) {
361 defer_check(NULL);
363 mainwindow_jump_to(data, FALSE);
364 if (sc_starting) {
365 sc_starting = FALSE;
366 main_window_set_menu_sensitive(static_mainwindow);
367 toolbar_main_set_sensitive(static_mainwindow);
369 return FALSE;
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);
387 g_free(message2);
388 g_free(message);
389 message = tmp;
392 gint r = 0;
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 NULL, _("_No"), NULL, _("_Yes"), NULL, NULL, ALERTFOCUS_SECOND,
410 FALSE, keep_backup_chk, ALERT_QUESTION) != G_ALERTALTERNATE) {
411 return FALSE;
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
416 * it in place. */
417 if (backup) {
418 backup_mode:
419 window = label_window_create(_("Copying configuration... This may take a while..."));
420 GTK_EVENTS_FLUSH();
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
426 * new directory */
427 if (r != 0) {
428 alertpanel_error(_("Migration failed!"));
429 remove_dir_recursive(new_cfg_dir);
430 } else {
431 if (!backup) {
432 /* fast mode failed, but we don't want backup */
433 remove_dir_recursive(old_cfg_dir);
436 } else {
437 window = label_window_create(_("Migrating configuration..."));
438 GTK_EVENTS_FLUSH();
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 */
444 if (r != 0) {
445 FILE_OP_ERROR(new_cfg_dir, "g_rename");
446 debug_print("rename failed, trying copy\n");
447 goto backup_mode;
450 return (r == 0);
453 static int migrate_common_rc(const gchar *old_rc, const gchar *new_rc)
455 FILE *oldfp, *newfp;
456 gchar *plugin_path, *old_plugin_path, *new_plugin_path;
457 gchar buf[BUFFSIZE];
458 gboolean err = FALSE;
460 oldfp = claws_fopen(old_rc, "r");
461 if (!oldfp)
462 return -1;
463 newfp = claws_fopen(new_rc, "w");
464 if (!newfp) {
465 claws_fclose(oldfp);
466 return -1;
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);
476 g_free(end);
477 } else {
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);
484 } else {
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);
491 g_free(plugin_path);
492 g_free(new_plugin_path);
493 g_free(old_plugin_path);
494 claws_fclose(oldfp);
495 if (claws_safe_fclose(newfp) == EOF)
496 err = TRUE;
498 return (err ? -1:0);
501 #ifdef HAVE_LIBSM
502 static void
503 sc_client_set_value (MainWindow *mainwin,
504 gchar *name,
505 char *type,
506 int num_vals,
507 SmPropValue *vals)
509 SmProp *proplist[1];
510 SmProp prop;
512 prop.name = name;
513 prop.type = type;
514 prop.num_vals = num_vals;
515 prop.vals = vals;
517 proplist[0]= &prop;
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)
524 clean_quit(NULL);
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,
540 int save_style,
541 gboolean shutdown,
542 int interact_style,
543 gboolean fast) {
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,
559 gpointer data)
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);
574 } else {
575 IceSetShutdownNegotiation (connection, False);
576 IceCloseConnection (connection);
580 return TRUE;
583 static void new_ice_connection (IceConn connection, IcePointer client_data, Bool opening,
584 IcePointer *watch_data)
586 guint input_id;
588 if (opening) {
589 GIOChannel *channel;
590 /* Make sure we don't pass on these file descriptors to any
591 exec'ed children */
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,
599 connection);
600 g_io_channel_unref (channel);
602 *watch_data = (IcePointer) GUINT_TO_POINTER (input_id);
603 } else {
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;
613 gchar *client_id;
614 IceIOErrorHandler default_handler;
616 if (connected)
617 return;
618 connected = TRUE;
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,
648 &callbacks,
649 NULL, &client_id,
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)
660 g_free(client_id);
662 if (error_string_ret[0] || mainwin->smc_conn == NULL)
663 g_warning("while connecting to session manager: %s",
664 error_string_ret);
665 else {
666 SmPropValue *vals;
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);
679 g_free(vals);
683 #endif
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;
698 #ifdef G_OS_WIN32
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)
706 BOOL ret;
707 DWORD bytes_written;
709 ret = WriteFile(win32_debug_log, string, strlen(string), &bytes_written, NULL);
710 if (!ret) {
711 DWORD err = GetLastError();
712 gchar *tmp;
714 tmp = g_strdup_printf("Error: WriteFile in failed with error 0x%lx. Buffer contents:\n%s", err, string);
715 OutputDebugString(tmp);
716 g_free(tmp);
720 static void win32_print_stdout(const gchar *string)
722 if (win32_debug_log) {
723 win32_log_WriteFile(string);
727 GLogWriterOutput win32_log_writer(GLogLevelFlags log_level, const GLogField *fields, gsize n_fields, gpointer user_data)
729 gchar *formatted;
730 gchar *out;
732 g_return_val_if_fail(win32_debug_log != NULL, G_LOG_WRITER_UNHANDLED);
733 g_return_val_if_fail(fields != NULL, G_LOG_WRITER_UNHANDLED);
734 g_return_val_if_fail(n_fields > 0, G_LOG_WRITER_UNHANDLED);
736 formatted = g_log_writer_format_fields(log_level, fields, n_fields, FALSE);
737 out = g_strdup_printf("%s\n", formatted);
739 win32_log_WriteFile(out);
741 g_free(formatted);
742 g_free(out);
744 return G_LOG_WRITER_HANDLED;
747 static void win32_log(const gchar *log_domain, GLogLevelFlags log_level, const gchar* message, gpointer user_data)
749 gchar *out;
751 if (win32_debug_log) {
752 const gchar* type;
754 switch(log_level & G_LOG_LEVEL_MASK)
756 case G_LOG_LEVEL_ERROR:
757 type="error";
758 break;
759 case G_LOG_LEVEL_CRITICAL:
760 type="critical";
761 break;
762 case G_LOG_LEVEL_WARNING:
763 type="warning";
764 break;
765 case G_LOG_LEVEL_MESSAGE:
766 type="message";
767 break;
768 case G_LOG_LEVEL_INFO:
769 type="info";
770 break;
771 case G_LOG_LEVEL_DEBUG:
772 type="debug";
773 break;
774 default:
775 type="N/A";
778 if (log_domain)
779 out = g_strdup_printf("%s: %s: %s", log_domain, type, message);
780 else
781 out = g_strdup_printf("%s: %s", type, message);
783 win32_log_WriteFile(out);
785 g_free(out);
789 static void win32_open_log(void)
791 gchar *logfile = win32_debug_log_path();
792 gchar *oldlogfile = g_strconcat(logfile, ".bak", NULL);
794 if (is_file_exist(logfile)) {
795 if (rename_force(logfile, oldlogfile) < 0)
796 FILE_OP_ERROR(logfile, "rename");
799 win32_debug_log = CreateFile(logfile,
800 GENERIC_WRITE,
801 FILE_SHARE_READ,
802 NULL,
803 CREATE_NEW,
804 FILE_ATTRIBUTE_NORMAL,
805 NULL);
807 if (win32_debug_log == INVALID_HANDLE_VALUE) {
808 win32_debug_log = NULL;
811 g_free(logfile);
812 g_free(oldlogfile);
814 if (win32_debug_log) {
815 g_set_print_handler(win32_print_stdout);
816 g_set_printerr_handler(win32_print_stdout);
818 win32_log_handler_app_id = g_log_set_handler(NULL, G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
819 | G_LOG_FLAG_RECURSION, win32_log, NULL);
820 win32_log_handler_glib_id = g_log_set_handler("GLib", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
821 | G_LOG_FLAG_RECURSION, win32_log, NULL);
822 win32_log_handler_gtk_id = g_log_set_handler("Gtk", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
823 | G_LOG_FLAG_RECURSION, win32_log, NULL);
825 g_log_set_writer_func(&win32_log_writer, NULL, NULL);
829 static void win32_close_log(void)
831 if (win32_debug_log) {
832 g_log_remove_handler("", win32_log_handler_app_id);
833 g_log_remove_handler("GLib", win32_log_handler_glib_id);
834 g_log_remove_handler("Gtk", win32_log_handler_gtk_id);
835 CloseHandle(win32_debug_log);
836 win32_debug_log = NULL;
839 #endif
841 static void main_dump_features_list(gboolean show_debug_only)
842 /* display compiled-in features list */
844 if (show_debug_only && !debug_get_mode())
845 return;
847 if (show_debug_only)
848 debug_print("runtime GTK %d.%d.%d / GLib %d.%d.%d\n",
849 gtk_major_version, gtk_minor_version, gtk_micro_version,
850 glib_major_version, glib_minor_version, glib_micro_version);
851 else
852 g_print("runtime GTK %d.%d.%d / GLib %d.%d.%d\n",
853 gtk_major_version, gtk_minor_version, gtk_micro_version,
854 glib_major_version, glib_minor_version, glib_micro_version);
855 if (show_debug_only)
856 debug_print("buildtime GTK %d.%d.%d / GLib %d.%d.%d\n",
857 GTK_MAJOR_VERSION, GTK_MINOR_VERSION, GTK_MICRO_VERSION,
858 GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION);
859 else
860 g_print("buildtime GTK %d.%d.%d / GLib %d.%d.%d\n",
861 GTK_MAJOR_VERSION, GTK_MINOR_VERSION, GTK_MICRO_VERSION,
862 GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION);
864 if (show_debug_only)
865 debug_print("Compiled-in features:\n");
866 else
867 g_print("Compiled-in features:\n");
868 #if HAVE_LIBCOMPFACE
869 if (show_debug_only)
870 debug_print(" compface\n");
871 else
872 g_print(" compface\n");
873 #endif
874 #if USE_ENCHANT
875 if (show_debug_only)
876 debug_print(" Enchant\n");
877 else
878 g_print(" Enchant\n");
879 #endif
880 #if USE_GNUTLS
881 if (show_debug_only)
882 debug_print(" GnuTLS\n");
883 else
884 g_print(" GnuTLS\n");
885 #endif
886 #if INET6
887 if (show_debug_only)
888 debug_print(" IPv6\n");
889 else
890 g_print(" IPv6\n");
891 #endif
892 #if HAVE_ICONV
893 if (show_debug_only)
894 debug_print(" iconv\n");
895 else
896 g_print(" iconv\n");
897 #endif
898 #if USE_JPILOT
899 if (show_debug_only)
900 debug_print(" JPilot\n");
901 else
902 g_print(" JPilot\n");
903 #endif
904 #if USE_LDAP
905 if (show_debug_only)
906 debug_print(" LDAP\n");
907 else
908 g_print(" LDAP\n");
909 #endif
910 #if HAVE_LIBETPAN
911 if (show_debug_only)
912 debug_print(" libetpan %d.%d\n", LIBETPAN_VERSION_MAJOR, LIBETPAN_VERSION_MINOR);
913 else
914 g_print(" libetpan %d.%d\n", LIBETPAN_VERSION_MAJOR, LIBETPAN_VERSION_MINOR);
915 #endif
916 #if HAVE_LIBSM
917 if (show_debug_only)
918 debug_print(" libSM\n");
919 else
920 g_print(" libSM\n");
921 #endif
922 #if HAVE_NETWORKMANAGER_SUPPORT
923 if (show_debug_only)
924 debug_print(" NetworkManager\n");
925 else
926 g_print(" NetworkManager\n");
927 #endif
928 #if HAVE_SVG
929 if (show_debug_only)
930 debug_print(" librSVG " LIBRSVG_VERSION "\n");
931 else
932 g_print(" librSVG " LIBRSVG_VERSION "\n");
933 #endif
936 #ifdef HAVE_DBUS_GLIB
937 static gulong dbus_item_hook_id = HOOK_NONE;
938 static gulong dbus_folder_hook_id = HOOK_NONE;
940 static void uninstall_dbus_status_handler(void)
942 if(awn_proxy)
943 g_object_unref(awn_proxy);
944 awn_proxy = NULL;
945 if (dbus_item_hook_id != HOOK_NONE)
946 hooks_unregister_hook(FOLDER_ITEM_UPDATE_HOOKLIST, dbus_item_hook_id);
947 if (dbus_folder_hook_id != HOOK_NONE)
948 hooks_unregister_hook(FOLDER_UPDATE_HOOKLIST, dbus_folder_hook_id);
951 static void dbus_update(FolderItem *removed_item)
953 guint new, unread, unreadmarked, marked, total;
954 guint replied, forwarded, locked, ignored, watched;
955 gchar *buf;
956 GError *error = NULL;
958 folder_count_total_msgs(&new, &unread, &unreadmarked, &marked, &total,
959 &replied, &forwarded, &locked, &ignored,
960 &watched);
961 if (removed_item) {
962 total -= removed_item->total_msgs;
963 new -= removed_item->new_msgs;
964 unread -= removed_item->unread_msgs;
967 if (new > 0) {
968 buf = g_strdup_printf("%d", new);
969 dbus_g_proxy_call(awn_proxy, "SetInfoByName", &error,
970 G_TYPE_STRING, "claws-mail",
971 G_TYPE_STRING, buf,
972 G_TYPE_INVALID, G_TYPE_INVALID);
973 g_free(buf);
975 } else {
976 dbus_g_proxy_call(awn_proxy, "UnsetInfoByName", &error, G_TYPE_STRING,
977 "claws-mail", G_TYPE_INVALID, G_TYPE_INVALID);
979 if (error) {
980 debug_print("%s\n", error->message);
981 g_error_free(error);
985 static gboolean dbus_status_update_folder_hook(gpointer source, gpointer data)
987 FolderUpdateData *hookdata;
988 hookdata = source;
989 if (hookdata->update_flags & FOLDER_REMOVE_FOLDERITEM)
990 dbus_update(hookdata->item);
991 else
992 dbus_update(NULL);
994 return FALSE;
997 static gboolean dbus_status_update_item_hook(gpointer source, gpointer data)
999 dbus_update(NULL);
1001 return FALSE;
1004 static void install_dbus_status_handler(void)
1006 GError *tmp_error = NULL;
1007 DBusGConnection *connection = dbus_g_bus_get(DBUS_BUS_SESSION, &tmp_error);
1009 if(!connection) {
1010 /* If calling code doesn't do error checking, at least print some debug */
1011 debug_print("Failed to open connection to session bus: %s\n",
1012 tmp_error->message);
1013 g_error_free(tmp_error);
1014 return;
1016 awn_proxy = dbus_g_proxy_new_for_name(connection,
1017 "com.google.code.Awn",
1018 "/com/google/code/Awn",
1019 "com.google.code.Awn");
1020 dbus_item_hook_id = hooks_register_hook (FOLDER_ITEM_UPDATE_HOOKLIST, dbus_status_update_item_hook, NULL);
1021 if (dbus_item_hook_id == HOOK_NONE) {
1022 g_warning("failed to register folder item update hook");
1023 uninstall_dbus_status_handler();
1024 return;
1027 dbus_folder_hook_id = hooks_register_hook (FOLDER_UPDATE_HOOKLIST, dbus_status_update_folder_hook, NULL);
1028 if (dbus_folder_hook_id == HOOK_NONE) {
1029 g_warning("failed to register folder update hook");
1030 uninstall_dbus_status_handler();
1031 return;
1034 #endif
1036 static void reset_statistics(void)
1038 /* (re-)initialize session statistics */
1039 session_stats.received = 0;
1040 session_stats.sent = 0;
1041 session_stats.replied = 0;
1042 session_stats.forwarded = 0;
1043 session_stats.spam = 0;
1044 session_stats.time_started = time(NULL);
1047 int main(int argc, char *argv[])
1049 #ifdef HAVE_DBUS_GLIB
1050 DBusGConnection *connection;
1051 GError *error;
1052 #endif
1053 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1054 DBusGProxy *nm_proxy;
1055 #endif
1056 gchar *userrc;
1057 MainWindow *mainwin;
1058 FolderView *folderview;
1059 GdkPixbuf *icon;
1060 gboolean crash_file_present = FALSE;
1061 guint num_folder_class = 0;
1062 gboolean asked_for_migration = FALSE;
1063 gboolean start_done = TRUE;
1064 GSList *plug_list = NULL;
1065 gboolean never_ran = FALSE;
1066 gboolean mainwin_shown = FALSE;
1067 gint ret;
1069 START_TIMING("startup");
1071 sc_starting = TRUE;
1073 #ifdef G_OS_WIN32
1074 win32_open_log();
1075 #endif
1076 if (!claws_init(&argc, &argv)) {
1077 #ifdef G_OS_WIN32
1078 win32_close_log();
1079 #endif
1080 return 0;
1083 prog_version = PROG_VERSION;
1084 #if (defined HAVE_LIBSM || defined CRASH_DIALOG)
1085 argv0 = g_strdup(argv[0]);
1086 #endif
1088 parse_cmd_opt(argc, argv);
1090 sock_init();
1092 /* check and create unix domain socket for remote operation */
1093 lock_socket = prohibit_duplicate_launch(&argc, &argv);
1094 if (lock_socket < 0) {
1095 #ifdef HAVE_STARTUP_NOTIFICATION
1096 #ifdef GDK_WINDOWING_X11
1097 if (GDK_IS_X11_DISPLAY(gdk_display_get_default())) {
1098 if (gtk_init_check(&argc, &argv))
1099 startup_notification_complete(TRUE);
1101 #endif
1102 #endif
1103 return 0;
1106 main_dump_features_list(TRUE);
1107 prefs_prepare_cache();
1109 #ifdef CRASH_DIALOG
1110 if (cmd.crash) {
1111 gtk_init(&argc, &argv);
1112 crash_main(cmd.crash_params);
1113 #ifdef G_OS_WIN32
1114 win32_close_log();
1115 #endif
1116 return 0;
1118 crash_install_handlers();
1119 #endif
1120 install_basic_sighandlers();
1122 if (cmd.status || cmd.status_full || cmd.search ||
1123 cmd.statistics || cmd.reset_statistics ||
1124 cmd.cancel_receiving || cmd.cancel_sending ||
1125 cmd.debug) {
1126 puts("0 Claws Mail not running.");
1127 lock_socket_remove();
1128 return 0;
1131 if (cmd.exit)
1132 return 0;
1134 reset_statistics();
1136 gtk_init(&argc, &argv);
1138 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1139 went_offline_nm = FALSE;
1140 nm_proxy = NULL;
1141 #endif
1142 #ifdef HAVE_DBUS_GLIB
1143 error = NULL;
1144 connection = dbus_g_bus_get(DBUS_BUS_SYSTEM, &error);
1146 if(!connection) {
1147 debug_print("Failed to open connection to system bus: %s\n", error->message);
1148 g_error_free(error);
1150 else {
1151 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1152 nm_proxy = dbus_g_proxy_new_for_name(connection,
1153 "org.freedesktop.NetworkManager",
1154 "/org/freedesktop/NetworkManager",
1155 "org.freedesktop.NetworkManager");
1156 if (nm_proxy) {
1157 dbus_g_proxy_add_signal(nm_proxy, "StateChanged", G_TYPE_UINT, G_TYPE_INVALID);
1158 dbus_g_proxy_connect_signal(nm_proxy, "StateChanged",
1159 G_CALLBACK(networkmanager_state_change_cb),
1160 NULL,NULL);
1162 #endif
1163 install_dbus_status_handler();
1165 #endif
1167 gtkut_create_ui_manager();
1169 /* Create container for all the menus we will be adding */
1170 MENUITEM_ADDUI("/", "Menus", NULL, GTK_UI_MANAGER_MENUBAR);
1172 #ifdef G_OS_WIN32
1173 CHDIR_EXEC_CODE_RETURN_VAL_IF_FAIL(get_home_dir(), 1, win32_close_log(););
1174 #else
1175 CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
1176 #endif
1178 /* no config dir exists. See if we can migrate an old config. */
1179 if (!is_dir_exist(get_rc_dir())) {
1180 prefs_destroy_cache();
1181 gboolean r = FALSE;
1183 /* if one of the old dirs exist, we'll ask if the user
1184 * want to migrates, and r will be TRUE if he said yes
1185 * and migration succeeded, and FALSE otherwise.
1187 if (is_dir_exist(OLD_GTK2_RC_DIR)) {
1188 r = migrate_old_config(OLD_GTK2_RC_DIR, get_rc_dir(),
1189 g_strconcat("Sylpheed-Claws 2.6.0 ", _("(or older)"), NULL));
1190 asked_for_migration = TRUE;
1191 } else if (is_dir_exist(OLDER_GTK2_RC_DIR)) {
1192 r = migrate_old_config(OLDER_GTK2_RC_DIR, get_rc_dir(),
1193 g_strconcat("Sylpheed-Claws 1.9.15 ",_("(or older)"), NULL));
1194 asked_for_migration = TRUE;
1195 } else if (is_dir_exist(OLD_GTK1_RC_DIR)) {
1196 r = migrate_old_config(OLD_GTK1_RC_DIR, get_rc_dir(),
1197 g_strconcat("Sylpheed-Claws 1.0.5 ",_("(or older)"), NULL));
1198 asked_for_migration = TRUE;
1199 } else if (is_dir_exist(SYLPHEED_RC_DIR)) {
1200 r = migrate_old_config(SYLPHEED_RC_DIR, get_rc_dir(), "Sylpheed");
1201 asked_for_migration = TRUE;
1204 /* If migration failed or the user didn't want to do it,
1205 * we create a new one (and we'll hit wizard later).
1207 if (r == FALSE && !is_dir_exist(get_rc_dir())) {
1208 #ifdef G_OS_UNIX
1209 if (copy_dir(SYSCONFDIR "/skel/.claws-mail", get_rc_dir()) < 0) {
1210 #endif
1211 if (!is_dir_exist(get_rc_dir()) && make_dir(get_rc_dir()) < 0) {
1212 #ifdef G_OS_WIN32
1213 win32_close_log();
1214 #endif
1215 exit(1);
1217 #ifdef G_OS_UNIX
1219 #endif
1224 if (!is_file_exist(RC_DIR G_DIR_SEPARATOR_S COMMON_RC) &&
1225 is_file_exist(RC_DIR G_DIR_SEPARATOR_S OLD_COMMON_RC)) {
1226 /* post 2.6 name change */
1227 migrate_common_rc(RC_DIR G_DIR_SEPARATOR_S OLD_COMMON_RC,
1228 RC_DIR G_DIR_SEPARATOR_S COMMON_RC);
1231 if (!cmd.exit)
1232 plugin_load_all("Common");
1234 userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, "gtkrc-2.0", NULL);
1235 gtk_rc_parse(userrc);
1236 g_free(userrc);
1238 userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
1240 if (copy_file(userrc, userrc, TRUE) < 0) {
1241 g_warning("can't copy %s to %s.bak",
1242 userrc, userrc);
1245 gtk_accel_map_load (userrc);
1246 g_free(userrc);
1248 #ifdef G_OS_WIN32
1249 CHDIR_EXEC_CODE_RETURN_VAL_IF_FAIL(get_rc_dir(), 1, win32_close_log(););
1250 #else
1251 CHDIR_RETURN_VAL_IF_FAIL(get_rc_dir(), 1);
1252 #endif
1254 MAKE_DIR_IF_NOT_EXIST(get_mail_base_dir());
1255 MAKE_DIR_IF_NOT_EXIST(get_imap_cache_dir());
1256 MAKE_DIR_IF_NOT_EXIST(get_news_cache_dir());
1257 MAKE_DIR_IF_NOT_EXIST(get_mime_tmp_dir());
1258 MAKE_DIR_IF_NOT_EXIST(get_tmp_dir());
1259 MAKE_DIR_IF_NOT_EXIST(UIDL_DIR);
1261 crash_file_present = is_file_exist(get_crashfile_name());
1262 /* remove temporary files */
1263 remove_all_files(get_tmp_dir());
1264 remove_all_files(get_mime_tmp_dir());
1266 if (!cmd.crash && crash_file_present)
1267 claws_crashed_bool = TRUE;
1269 if (is_file_exist("claws.log")) {
1270 if (rename_force("claws.log", "claws.log.bak") < 0)
1271 FILE_OP_ERROR("claws.log", "rename");
1273 set_log_file(LOG_PROTOCOL, "claws.log");
1275 if (is_file_exist("filtering.log")) {
1276 if (rename_force("filtering.log", "filtering.log.bak") < 0)
1277 FILE_OP_ERROR("filtering.log", "rename");
1279 set_log_file(LOG_DEBUG_FILTERING, "filtering.log");
1281 #ifdef G_OS_WIN32
1282 CHDIR_EXEC_CODE_RETURN_VAL_IF_FAIL(get_home_dir(), 1, win32_close_log(););
1283 #else
1284 CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
1285 #endif
1287 folder_system_init();
1288 prefs_common_read_config();
1290 if (prefs_update_config_version_common() < 0) {
1291 debug_print("Main configuration file version upgrade failed, exiting\n");
1292 #ifdef G_OS_WIN32
1293 win32_close_log();
1294 #endif
1295 exit(200);
1298 prefs_themes_init();
1299 prefs_fonts_init();
1300 prefs_ext_prog_init();
1301 prefs_wrapping_init();
1302 prefs_compose_writing_init();
1303 prefs_msg_colors_init();
1304 image_viewer_init();
1305 prefs_image_viewer_init();
1306 prefs_quote_init();
1307 prefs_summaries_init();
1308 prefs_message_init();
1309 prefs_other_init();
1310 prefs_proxy_init();
1311 prefs_logging_init();
1312 prefs_receive_init();
1313 prefs_send_init();
1314 tags_read_tags();
1315 matcher_init();
1316 #ifdef USE_ENCHANT
1317 gtkaspell_checkers_init();
1318 prefs_spelling_init();
1319 #endif
1321 codeconv_set_allow_jisx0201_kana(prefs_common.allow_jisx0201_kana);
1322 codeconv_set_broken_are_utf8(prefs_common.broken_are_utf8);
1324 #ifdef G_OS_WIN32
1325 if(prefs_common.gtk_theme && strcmp(prefs_common.gtk_theme, DEFAULT_W32_GTK_THEME))
1326 gtk_settings_set_string_property(gtk_settings_get_default(),
1327 "gtk-theme-name",
1328 prefs_common.gtk_theme,
1329 "XProperty");
1330 #endif
1333 sock_set_io_timeout(prefs_common.io_timeout_secs);
1334 prefs_actions_read_config();
1335 prefs_display_header_read_config();
1336 /* prefs_filtering_read_config(); */
1337 #ifndef USE_ALT_ADDRBOOK
1338 addressbook_read_file();
1339 #else
1340 g_clear_error(&error);
1341 if (! addressbook_start_service(&error)) {
1342 g_warning("%s", error->message);
1343 g_clear_error(&error);
1345 else {
1346 addressbook_install_hooks(&error);
1348 #endif
1349 gtkut_widget_init();
1350 priv_pixbuf_gdk(PRIV_PIXMAP_CLAWS_MAIL_ICON, &icon);
1351 gtk_window_set_default_icon(icon);
1353 folderview_initialize();
1355 mh_gtk_init();
1356 imap_gtk_init();
1357 news_gtk_init();
1359 mainwin = main_window_create();
1361 if (!check_file_integrity())
1362 exit(1);
1364 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1365 networkmanager_state_change_cb(nm_proxy,NULL,mainwin);
1366 #endif
1368 manage_window_focus_in(mainwin->window, NULL, NULL);
1369 folderview = mainwin->folderview;
1371 folderview_freeze(mainwin->folderview);
1372 folder_item_update_freeze();
1374 if ((ret = passwd_store_read_config()) < 0) {
1375 debug_print("Password store configuration file version upgrade failed (%d), exiting\n", ret);
1376 #ifdef G_OS_WIN32
1377 win32_close_log();
1378 #endif
1379 exit(202);
1382 prefs_account_init();
1383 account_read_config_all();
1385 if (prefs_update_config_version_accounts() < 0) {
1386 debug_print("Accounts configuration file version upgrade failed, exiting\n");
1387 #ifdef G_OS_WIN32
1388 win32_close_log();
1389 #endif
1390 exit(201);
1393 #ifdef HAVE_LIBETPAN
1394 imap_main_init(prefs_common.skip_ssl_cert_check);
1395 imap_main_set_timeout(prefs_common.io_timeout_secs);
1396 nntp_main_init(prefs_common.skip_ssl_cert_check);
1397 #endif
1398 /* If we can't read a folder list or don't have accounts,
1399 * it means the configuration's not done. Either this is
1400 * a brand new install, a failed/refused migration,
1401 * or a failed config_version upgrade.
1403 if ((ret = folder_read_list()) < 0) {
1404 debug_print("Folderlist read failed (%d)\n", ret);
1405 prefs_destroy_cache();
1407 if (ret == -2) {
1408 /* config_version update failed in folder_read_list(). We
1409 * do not want to run the wizard, just exit. */
1410 debug_print("Folderlist version upgrade failed, exiting\n");
1411 #ifdef G_OS_WIN32
1412 win32_close_log();
1413 #endif
1414 exit(203);
1417 /* if run_wizard returns FALSE it's because it's
1418 * been cancelled. We can't do much but exit.
1419 * however, if the user was asked for a migration,
1420 * we remove the newly created directory so that
1421 * he's asked again for migration on next launch.*/
1422 if (!run_wizard(mainwin, TRUE)) {
1423 if (asked_for_migration)
1424 remove_dir_recursive(RC_DIR);
1425 #ifdef G_OS_WIN32
1426 win32_close_log();
1427 #endif
1428 exit(1);
1430 main_window_reflect_prefs_all_now();
1431 folder_write_list();
1432 never_ran = TRUE;
1435 if (!account_get_list()) {
1436 prefs_destroy_cache();
1437 if (!run_wizard(mainwin, FALSE)) {
1438 if (asked_for_migration)
1439 remove_dir_recursive(RC_DIR);
1440 #ifdef G_OS_WIN32
1441 win32_close_log();
1442 #endif
1443 exit(1);
1445 if(!account_get_list()) {
1446 exit_claws(mainwin);
1447 exit(1);
1449 never_ran = TRUE;
1453 toolbar_main_set_sensitive(mainwin);
1454 main_window_set_menu_sensitive(mainwin);
1456 /* if crashed, show window early so that the user
1457 * sees what's happening */
1458 if (claws_crashed()) {
1459 main_window_popup(mainwin);
1460 mainwin_shown = TRUE;
1463 account_set_missing_folder();
1464 folder_set_missing_folders();
1465 folderview_set(folderview);
1467 prefs_matcher_read_config();
1468 quicksearch_set_search_strings(mainwin->summaryview->quicksearch);
1470 /* make one all-folder processing before using claws */
1471 main_window_cursor_wait(mainwin);
1472 folder_func_to_all_folders(initial_processing, (gpointer *)mainwin);
1474 /* if claws crashed, rebuild caches */
1475 if (claws_crashed()) {
1476 GTK_EVENTS_FLUSH();
1477 debug_print("Claws Mail crashed, checking for new messages in local folders\n");
1478 folder_item_update_thaw();
1479 folderview_check_new(NULL);
1480 folder_clean_cache_memory_force();
1481 folder_item_update_freeze();
1483 /* make the crash-indicator file */
1484 if (str_write_to_file("foo", get_crashfile_name(), FALSE) < 0) {
1485 g_warning("can't create the crash-indicator file");
1488 inc_autocheck_timer_init(mainwin);
1490 /* ignore SIGPIPE signal for preventing sudden death of program */
1491 #ifdef G_OS_UNIX
1492 signal(SIGPIPE, SIG_IGN);
1493 #endif
1494 if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
1495 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
1497 if (cmd.online_mode == ONLINE_MODE_ONLINE) {
1498 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
1501 if (cmd.status_folders) {
1502 g_ptr_array_free(cmd.status_folders, TRUE);
1503 cmd.status_folders = NULL;
1505 if (cmd.status_full_folders) {
1506 g_ptr_array_free(cmd.status_full_folders, TRUE);
1507 cmd.status_full_folders = NULL;
1510 claws_register_idle_function(claws_gtk_idle);
1512 avatars_init();
1513 prefs_toolbar_init();
1515 num_folder_class = g_list_length(folder_get_list());
1517 plugin_load_all("GTK3");
1519 if (g_list_length(folder_get_list()) != num_folder_class) {
1520 debug_print("new folders loaded, reloading processing rules\n");
1521 prefs_matcher_read_config();
1524 if ((plug_list = plugin_get_unloaded_list()) != NULL) {
1525 GSList *cur;
1526 gchar *list = NULL;
1527 gint num_plugins = 0;
1528 for (cur = plug_list; cur; cur = cur->next) {
1529 Plugin *plugin = (Plugin *)cur->data;
1530 gchar *tmp = g_strdup_printf("%s\n%s",
1531 list? list:"",
1532 plugin_get_name(plugin));
1533 g_free(list);
1534 list = tmp;
1535 num_plugins++;
1537 main_window_cursor_normal(mainwin);
1538 main_window_popup(mainwin);
1539 mainwin_shown = TRUE;
1540 alertpanel_warning(ngettext(
1541 "The following plugin failed to load. "
1542 "Check the Plugins configuration "
1543 "for more information:\n%s",
1544 "The following plugins failed to load. "
1545 "Check the Plugins configuration "
1546 "for more information:\n%s",
1547 num_plugins),
1548 list);
1549 main_window_cursor_wait(mainwin);
1550 g_free(list);
1551 g_slist_free(plug_list);
1554 if (never_ran) {
1555 prefs_common_write_config();
1556 plugin_load_standard_plugins ();
1559 /* if not crashed, show window now */
1560 if (!mainwin_shown) {
1561 /* apart if something told not to show */
1562 if (show_at_startup)
1563 main_window_popup(mainwin);
1566 if (cmd.geometry != NULL) {
1567 if (!gtk_window_parse_geometry(GTK_WINDOW(mainwin->window), cmd.geometry))
1568 g_warning("failed to parse geometry '%s'", cmd.geometry);
1569 else {
1570 int width, height;
1572 if (sscanf(cmd.geometry, "%ux%u+", &width, &height) == 2)
1573 gtk_window_resize(GTK_WINDOW(mainwin->window), width, height);
1574 else
1575 g_warning("failed to parse geometry's width/height");
1579 if (!folder_have_mailbox()) {
1580 prefs_destroy_cache();
1581 main_window_cursor_normal(mainwin);
1582 if (folder_get_list() != NULL) {
1583 alertpanel_error(_("Claws Mail has detected a configured "
1584 "mailbox, but it is incomplete. It is "
1585 "possibly due to a failing IMAP account. Use "
1586 "\"Rebuild folder tree\" on the mailbox parent "
1587 "folder's context menu to try to fix it."));
1588 } else {
1589 alertpanel_error(_("Claws Mail has detected a configured "
1590 "mailbox, but could not load it. It is "
1591 "probably provided by an out-of-date "
1592 "external plugin. Please reinstall the "
1593 "plugin and try again."));
1594 exit_claws(mainwin);
1595 exit(1);
1599 static_mainwindow = mainwin;
1601 #ifdef HAVE_STARTUP_NOTIFICATION
1602 #ifdef GDK_WINDOWING_X11
1603 if (GDK_IS_X11_DISPLAY(gdk_display_get_default()))
1604 startup_notification_complete(FALSE);
1605 #endif
1606 #endif
1607 #ifdef HAVE_LIBSM
1608 sc_session_manager_connect(mainwin);
1609 #endif
1611 folder_item_update_thaw();
1612 folderview_thaw(mainwin->folderview);
1613 main_window_cursor_normal(mainwin);
1615 if (!cmd.target && prefs_common.goto_folder_on_startup &&
1616 folder_find_item_from_identifier(prefs_common.startup_folder) != NULL &&
1617 !claws_crashed()) {
1618 cmd.target = prefs_common.startup_folder;
1619 } else if (!cmd.target && prefs_common.goto_last_folder_on_startup &&
1620 folder_find_item_from_identifier(prefs_common.last_opened_folder) != NULL &&
1621 !claws_crashed()) {
1622 cmd.target = prefs_common.last_opened_folder;
1625 if (cmd.receive_all && !cmd.target) {
1626 start_done = FALSE;
1627 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(FALSE));
1628 } else if (prefs_common.chk_on_startup && !cmd.target) {
1629 start_done = FALSE;
1630 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(TRUE));
1631 } else if (cmd.receive && !cmd.target) {
1632 start_done = FALSE;
1633 g_timeout_add(1000, defer_check, NULL);
1635 folderview_grab_focus(folderview);
1637 if (cmd.compose) {
1638 open_compose_new(cmd.compose_mailto, cmd.attach_files);
1640 if (cmd.attach_files) {
1641 list_free_strings_full(cmd.attach_files);
1642 cmd.attach_files = NULL;
1644 if (cmd.subscribe) {
1645 folder_subscribe(cmd.subscribe_uri);
1648 if (cmd.send) {
1649 send_queue();
1652 if (cmd.target) {
1653 start_done = FALSE;
1654 g_timeout_add(500, defer_jump, (gpointer)cmd.target);
1657 prefs_destroy_cache();
1659 compose_reopen_exit_drafts();
1661 if (start_done) {
1662 sc_starting = FALSE;
1663 main_window_set_menu_sensitive(mainwin);
1664 toolbar_main_set_sensitive(mainwin);
1667 /* register the callback of unix domain socket input */
1668 lock_socket_tag = claws_input_add(lock_socket,
1669 G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_PRI,
1670 lock_socket_input_cb,
1671 mainwin, TRUE);
1673 END_TIMING();
1675 gtk_main();
1677 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1678 if(nm_proxy)
1679 g_object_unref(nm_proxy);
1680 #endif
1681 #ifdef HAVE_DBUS_GLIB
1682 uninstall_dbus_status_handler();
1683 if(connection)
1684 dbus_g_connection_unref(connection);
1685 #endif
1686 utils_free_regex();
1687 exit_claws(mainwin);
1689 return 0;
1692 static void save_all_caches(FolderItem *item, gpointer data)
1694 if (!item->cache) {
1695 return;
1698 if (item->opened) {
1699 folder_item_close(item);
1702 folder_item_free_cache(item, TRUE);
1705 static void exit_claws(MainWindow *mainwin)
1707 gchar *filename;
1708 gboolean have_connectivity;
1709 FolderItem *item;
1711 sc_exiting = TRUE;
1713 debug_print("shutting down\n");
1714 inc_autocheck_timer_remove();
1716 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1717 if (prefs_common.work_offline && went_offline_nm)
1718 prefs_common.work_offline = FALSE;
1719 #endif
1721 /* save prefs for opened folder */
1722 if((item = folderview_get_opened_item(mainwin->folderview)) != NULL) {
1723 summary_save_prefs_to_folderitem(
1724 mainwin->summaryview, item);
1725 if (prefs_common.last_opened_folder != NULL)
1726 g_free(prefs_common.last_opened_folder);
1727 prefs_common.last_opened_folder =
1728 !prefs_common.goto_last_folder_on_startup ? NULL :
1729 folder_item_get_identifier(item);
1732 /* save all state before exiting */
1733 folder_func_to_all_folders(save_all_caches, NULL);
1734 folder_write_list();
1736 main_window_get_size(mainwin);
1737 main_window_get_position(mainwin);
1739 prefs_common_write_config();
1740 account_write_config_all();
1741 passwd_store_write_config();
1742 #ifndef USE_ALT_ADDRBOOK
1743 addressbook_export_to_file();
1744 #endif
1745 filename = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
1746 gtk_accel_map_save(filename);
1747 g_free(filename);
1749 /* delete temporary files */
1750 remove_all_files(get_tmp_dir());
1751 remove_all_files(get_mime_tmp_dir());
1753 close_log_file(LOG_PROTOCOL);
1754 close_log_file(LOG_DEBUG_FILTERING);
1756 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1757 have_connectivity = networkmanager_is_online(NULL);
1758 #else
1759 have_connectivity = TRUE;
1760 #endif
1761 #ifdef HAVE_LIBETPAN
1762 imap_main_done(have_connectivity);
1763 nntp_main_done(have_connectivity);
1764 #endif
1765 /* delete crashfile */
1766 if (!cmd.crash)
1767 claws_unlink(get_crashfile_name());
1769 lock_socket_remove();
1771 #ifdef HAVE_LIBSM
1772 if (mainwin->smc_conn)
1773 SmcCloseConnection ((SmcConn)mainwin->smc_conn, 0, NULL);
1774 mainwin->smc_conn = NULL;
1775 #endif
1777 main_window_destroy_all();
1779 plugin_unload_all("GTK3");
1781 matcher_done();
1782 prefs_toolbar_done();
1783 avatars_done();
1785 #ifndef USE_ALT_ADDRBOOK
1786 addressbook_destroy();
1787 #endif
1788 prefs_themes_done();
1789 prefs_fonts_done();
1790 prefs_ext_prog_done();
1791 prefs_wrapping_done();
1792 prefs_compose_writing_done();
1793 prefs_msg_colors_done();
1794 prefs_image_viewer_done();
1795 image_viewer_done();
1796 prefs_quote_done();
1797 prefs_summaries_done();
1798 prefs_message_done();
1799 prefs_other_done();
1800 prefs_proxy_done();
1801 prefs_receive_done();
1802 prefs_logging_done();
1803 prefs_send_done();
1804 tags_write_tags();
1805 #ifdef USE_ENCHANT
1806 prefs_spelling_done();
1807 gtkaspell_checkers_quit();
1808 #endif
1809 plugin_unload_all("Common");
1810 #ifdef G_OS_WIN32
1811 win32_close_log();
1812 #endif
1813 claws_done();
1816 #define G_PRINT_EXIT(msg) \
1818 g_print(msg); \
1819 exit(1); \
1822 static void parse_cmd_compose_from_file(const gchar *fn, GString *body)
1824 GString *headers = g_string_new(NULL);
1825 gchar *to = NULL;
1826 gchar *h;
1827 gchar *v;
1828 gchar fb[BUFFSIZE];
1829 FILE *fp;
1830 gboolean isstdin;
1832 if (fn == NULL || *fn == '\0')
1833 G_PRINT_EXIT(_("Missing filename\n"));
1834 isstdin = (*fn == '-' && *(fn + 1) == '\0');
1835 if (isstdin)
1836 fp = stdin;
1837 else {
1838 fp = claws_fopen(fn, "r");
1839 if (!fp)
1840 G_PRINT_EXIT(_("Cannot open filename for reading\n"));
1843 while (claws_fgets(fb, sizeof(fb), fp)) {
1844 gchar *tmp;
1845 strretchomp(fb);
1846 if (*fb == '\0')
1847 break;
1848 h = fb;
1849 while (*h && *h != ':') { ++h; } /* search colon */
1850 if (*h == '\0')
1851 G_PRINT_EXIT(_("Malformed header\n"));
1852 v = h + 1;
1853 while (*v && *v == ' ') { ++v; } /* trim value start */
1854 *h = '\0';
1855 tmp = g_ascii_strdown(fb, -1); /* get header name */
1856 if (!strcmp(tmp, "to")) {
1857 if (to != NULL)
1858 G_PRINT_EXIT(_("Duplicated 'To:' header\n"));
1859 to = g_strdup(v);
1860 } else {
1861 g_string_append_c(headers, '&');
1862 g_string_append(headers, tmp);
1863 g_string_append_c(headers, '=');
1864 g_string_append_uri_escaped(headers, v, NULL, TRUE);
1866 g_free(tmp);
1868 if (to == NULL)
1869 G_PRINT_EXIT(_("Missing required 'To:' header\n"));
1870 g_string_append(body, to);
1871 g_free(to);
1872 g_string_append(body, "?body=");
1873 while (claws_fgets(fb, sizeof(fb), fp)) {
1874 g_string_append_uri_escaped(body, fb, NULL, TRUE);
1876 if (!isstdin)
1877 claws_fclose(fp);
1878 /* append the remaining headers */
1879 g_string_append(body, headers->str);
1880 g_string_free(headers, TRUE);
1883 #undef G_PRINT_EXIT
1885 static void parse_cmd_opt_error(char *errstr, char* optstr)
1887 gchar tmp[BUFSIZ];
1889 cm_return_if_fail(errstr != NULL);
1890 cm_return_if_fail(optstr != NULL);
1892 g_snprintf(tmp, sizeof(tmp), errstr, optstr);
1893 g_print(_("%s. Try -h or --help for usage.\n"), tmp);
1894 exit(1);
1897 static GString mailto; /* used to feed cmd.compose_mailto when --compose-from-file is used */
1899 static void parse_cmd_opt(int argc, char *argv[])
1901 AttachInfo *ainfo;
1902 gint i;
1904 for (i = 1; i < argc; i++) {
1905 if (!strcmp(argv[i], "--receive-all")) {
1906 cmd.receive_all = TRUE;
1907 } else if (!strcmp(argv[i], "--receive")) {
1908 cmd.receive = TRUE;
1909 } else if (!strcmp(argv[i], "--cancel-receiving")) {
1910 cmd.cancel_receiving = TRUE;
1911 } else if (!strcmp(argv[i], "--cancel-sending")) {
1912 cmd.cancel_sending = TRUE;
1913 } else if (!strcmp(argv[i], "--compose-from-file")) {
1914 if (i+1 < argc) {
1915 const gchar *p = argv[i+1];
1917 parse_cmd_compose_from_file(p, &mailto);
1918 cmd.compose = TRUE;
1919 cmd.compose_mailto = mailto.str;
1920 i++;
1921 } else {
1922 parse_cmd_opt_error(_("Missing file argument for option %s"), argv[i]);
1924 } else if (!strcmp(argv[i], "--compose")) {
1925 const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
1927 cmd.compose = TRUE;
1928 cmd.compose_mailto = NULL;
1929 if (p && *p != '\0' && *p != '-') {
1930 if (!STRNCMP(p, "mailto:")) {
1931 cmd.compose_mailto = p + 7;
1932 } else {
1933 cmd.compose_mailto = p;
1935 i++;
1937 } else if (!strcmp(argv[i], "--subscribe")) {
1938 if (i+1 < argc) {
1939 const gchar *p = argv[i+1];
1940 if (p && *p != '\0' && *p != '-') {
1941 cmd.subscribe = TRUE;
1942 cmd.subscribe_uri = p;
1943 } else {
1944 parse_cmd_opt_error(_("Missing or empty uri argument for option %s"), argv[i]);
1946 } else {
1947 parse_cmd_opt_error(_("Missing uri argument for option %s"), argv[i]);
1949 } else if (!strcmp(argv[i], "--attach") ||
1950 !strcmp(argv[i], "--insert")) {
1951 if (i+1 < argc) {
1952 const gchar *p = argv[i+1];
1953 gint ii = i;
1954 gchar *file = NULL;
1955 gboolean insert = !strcmp(argv[i], "--insert");
1957 while (p && *p != '\0' && *p != '-') {
1958 if ((file = g_filename_from_uri(p, NULL, NULL)) != NULL) {
1959 if (!is_file_exist(file)) {
1960 g_free(file);
1961 file = NULL;
1964 if (file == NULL && *p != G_DIR_SEPARATOR) {
1965 file = g_strconcat(claws_get_startup_dir(),
1966 G_DIR_SEPARATOR_S,
1967 p, NULL);
1968 } else if (file == NULL) {
1969 file = g_strdup(p);
1972 ainfo = g_new0(AttachInfo, 1);
1973 ainfo->file = file;
1974 ainfo->insert = insert;
1975 cmd.attach_files = g_list_append(cmd.attach_files, ainfo);
1976 ii++;
1977 p = (ii+1 < argc)?argv[ii+1]:NULL;
1979 if (ii==i) {
1980 parse_cmd_opt_error(_("Missing at least one non-empty file argument for option %s"), argv[i]);
1981 } else {
1982 i=ii;
1984 } else {
1985 parse_cmd_opt_error(_("Missing file argument for option %s"), argv[i]);
1987 } else if (!strcmp(argv[i], "--send")) {
1988 cmd.send = TRUE;
1989 } else if (!strcmp(argv[i], "--version-full") ||
1990 !strcmp(argv[i], "-V")) {
1991 g_print("Claws Mail version " VERSION_GIT_FULL "\n");
1992 main_dump_features_list(FALSE);
1993 exit(0);
1994 } else if (!strcmp(argv[i], "--version") ||
1995 !strcmp(argv[i], "-v")) {
1996 g_print("Claws Mail version " VERSION "\n");
1997 exit(0);
1998 } else if (!strcmp(argv[i], "--status-full")) {
1999 const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
2001 cmd.status_full = TRUE;
2002 while (p && *p != '\0' && *p != '-') {
2003 if (!cmd.status_full_folders) {
2004 cmd.status_full_folders =
2005 g_ptr_array_new();
2007 g_ptr_array_add(cmd.status_full_folders,
2008 g_strdup(p));
2009 i++;
2010 p = (i+1 < argc)?argv[i+1]:NULL;
2012 } else if (!strcmp(argv[i], "--status")) {
2013 const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
2015 cmd.status = TRUE;
2016 while (p && *p != '\0' && *p != '-') {
2017 if (!cmd.status_folders)
2018 cmd.status_folders = g_ptr_array_new();
2019 g_ptr_array_add(cmd.status_folders,
2020 g_strdup(p));
2021 i++;
2022 p = (i+1 < argc)?argv[i+1]:NULL;
2024 } else if (!strcmp(argv[i], "--search")) {
2025 if (i+3 < argc) { /* 3 first arguments are mandatory */
2026 const char* p;
2027 /* only set search parameters if they are valid */
2028 p = argv[i+1];
2029 cmd.search_folder = (p && *p != '\0' && *p != '-')?p:NULL;
2030 p = argv[i+2];
2031 cmd.search_type = (p && *p != '\0' && *p != '-')?p:NULL;
2032 p = argv[i+3];
2033 cmd.search_request = (p && *p != '\0' && *p != '-')?p:NULL;
2034 p = (i+4 < argc)?argv[i+4]:NULL;
2035 const char* rec = (p && *p != '\0' && *p != '-')?p:NULL;
2036 cmd.search_recursive = TRUE;
2037 if (rec) {
2038 i++;
2039 if (tolower(*rec)=='n' || tolower(*rec)=='f' || *rec=='0')
2040 cmd.search_recursive = FALSE;
2042 if (cmd.search_folder && cmd.search_type && cmd.search_request) {
2043 cmd.search = TRUE;
2044 i+=3;
2046 } else {
2047 switch (argc-i-1) {
2048 case 0:
2049 parse_cmd_opt_error(_("Missing folder, type and request arguments for option %s"), argv[i]);
2050 break;
2051 case 1:
2052 parse_cmd_opt_error(_("Missing type and request arguments for option %s"), argv[i]);
2053 break;
2054 case 2:
2055 parse_cmd_opt_error(_("Missing request argument for option %s"), argv[i]);
2058 } else if (!strcmp(argv[i], "--online")) {
2059 cmd.online_mode = ONLINE_MODE_ONLINE;
2060 } else if (!strcmp(argv[i], "--offline")) {
2061 cmd.online_mode = ONLINE_MODE_OFFLINE;
2062 } else if (!strcmp(argv[i], "--toggle-debug")) {
2063 cmd.debug = TRUE;
2064 } else if (!strcmp(argv[i], "--statistics")) {
2065 cmd.statistics = TRUE;
2066 } else if (!strcmp(argv[i], "--reset-statistics")) {
2067 cmd.reset_statistics = TRUE;
2068 } else if (!strcmp(argv[i], "--help") ||
2069 !strcmp(argv[i], "-h")) {
2070 gchar *base = g_path_get_basename(argv[0]);
2071 g_print(_("Usage: %s [OPTION]...\n"), base);
2073 g_print("%s\n", _(" --compose [address] open composition window"));
2074 g_print("%s\n", _(" --compose-from-file file\n"
2075 " open composition window with data from given file;\n"
2076 " use - as file name for reading from standard input;\n"
2077 " content format: headers first (To: required) until an\n"
2078 " empty line, then mail body until end of file."));
2079 g_print("%s\n", _(" --subscribe uri subscribe to the given URI if possible"));
2080 g_print("%s\n", _(" --attach file1 [file2]...\n"
2081 " open composition window with specified files\n"
2082 " attached"));
2083 g_print("%s\n", _(" --insert file1 [file2]...\n"
2084 " open composition window with specified files\n"
2085 " inserted"));
2086 g_print("%s\n", _(" --receive receive new messages"));
2087 g_print("%s\n", _(" --receive-all receive new messages of all accounts"));
2088 g_print("%s\n", _(" --cancel-receiving cancel receiving of messages"));
2089 g_print("%s\n", _(" --cancel-sending cancel sending of messages"));
2090 g_print("%s\n", _(" --search folder type request [recursive]\n"
2091 " searches mail\n"
2092 " folder ex.: \"#mh/Mailbox/inbox\" or \"Mail\"\n"
2093 " type: s[ubject],f[rom],t[o],e[xtended],m[ixed] or g: tag\n"
2094 " request: search string\n"
2095 " recursive: false if arg. starts with 0, n, N, f or F"));
2097 g_print("%s\n", _(" --send send all queued messages"));
2098 g_print("%s\n", _(" --status [folder]... show the total number of messages"));
2099 g_print("%s\n", _(" --status-full [folder]...\n"
2100 " show the status of each folder"));
2101 g_print("%s\n", _(" --statistics show session statistics"));
2102 g_print("%s\n", _(" --reset-statistics reset session statistics"));
2103 g_print("%s\n", _(" --select folder[/msg] jump to the specified folder/message\n"
2104 " folder is a folder id like 'folder/sub_folder', a file:// uri or an absolute path"));
2105 g_print("%s\n", _(" --online switch to online mode"));
2106 g_print("%s\n", _(" --offline switch to offline mode"));
2107 g_print("%s\n", _(" --exit --quit -q exit Claws Mail"));
2108 g_print("%s\n", _(" --debug -d debug mode"));
2109 g_print("%s\n", _(" --toggle-debug toggle debug mode"));
2110 g_print("%s\n", _(" --help -h display this help"));
2111 g_print("%s\n", _(" --version -v output version information"));
2112 g_print("%s\n", _(" --version-full -V output version and built-in features information"));
2113 g_print("%s\n", _(" --config-dir output configuration directory"));
2114 g_print("%s\n", _(" --alternate-config-dir directory\n"
2115 " use specified configuration directory"));
2116 g_print("%s\n", _(" --geometry -geometry [WxH][+X+Y]\n"
2117 " set geometry for main window"));
2119 g_free(base);
2120 exit(1);
2121 } else if (!strcmp(argv[i], "--crash")) {
2122 cmd.crash = TRUE;
2123 cmd.crash_params = g_strdup((i+1 < argc)?argv[i+1]:NULL);
2124 i++;
2125 } else if (!strcmp(argv[i], "--config-dir")) {
2126 g_print(RC_DIR "\n");
2127 exit(0);
2128 } else if (!strcmp(argv[i], "--alternate-config-dir")) {
2129 if (i+1 < argc) {
2130 set_rc_dir(argv[i+1]);
2131 i++;
2132 } else {
2133 parse_cmd_opt_error(_("Missing directory argument for option %s"), argv[i]);
2135 } else if (!strcmp(argv[i], "--geometry") ||
2136 !strcmp(argv[i], "-geometry")) {
2137 if (i+1 < argc) {
2138 cmd.geometry = argv[i+1];
2139 i++;
2140 } else {
2141 parse_cmd_opt_error(_("Missing geometry argument for option %s"), argv[i]);
2143 } else if (!strcmp(argv[i], "--exit") ||
2144 !strcmp(argv[i], "--quit") ||
2145 !strcmp(argv[i], "-q")) {
2146 cmd.exit = TRUE;
2147 } else if (!strcmp(argv[i], "--select")) {
2148 if (i+1 < argc) {
2149 cmd.target = argv[i+1];
2150 i++;
2151 } else {
2152 parse_cmd_opt_error(_("Missing folder argument for option %s"), argv[i]);
2154 } else if (i == 1 && argc == 2) {
2155 /* only one parameter. Do something intelligent about it */
2156 if ((strstr(argv[i], "@") || !STRNCMP(argv[i], "mailto:")) && !strstr(argv[i], "://")) {
2157 const gchar *p = argv[i];
2159 cmd.compose = TRUE;
2160 cmd.compose_mailto = NULL;
2161 if (p && *p != '\0' && *p != '-') {
2162 if (!STRNCMP(p, "mailto:")) {
2163 cmd.compose_mailto = p + 7;
2164 } else {
2165 cmd.compose_mailto = p;
2168 } else if (!STRNCMP(argv[i], "file://")) {
2169 cmd.target = argv[i];
2170 } else if (!STRNCMP(argv[i], "?attach=file://")) {
2171 /* Thunar support as per 3.3.0cvs19 */
2172 cmd.compose = TRUE;
2173 cmd.compose_mailto = argv[i];
2174 } else if (strstr(argv[i], "://")) {
2175 const gchar *p = argv[i];
2176 if (p && *p != '\0' && *p != '-') {
2177 cmd.subscribe = TRUE;
2178 cmd.subscribe_uri = p;
2180 } else if (!strcmp(argv[i], "--sync")) {
2181 /* gtk debug */
2182 } else if (is_dir_exist(argv[i]) || is_file_exist(argv[i])) {
2183 cmd.target = argv[i];
2184 } else {
2185 parse_cmd_opt_error(_("Unknown option %s"), argv[i]);
2187 } else {
2188 parse_cmd_opt_error(_("Unknown option %s"), argv[i]);
2192 if (cmd.attach_files && cmd.compose == FALSE) {
2193 cmd.compose = TRUE;
2194 cmd.compose_mailto = NULL;
2198 static void initial_processing(FolderItem *item, gpointer data)
2200 MainWindow *mainwin = (MainWindow *)data;
2201 gchar *buf;
2203 cm_return_if_fail(item);
2204 buf = g_strdup_printf(_("Processing (%s)..."),
2205 item->path
2206 ? item->path
2207 : _("top level folder"));
2208 g_free(buf);
2210 if (folder_item_parent(item) != NULL && item->prefs->enable_processing) {
2211 item->processing_pending = TRUE;
2212 folder_item_apply_processing(item);
2213 item->processing_pending = FALSE;
2216 STATUSBAR_POP(mainwin);
2219 static gboolean draft_all_messages(void)
2221 const GList *compose_list = NULL;
2223 compose_clear_exit_drafts();
2224 compose_list = compose_get_compose_list();
2225 while (compose_list != NULL) {
2226 Compose *c = (Compose*)compose_list->data;
2227 if (!compose_draft(c, COMPOSE_DRAFT_FOR_EXIT))
2228 return FALSE;
2229 compose_list = compose_get_compose_list();
2231 return TRUE;
2233 gboolean clean_quit(gpointer data)
2235 static gboolean firstrun = TRUE;
2237 if (!firstrun) {
2238 return FALSE;
2240 firstrun = FALSE;
2242 /*!< Good idea to have the main window stored in a
2243 * static variable so we can check that variable
2244 * to see if we're really allowed to do things
2245 * that actually the spawner is supposed to
2246 * do (like: sending mail, composing messages).
2247 * Because, really, if we're the spawnee, and
2248 * we touch GTK stuff, we're hosed. See the
2249 * next fixme. */
2251 /* FIXME: Use something else to signal that we're
2252 * in the original spawner, and not in a spawned
2253 * child. */
2254 if (!static_mainwindow) {
2255 return FALSE;
2258 draft_all_messages();
2259 emergency_exit = TRUE;
2260 exit_claws(static_mainwindow);
2261 exit(0);
2263 return FALSE;
2266 void app_will_exit(GtkWidget *widget, gpointer data)
2268 MainWindow *mainwin = data;
2270 if (gtk_main_level() == 0) {
2271 debug_print("not even started\n");
2272 return;
2274 if (sc_exiting == TRUE) {
2275 debug_print("exit pending\n");
2276 return;
2278 sc_exiting = TRUE;
2279 debug_print("exiting\n");
2280 if (compose_get_compose_list()) {
2281 if (!draft_all_messages()) {
2282 main_window_popup(mainwin);
2283 sc_exiting = FALSE;
2284 return;
2288 if (prefs_common.warn_queued_on_exit && procmsg_have_queued_mails_fast()) {
2289 if (alertpanel(_("Queued messages"),
2290 _("Some unsent messages are queued. Exit now?"),
2291 NULL, _("_Cancel"), NULL, _("_OK"), NULL, NULL,
2292 ALERTFOCUS_FIRST)
2293 != G_ALERTALTERNATE) {
2294 main_window_popup(mainwin);
2295 sc_exiting = FALSE;
2296 return;
2298 manage_window_focus_in(mainwin->window, NULL, NULL);
2301 sock_cleanup();
2302 #ifdef HAVE_VALGRIND
2303 if (RUNNING_ON_VALGRIND) {
2304 summary_clear_list(mainwin->summaryview);
2306 #endif
2307 if (folderview_get_selected_item(mainwin->folderview))
2308 folder_item_close(folderview_get_selected_item(mainwin->folderview));
2309 gtk_main_quit();
2312 gboolean claws_is_exiting(void)
2314 return sc_exiting;
2317 gboolean claws_is_starting(void)
2319 return sc_starting;
2322 #ifdef G_OS_UNIX
2324 * CLAWS: want this public so crash dialog can delete the
2325 * lock file too
2327 gchar *claws_get_socket_name(void)
2329 static gchar *filename = NULL;
2330 gchar *socket_dir = NULL;
2331 gchar md5sum[33];
2333 if (filename == NULL) {
2334 GStatBuf st;
2335 gint stat_ok;
2337 socket_dir = g_strdup_printf("%s%cclaws-mail",
2338 g_get_user_runtime_dir(), G_DIR_SEPARATOR);
2339 stat_ok = g_stat(socket_dir, &st);
2340 if (stat_ok < 0 && errno != ENOENT) {
2341 g_print("Error stat'ing socket_dir %s: %s\n",
2342 socket_dir, g_strerror(errno));
2343 } else if (stat_ok == 0 && S_ISSOCK(st.st_mode)) {
2344 /* old versions used a sock in $TMPDIR/claws-mail-$UID */
2345 debug_print("Using legacy socket %s\n", socket_dir);
2346 filename = g_strdup(socket_dir);
2347 g_free(socket_dir);
2348 return filename;
2351 if (!is_dir_exist(socket_dir) && make_dir(socket_dir) < 0) {
2352 g_print("Error creating socket_dir %s: %s\n",
2353 socket_dir, g_strerror(errno));
2356 md5_hex_digest(md5sum, get_rc_dir());
2358 filename = g_strdup_printf("%s%c%s", socket_dir, G_DIR_SEPARATOR,
2359 md5sum);
2360 g_free(socket_dir);
2361 debug_print("Using control socket %s\n", filename);
2364 return filename;
2366 #endif
2368 static gchar *get_crashfile_name(void)
2370 static gchar *filename = NULL;
2372 if (filename == NULL) {
2373 filename = g_strdup_printf("%s%cclaws-crashed",
2374 get_tmp_dir(), G_DIR_SEPARATOR);
2377 return filename;
2380 static gint prohibit_duplicate_launch(int *argc, char ***argv)
2382 gint sock;
2383 GList *curr;
2384 #ifdef G_OS_UNIX
2385 gchar *path;
2387 path = claws_get_socket_name();
2388 /* Try to connect to the control socket */
2389 sock = fd_connect_unix(path);
2391 if (sock < 0) {
2392 gint ret;
2393 #if HAVE_FLOCK
2394 gchar *socket_lock;
2395 gint lock_fd;
2396 /* If connect failed, no other process is running.
2397 * Unlink the potentially existing socket, then
2398 * open it. This has to be done locking a temporary
2399 * file to avoid the race condition where another
2400 * process could have created the socket just in
2401 * between.
2403 socket_lock = g_strconcat(path, ".lock",
2404 NULL);
2405 lock_fd = g_open(socket_lock, O_RDWR|O_CREAT, 0);
2406 if (lock_fd < 0) {
2407 debug_print("Couldn't open %s: %s (%d)\n", socket_lock,
2408 g_strerror(errno), errno);
2409 g_free(socket_lock);
2410 return -1;
2412 if (flock(lock_fd, LOCK_EX) < 0) {
2413 debug_print("Couldn't lock %s: %s (%d)\n", socket_lock,
2414 g_strerror(errno), errno);
2415 close(lock_fd);
2416 g_free(socket_lock);
2417 return -1;
2419 #endif
2421 claws_unlink(path);
2422 debug_print("Opening socket %s\n", path);
2423 ret = fd_open_unix(path);
2424 #if HAVE_FLOCK
2425 flock(lock_fd, LOCK_UN);
2426 close(lock_fd);
2427 claws_unlink(socket_lock);
2428 g_free(socket_lock);
2429 #endif
2430 return ret;
2432 #else
2433 HANDLE hmutex;
2435 hmutex = CreateMutexA(NULL, FALSE, "ClawsMail");
2436 if (!hmutex) {
2437 debug_print("cannot create Mutex\n");
2438 return -1;
2440 if (GetLastError() != ERROR_ALREADY_EXISTS) {
2441 sock = fd_open_inet(50216);
2442 if (sock < 0)
2443 return 0;
2444 return sock;
2447 sock = fd_connect_inet(50216);
2448 if (sock < 0)
2449 return -1;
2450 #endif
2451 /* remote command mode */
2453 debug_print("another Claws Mail instance is already running.\n");
2455 if (cmd.receive_all) {
2456 CM_FD_WRITE_ALL("receive_all\n");
2457 } else if (cmd.receive) {
2458 CM_FD_WRITE_ALL("receive\n");
2459 } else if (cmd.cancel_receiving) {
2460 CM_FD_WRITE_ALL("cancel_receiving\n");
2461 } else if (cmd.cancel_sending) {
2462 CM_FD_WRITE_ALL("cancel_sending\n");
2463 } else if (cmd.compose && cmd.attach_files) {
2464 gchar *str, *compose_str;
2466 if (cmd.compose_mailto) {
2467 compose_str = g_strdup_printf("compose_attach %s\n",
2468 cmd.compose_mailto);
2469 } else {
2470 compose_str = g_strdup("compose_attach\n");
2473 CM_FD_WRITE_ALL(compose_str);
2474 g_free(compose_str);
2476 for (curr = cmd.attach_files; curr != NULL ; curr = curr->next) {
2477 str = (gchar *) ((AttachInfo *)curr->data)->file;
2478 if (((AttachInfo *)curr->data)->insert)
2479 CM_FD_WRITE_ALL("insert ");
2480 else
2481 CM_FD_WRITE_ALL("attach ");
2482 CM_FD_WRITE_ALL(str);
2483 CM_FD_WRITE_ALL("\n");
2486 CM_FD_WRITE_ALL(".\n");
2487 } else if (cmd.compose) {
2488 gchar *compose_str;
2490 if (cmd.compose_mailto) {
2491 compose_str = g_strdup_printf
2492 ("compose %s\n", cmd.compose_mailto);
2493 } else {
2494 compose_str = g_strdup("compose\n");
2497 CM_FD_WRITE_ALL(compose_str);
2498 g_free(compose_str);
2499 } else if (cmd.subscribe) {
2500 gchar *str = g_strdup_printf("subscribe %s\n", cmd.subscribe_uri);
2501 CM_FD_WRITE_ALL(str);
2502 g_free(str);
2503 } else if (cmd.send) {
2504 CM_FD_WRITE_ALL("send\n");
2505 } else if (cmd.online_mode == ONLINE_MODE_ONLINE) {
2506 CM_FD_WRITE("online\n");
2507 } else if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
2508 CM_FD_WRITE("offline\n");
2509 } else if (cmd.debug) {
2510 CM_FD_WRITE("debug\n");
2511 } else if (cmd.status || cmd.status_full) {
2512 gchar buf[BUFFSIZE];
2513 gint i;
2514 const gchar *command;
2515 GPtrArray *folders;
2516 gchar *folder;
2518 command = cmd.status_full ? "status-full\n" : "status\n";
2519 folders = cmd.status_full ? cmd.status_full_folders :
2520 cmd.status_folders;
2522 CM_FD_WRITE_ALL(command);
2523 for (i = 0; folders && i < folders->len; ++i) {
2524 folder = g_ptr_array_index(folders, i);
2525 CM_FD_WRITE_ALL(folder);
2526 CM_FD_WRITE_ALL("\n");
2528 CM_FD_WRITE_ALL(".\n");
2529 for (;;) {
2530 fd_gets(sock, buf, sizeof(buf) - 1);
2531 buf[sizeof(buf) - 1] = '\0';
2532 if (!STRNCMP(buf, ".\n")) break;
2533 if (claws_fputs(buf, stdout) == EOF) {
2534 g_warning("writing to stdout failed");
2535 break;
2538 } else if (cmd.exit) {
2539 CM_FD_WRITE_ALL("exit\n");
2540 } else if (cmd.statistics) {
2541 gchar buf[BUFSIZ];
2542 CM_FD_WRITE("statistics\n");
2543 for (;;) {
2544 fd_gets(sock, buf, sizeof(buf) - 1);
2545 buf[sizeof(buf) - 1] = '\0';
2546 if (!STRNCMP(buf, ".\n")) break;
2547 if (claws_fputs(buf, stdout) == EOF) {
2548 g_warning("writing to stdout failed");
2549 break;
2552 } else if (cmd.reset_statistics) {
2553 CM_FD_WRITE("reset_statistics\n");
2554 } else if (cmd.target) {
2555 gchar *str = g_strdup_printf("select %s\n", cmd.target);
2556 CM_FD_WRITE_ALL(str);
2557 g_free(str);
2558 } else if (cmd.search) {
2559 gchar buf[BUFFSIZE];
2560 gchar *str =
2561 g_strdup_printf("search %s\n%s\n%s\n%c\n",
2562 cmd.search_folder, cmd.search_type, cmd.search_request,
2563 (cmd.search_recursive==TRUE)?'1':'0');
2564 CM_FD_WRITE_ALL(str);
2565 g_free(str);
2566 for (;;) {
2567 fd_gets(sock, buf, sizeof(buf) - 1);
2568 buf[sizeof(buf) - 1] = '\0';
2569 if (!STRNCMP(buf, ".\n")) break;
2570 if (claws_fputs(buf, stdout) == EOF) {
2571 g_warning("writing to stdout failed");
2572 break;
2575 } else {
2576 #ifdef G_OS_UNIX
2577 gchar buf[BUFSIZ];
2578 CM_FD_WRITE_ALL("get_display\n");
2579 memset(buf, 0, sizeof(buf));
2580 fd_gets(sock, buf, sizeof(buf) - 1);
2581 buf[sizeof(buf) - 1] = '\0';
2583 /* Try to connect to a display; if it is the same one as
2584 * the other Claws instance, then ask it to pop up. */
2585 int diff_display = 1;
2586 if (gtk_init_check(argc, argv)) {
2587 GdkDisplay *display = gdk_display_get_default();
2588 diff_display = g_strcmp0(buf, gdk_display_get_name(display));
2590 if (diff_display) {
2591 g_print("Claws Mail is already running on display %s.\n",
2592 buf);
2593 } else {
2594 g_print("Claws Mail is already running on this display (%s).\n",
2595 buf);
2596 fd_close(sock);
2597 sock = fd_connect_unix(path);
2598 CM_FD_WRITE_ALL("popup\n");
2600 #else
2601 CM_FD_WRITE_ALL("popup\n");
2602 #endif
2605 fd_close(sock);
2606 return -1;
2609 static gint lock_socket_remove(void)
2611 #ifdef G_OS_UNIX
2612 gchar *filename, *dirname;
2613 #endif
2614 if (lock_socket < 0) {
2615 return -1;
2618 if (lock_socket_tag > 0) {
2619 g_source_remove(lock_socket_tag);
2621 fd_close(lock_socket);
2623 #ifdef G_OS_UNIX
2624 filename = claws_get_socket_name();
2625 dirname = g_path_get_dirname(filename);
2626 if (claws_unlink(filename) < 0)
2627 FILE_OP_ERROR(filename, "claws_unlink");
2628 g_rmdir(dirname);
2629 g_free(dirname);
2630 #endif
2632 return 0;
2635 static GPtrArray *get_folder_item_list(gint sock)
2637 gchar buf[BUFFSIZE];
2638 FolderItem *item;
2639 GPtrArray *folders = NULL;
2641 for (;;) {
2642 fd_gets(sock, buf, sizeof(buf) - 1);
2643 buf[sizeof(buf) - 1] = '\0';
2644 if (!STRNCMP(buf, ".\n")) {
2645 break;
2647 strretchomp(buf);
2648 if (!folders) {
2649 folders = g_ptr_array_new();
2651 item = folder_find_item_from_identifier(buf);
2652 if (item) {
2653 g_ptr_array_add(folders, item);
2654 } else {
2655 g_warning("no such folder: %s", buf);
2659 return folders;
2662 static void lock_socket_input_cb(gpointer data,
2663 gint source,
2664 GIOCondition condition)
2666 MainWindow *mainwin = (MainWindow *)data;
2667 gint sock;
2668 gchar buf[BUFFSIZE];
2670 sock = fd_accept(source);
2671 if (sock < 0)
2672 return;
2674 fd_gets(sock, buf, sizeof(buf) - 1);
2675 buf[sizeof(buf) - 1] = '\0';
2677 if (!STRNCMP(buf, "popup")) {
2678 main_window_popup(mainwin);
2679 #ifdef G_OS_UNIX
2680 } else if (!STRNCMP(buf, "get_display")) {
2681 GdkDisplay* display = gtk_widget_get_display(mainwin->window);
2682 const gchar *display_name = gdk_display_get_name(display);
2683 CM_FD_WRITE_ALL(display_name);
2684 #endif
2685 } else if (!STRNCMP(buf, "receive_all")) {
2686 inc_all_account_mail(mainwin, FALSE, FALSE,
2687 prefs_common.newmail_notify_manu);
2688 } else if (!STRNCMP(buf, "receive")) {
2689 inc_mail(mainwin, prefs_common.newmail_notify_manu);
2690 } else if (!STRNCMP(buf, "cancel_receiving")) {
2691 inc_cancel_all();
2692 imap_cancel_all();
2693 } else if (!STRNCMP(buf, "cancel_sending")) {
2694 send_cancel();
2695 } else if (!STRNCMP(buf, "compose_attach")) {
2696 GList *files = NULL, *curr;
2697 AttachInfo *ainfo;
2698 gchar *mailto;
2700 mailto = g_strdup(buf + strlen("compose_attach") + 1);
2701 while (fd_gets(sock, buf, sizeof(buf) - 1) > 0) {
2702 buf[sizeof(buf) - 1] = '\0';
2703 strretchomp(buf);
2704 if (!g_strcmp0(buf, "."))
2705 break;
2707 ainfo = g_new0(AttachInfo, 1);
2708 ainfo->file = g_strdup(strstr(buf, " ") + 1);
2709 ainfo->insert = !STRNCMP(buf, "insert ");
2710 files = g_list_append(files, ainfo);
2712 open_compose_new(mailto, files);
2714 curr = g_list_first(files);
2715 while (curr != NULL) {
2716 ainfo = (AttachInfo *)curr->data;
2717 g_free(ainfo->file);
2718 g_free(ainfo);
2719 curr = curr->next;
2721 g_list_free(files);
2722 g_free(mailto);
2723 } else if (!STRNCMP(buf, "compose")) {
2724 open_compose_new(buf + strlen("compose") + 1, NULL);
2725 } else if (!STRNCMP(buf, "subscribe")) {
2726 main_window_popup(mainwin);
2727 folder_subscribe(buf + strlen("subscribe") + 1);
2728 } else if (!STRNCMP(buf, "send")) {
2729 send_queue();
2730 } else if (!STRNCMP(buf, "online")) {
2731 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
2732 } else if (!STRNCMP(buf, "offline")) {
2733 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
2734 } else if (!STRNCMP(buf, "debug")) {
2735 debug_set_mode(debug_get_mode() ? FALSE : TRUE);
2736 } else if (!STRNCMP(buf, "status-full") ||
2737 !STRNCMP(buf, "status")) {
2738 gchar *status;
2739 GPtrArray *folders;
2741 folders = get_folder_item_list(sock);
2742 status = folder_get_status
2743 (folders, !STRNCMP(buf, "status-full"));
2744 CM_FD_WRITE_ALL(status);
2745 CM_FD_WRITE_ALL(".\n");
2746 g_free(status);
2747 if (folders) g_ptr_array_free(folders, TRUE);
2748 } else if (!STRNCMP(buf, "statistics")) {
2749 gchar tmp[BUFSIZ];
2751 g_snprintf(tmp, sizeof(tmp), _("Session statistics\n"));
2752 CM_FD_WRITE_ALL(tmp);
2754 if (prefs_common.date_format) {
2755 struct tm *lt;
2756 gint len = 100;
2757 gchar date[len];
2759 lt = localtime(&session_stats.time_started);
2760 fast_strftime(date, len, prefs_common.date_format, lt);
2761 g_snprintf(tmp, sizeof(tmp), _("Started: %s\n"),
2762 lt ? date : ctime(&session_stats.time_started));
2763 } else
2764 g_snprintf(tmp, sizeof(tmp), _("Started: %s\n"),
2765 ctime(&session_stats.time_started));
2766 CM_FD_WRITE_ALL(tmp);
2768 CM_FD_WRITE_ALL("\n");
2770 g_snprintf(tmp, sizeof(tmp), _("Incoming traffic\n"));
2771 CM_FD_WRITE_ALL(tmp);
2773 g_snprintf(tmp, sizeof(tmp), _("Received messages: %d\n"),
2774 session_stats.received);
2775 CM_FD_WRITE_ALL(tmp);
2777 if (session_stats.spam > 0) {
2778 g_snprintf(tmp, sizeof(tmp), _("Spam messages: %d\n"),
2779 session_stats.spam);
2780 CM_FD_WRITE_ALL(tmp);
2783 CM_FD_WRITE_ALL("\n");
2785 g_snprintf(tmp, sizeof(tmp), _("Outgoing traffic\n"));
2786 CM_FD_WRITE_ALL(tmp);
2788 g_snprintf(tmp, sizeof(tmp), _("New/redirected messages: %d\n"),
2789 session_stats.sent);
2790 CM_FD_WRITE_ALL(tmp);
2792 g_snprintf(tmp, sizeof(tmp), _("Replied messages: %d\n"),
2793 session_stats.replied);
2794 CM_FD_WRITE_ALL(tmp);
2796 g_snprintf(tmp, sizeof(tmp), _("Forwarded messages: %d\n"),
2797 session_stats.forwarded);
2798 CM_FD_WRITE_ALL(tmp);
2800 g_snprintf(tmp, sizeof(tmp), _("Total outgoing messages: %d\n"),
2801 (session_stats.sent + session_stats.replied +
2802 session_stats.forwarded));
2803 CM_FD_WRITE_ALL(tmp);
2805 CM_FD_WRITE_ALL(".\n");
2806 } else if (!STRNCMP(buf, "reset_statistics")) {
2807 reset_statistics();
2808 } else if (!STRNCMP(buf, "select ")) {
2809 const gchar *target = buf+7;
2810 mainwindow_jump_to(target, TRUE);
2811 } else if (!STRNCMP(buf, "search ")) {
2812 FolderItem* folderItem = NULL;
2813 GSList *messages = NULL;
2814 gchar *folder_name = NULL;
2815 gchar *request = NULL;
2816 AdvancedSearch *search;
2817 gboolean recursive;
2818 AdvancedSearchType searchType = ADVANCED_SEARCH_EXTENDED;
2820 search = advsearch_new();
2822 folder_name = g_strdup(buf+7);
2823 strretchomp(folder_name);
2825 if (fd_gets(sock, buf, sizeof(buf) - 1) <= 0)
2826 goto search_exit;
2827 buf[sizeof(buf) - 1] = '\0';
2829 switch (toupper(buf[0])) {
2830 case 'S': searchType = ADVANCED_SEARCH_SUBJECT; break;
2831 case 'F': searchType = ADVANCED_SEARCH_FROM; break;
2832 case 'T': searchType = ADVANCED_SEARCH_TO; break;
2833 case 'M': searchType = ADVANCED_SEARCH_MIXED; break;
2834 case 'G': searchType = ADVANCED_SEARCH_TAG; break;
2835 case 'E': searchType = ADVANCED_SEARCH_EXTENDED; break;
2838 if (fd_gets(sock, buf, sizeof(buf) - 1) <= 0)
2839 goto search_exit;
2841 buf[sizeof(buf) - 1] = '\0';
2842 request = g_strdup(buf);
2843 strretchomp(request);
2845 recursive = TRUE;
2846 if (fd_gets(sock, buf, sizeof(buf) - 1) > 0)
2847 recursive = buf[0] != '0';
2849 buf[sizeof(buf) - 1] = '\0';
2851 debug_print("search: %s %i %s %i\n", folder_name, searchType, request, recursive);
2853 folderItem = folder_find_item_from_identifier(folder_name);
2855 if (folderItem == NULL) {
2856 debug_print("Unknown folder item : '%s', searching folder\n",folder_name);
2857 Folder* folder = folder_find_from_path(folder_name);
2858 if (folder != NULL)
2859 folderItem = FOLDER_ITEM(folder->node->data);
2860 else
2861 debug_print("Unknown folder: '%s'\n",folder_name);
2862 } else {
2863 debug_print("%s %s\n",folderItem->name, folderItem->path);
2866 if (folderItem != NULL) {
2867 advsearch_set(search, searchType, request);
2868 advsearch_search_msgs_in_folders(search, &messages, folderItem, recursive);
2869 } else {
2870 g_print("Folder '%s' not found.\n'", folder_name);
2873 GSList *cur;
2874 for (cur = messages; cur != NULL; cur = cur->next) {
2875 MsgInfo* msg = (MsgInfo *)cur->data;
2876 gchar *file = procmsg_get_message_file_path(msg);
2877 CM_FD_WRITE_ALL(file);
2878 CM_FD_WRITE_ALL("\n");
2879 g_free(file);
2881 CM_FD_WRITE_ALL(".\n");
2883 search_exit:
2884 g_free(folder_name);
2885 g_free(request);
2886 advsearch_free(search);
2887 if (messages != NULL)
2888 procmsg_msg_list_free(messages);
2889 } else if (!STRNCMP(buf, "exit")) {
2890 if (prefs_common.clean_on_exit && !prefs_common.ask_on_clean) {
2891 procmsg_empty_all_trash();
2893 app_will_exit(NULL, mainwin);
2895 fd_close(sock);
2899 static void open_compose_new(const gchar *address, GList *attach_files)
2901 gchar *addr = NULL;
2903 if (address) {
2904 Xstrdup_a(addr, address, return);
2905 g_strstrip(addr);
2908 compose_new(NULL, addr, attach_files);
2911 static void send_queue(void)
2913 GList *list;
2914 gchar *errstr = NULL;
2915 gboolean error = FALSE;
2916 for (list = folder_get_list(); list != NULL; list = list->next) {
2917 Folder *folder = list->data;
2919 if (folder->queue) {
2920 gint res = procmsg_send_queue
2921 (folder->queue, prefs_common.savemsg,
2922 &errstr);
2924 if (res) {
2925 folder_item_scan(folder->queue);
2928 if (res < 0)
2929 error = TRUE;
2932 if (errstr) {
2933 alertpanel_error_log(_("Some errors occurred "
2934 "while sending queued messages:\n%s"), errstr);
2935 g_free(errstr);
2936 } else if (error) {
2937 alertpanel_error_log("Some errors occurred "
2938 "while sending queued messages.");
2942 #ifndef G_OS_WIN32
2943 static void quit_signal_handler(int sig)
2945 debug_print("Quitting on signal %d\n", sig);
2947 g_timeout_add(0, clean_quit, NULL);
2949 #endif
2951 static void install_basic_sighandlers()
2953 #ifndef G_OS_WIN32
2954 sigset_t mask;
2955 struct sigaction act;
2957 sigemptyset(&mask);
2959 #ifdef SIGTERM
2960 sigaddset(&mask, SIGTERM);
2961 #endif
2962 #ifdef SIGINT
2963 sigaddset(&mask, SIGINT);
2964 #endif
2965 #ifdef SIGHUP
2966 sigaddset(&mask, SIGHUP);
2967 #endif
2969 act.sa_handler = quit_signal_handler;
2970 act.sa_mask = mask;
2971 act.sa_flags = 0;
2973 #ifdef SIGTERM
2974 sigaction(SIGTERM, &act, 0);
2975 #endif
2976 #ifdef SIGINT
2977 sigaction(SIGINT, &act, 0);
2978 #endif
2979 #ifdef SIGHUP
2980 sigaction(SIGHUP, &act, 0);
2981 #endif
2983 sigprocmask(SIG_UNBLOCK, &mask, 0);
2984 #endif /* !G_OS_WIN32 */
2987 #ifdef HAVE_NETWORKMANAGER_SUPPORT
2988 static void networkmanager_state_change_cb(DBusGProxy *proxy, gchar *dev,
2989 gpointer data)
2991 MainWindow *mainWin;
2993 mainWin = NULL;
2994 if (static_mainwindow)
2995 mainWin = static_mainwindow;
2996 else if (data)
2997 mainWin = (MainWindow*)data;
2999 if (!prefs_common.use_networkmanager)
3000 return;
3002 if (mainWin) {
3003 GError *error = NULL;
3004 gboolean online;
3006 online = networkmanager_is_online(&error);
3007 if(!error) {
3008 if(online && went_offline_nm) {
3009 went_offline_nm = FALSE;
3010 main_window_toggle_work_offline(mainWin, FALSE, FALSE);
3011 debug_print("NetworkManager: Went online\n");
3012 log_message(LOG_PROTOCOL, _("NetworkManager: network is online.\n"));
3014 else if(!online) {
3015 went_offline_nm = TRUE;
3016 main_window_toggle_work_offline(mainWin, TRUE, FALSE);
3017 debug_print("NetworkManager: Went offline\n");
3018 log_message(LOG_PROTOCOL, _("NetworkManager: network is offline.\n"));
3021 else {
3022 debug_print("Failed to get online information from NetworkManager: %s\n",
3023 error->message);
3024 g_error_free(error);
3027 else
3028 debug_print("NetworkManager: Cannot change connection state because "
3029 "main window does not exist\n");
3032 /* Returns true (and sets error appropriately, if given) in case of error */
3033 gboolean networkmanager_is_online(GError **error)
3035 DBusGConnection *connection;
3036 DBusGProxy *proxy;
3037 GError *tmp_error = NULL;
3038 gboolean retVal;
3039 guint32 state;
3041 if (!prefs_common.use_networkmanager)
3042 return TRUE;
3044 tmp_error = NULL;
3045 proxy = NULL;
3046 connection = dbus_g_bus_get(DBUS_BUS_SYSTEM, &tmp_error);
3048 if(!connection) {
3049 /* If calling code doesn't do error checking, at least print some debug */
3050 if((error == NULL) || (*error == NULL))
3051 debug_print("Failed to open connection to system bus: %s\n",
3052 tmp_error->message);
3053 g_propagate_error(error, tmp_error);
3054 return TRUE;
3057 proxy = dbus_g_proxy_new_for_name(connection,
3058 "org.freedesktop.NetworkManager",
3059 "/org/freedesktop/NetworkManager",
3060 "org.freedesktop.NetworkManager");
3062 retVal = dbus_g_proxy_call(proxy,"state",&tmp_error, G_TYPE_INVALID,
3063 G_TYPE_UINT, &state, G_TYPE_INVALID);
3065 if(proxy)
3066 g_object_unref(proxy);
3067 if(connection)
3068 dbus_g_connection_unref(connection);
3070 if(!retVal) {
3071 /* If calling code doesn't do error checking, at least print some debug */
3072 if((error == NULL) || (*error == NULL))
3073 debug_print("Failed to get state info from NetworkManager: %s\n",
3074 tmp_error->message);
3075 g_propagate_error(error, tmp_error);
3076 return TRUE;
3078 return (state == NM_STATE_CONNECTED_LOCAL ||
3079 state == NM_STATE_CONNECTED_SITE ||
3080 state == NM_STATE_CONNECTED_GLOBAL ||
3081 state == NM_STATE_UNKNOWN);
3083 #endif