prevent claws-mail logo from being themed
[claws.git] / src / main.c
blobf844abb9d5a4daae4afad626600e01c0dd380396
1 /*
2 * Claws Mail -- a GTK based, lightweight, and fast e-mail client
3 * Copyright (C) 1999-2022 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 # define SN_API_NOT_YET_FROZEN
55 # include <libsn/sn-launchee.h>
56 # include <gdk/gdkx.h>
57 #endif
59 #ifdef HAVE_DBUS_GLIB
60 #include <dbus/dbus-glib.h>
61 #endif
62 #ifdef HAVE_NETWORKMANAGER_SUPPORT
63 #include <NetworkManager.h>
64 #endif
65 #ifdef HAVE_VALGRIND
66 #include <valgrind.h>
67 #endif
68 #ifdef HAVE_SVG
69 #include <librsvg/rsvg.h>
70 #endif
72 #include "claws.h"
73 #include "main.h"
74 #include "mainwindow.h"
75 #include "folderview.h"
76 #include "image_viewer.h"
77 #include "summaryview.h"
78 #include "prefs_common.h"
79 #include "prefs_account.h"
80 #include "prefs_actions.h"
81 #include "prefs_ext_prog.h"
82 #include "prefs_fonts.h"
83 #include "prefs_image_viewer.h"
84 #include "prefs_message.h"
85 #include "prefs_migration.h"
86 #include "prefs_receive.h"
87 #include "prefs_msg_colors.h"
88 #include "prefs_quote.h"
89 #include "prefs_spelling.h"
90 #include "prefs_summaries.h"
91 #include "prefs_themes.h"
92 #include "prefs_other.h"
93 #include "prefs_proxy.h"
94 #include "prefs_logging.h"
95 #include "prefs_send.h"
96 #include "prefs_wrapping.h"
97 #include "prefs_compose_writing.h"
98 #include "prefs_display_header.h"
99 #include "account.h"
100 #include "procmsg.h"
101 #include "inc.h"
102 #include "imap.h"
103 #include "send_message.h"
104 #include "md5.h"
105 #include "import.h"
106 #include "manage_window.h"
107 #include "alertpanel.h"
108 #include "statusbar.h"
109 #ifndef USE_ALT_ADDRBOOK
110 #include "addressbook.h"
111 #else
112 #include "addressbook-dbus.h"
113 #endif
114 #include "compose.h"
115 #include "folder.h"
116 #include "folder_item_prefs.h"
117 #include "setup.h"
118 #include "utils.h"
119 #include "gtkutils.h"
120 #include "socket.h"
121 #include "log.h"
122 #include "prefs_toolbar.h"
123 #include "plugin.h"
124 #include "mh_gtk.h"
125 #include "imap_gtk.h"
126 #include "news_gtk.h"
127 #include "matcher.h"
128 #include "tags.h"
129 #include "hooks.h"
130 #include "menu.h"
131 #include "quicksearch.h"
132 #include "advsearch.h"
133 #include "avatars.h"
134 #include "passwordstore.h"
135 #include "file-utils.h"
137 #ifdef HAVE_LIBETPAN
138 #include "imap-thread.h"
139 #include "nntp-thread.h"
140 #endif
141 #include "stock_pixmap.h"
142 #ifdef USE_GNUTLS
143 # include "ssl.h"
144 #endif
146 #include "version.h"
148 #include "crash.h"
150 #include "timing.h"
152 #ifdef HAVE_NETWORKMANAGER_SUPPORT
153 /* Went offline due to NetworkManager */
154 static gboolean went_offline_nm;
155 #endif
158 #ifdef HAVE_DBUS_GLIB
159 static DBusGProxy *awn_proxy = NULL;
160 #endif
162 gchar *prog_version;
163 #if (defined HAVE_LIBSM || defined CRASH_DIALOG)
164 gchar *argv0;
165 #endif
167 #ifdef HAVE_STARTUP_NOTIFICATION
168 static SnLauncheeContext *sn_context = NULL;
169 static SnDisplay *sn_display = NULL;
170 #endif
172 static gint lock_socket = -1;
173 static gint lock_socket_tag = 0;
174 #ifdef G_OS_UNIX
175 static gchar *x_display = NULL;
176 #endif
177 typedef enum
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 (void);
222 static gchar * get_crashfile_name (void);
223 static gint lock_socket_remove (void);
224 static void lock_socket_input_cb (gpointer data,
225 gint source,
226 GIOCondition condition);
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 #ifndef G_OS_WIN32
234 static void quit_signal_handler (int sig);
235 #endif
236 static void install_basic_sighandlers (void);
237 #if (defined linux && defined SIGIO)
238 static void install_memory_sighandler (void);
239 #endif
240 static void exit_claws (MainWindow *mainwin);
242 #ifdef HAVE_NETWORKMANAGER_SUPPORT
243 static void networkmanager_state_change_cb(DBusGProxy *proxy, gchar *dev,
244 gpointer data);
245 #endif
247 #define MAKE_DIR_IF_NOT_EXIST(dir) \
249 if (!is_dir_exist(dir)) { \
250 if (is_file_exist(dir)) { \
251 alertpanel_warning \
252 (_("File '%s' already exists.\n" \
253 "Can't create folder."), \
254 dir); \
255 return 1; \
257 if (make_dir(dir) < 0) \
258 return 1; \
262 #define STRNCMP(S1, S2) (strncmp((S1), (S2), sizeof((S2)) - 1))
264 #define CM_FD_WRITE(S) fd_write(sock, (S), strlen((S)))
265 #define CM_FD_WRITE_ALL(S) fd_write_all(sock, (S), strlen((S)))
267 static MainWindow *static_mainwindow;
269 static gboolean emergency_exit = FALSE;
271 #ifdef HAVE_STARTUP_NOTIFICATION
272 static void sn_error_trap_push(SnDisplay *display, Display *xdisplay)
274 gdk_error_trap_push();
277 static void sn_error_trap_pop(SnDisplay *display, Display *xdisplay)
279 gdk_error_trap_pop();
282 static void startup_notification_complete(gboolean with_window)
284 Display *xdisplay;
285 GtkWidget *hack = NULL;
287 if (with_window) {
288 /* this is needed to make the startup notification leave,
289 * if we have been launched from a menu.
290 * We have to display a window, so let it be very little */
291 hack = gtk_window_new(GTK_WINDOW_POPUP);
292 gtk_window_move(GTK_WINDOW(hack), 0, 0);
293 gtk_widget_set_size_request(hack, 1, 1);
294 gtk_widget_show(hack);
297 xdisplay = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
298 sn_display = sn_display_new(xdisplay,
299 sn_error_trap_push,
300 sn_error_trap_pop);
301 sn_context = sn_launchee_context_new_from_environment(sn_display,
302 DefaultScreen(xdisplay));
304 if (sn_context != NULL) {
305 sn_launchee_context_complete(sn_context);
306 sn_launchee_context_unref(sn_context);
307 sn_display_unref(sn_display);
309 if (with_window) {
310 gtk_widget_destroy(hack);
313 #endif /* HAVE_STARTUP_NOTIFICATION */
315 static void claws_gtk_idle(void)
317 while(gtk_events_pending()) {
318 gtk_main_iteration();
320 g_usleep(50000);
323 static gboolean sc_starting = FALSE;
325 static gboolean defer_check_all(void *data)
327 gboolean autochk = GPOINTER_TO_INT(data);
329 if (!sc_starting) {
330 inc_all_account_mail(static_mainwindow, autochk, FALSE,
331 prefs_common.newmail_notify_manu);
333 } else {
334 inc_all_account_mail(static_mainwindow, FALSE,
335 prefs_common.chk_on_startup,
336 prefs_common.newmail_notify_manu);
337 sc_starting = FALSE;
338 main_window_set_menu_sensitive(static_mainwindow);
339 toolbar_main_set_sensitive(static_mainwindow);
341 return FALSE;
344 static gboolean defer_check(void *data)
346 inc_mail(static_mainwindow, prefs_common.newmail_notify_manu);
348 if (sc_starting) {
349 sc_starting = FALSE;
350 main_window_set_menu_sensitive(static_mainwindow);
351 toolbar_main_set_sensitive(static_mainwindow);
353 return FALSE;
356 static gboolean defer_jump(void *data)
358 if (cmd.receive_all) {
359 defer_check_all(GINT_TO_POINTER(FALSE));
360 } else if (prefs_common.chk_on_startup) {
361 defer_check_all(GINT_TO_POINTER(TRUE));
362 } else if (cmd.receive) {
363 defer_check(NULL);
365 mainwindow_jump_to(data, FALSE);
366 if (sc_starting) {
367 sc_starting = FALSE;
368 main_window_set_menu_sensitive(static_mainwindow);
369 toolbar_main_set_sensitive(static_mainwindow);
371 return FALSE;
374 static void chk_update_val(GtkWidget *widget, gpointer data)
376 gboolean *val = (gboolean *)data;
377 *val = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget));
380 static gboolean migrate_old_config(const gchar *old_cfg_dir, const gchar *new_cfg_dir, const gchar *oldversion)
382 gchar *message = g_strdup_printf(_("Configuration for %s found.\n"
383 "Do you want to migrate this configuration?"), oldversion);
385 if (!strcmp(oldversion, "Sylpheed")) {
386 gchar *message2 = g_strdup_printf(_("\n\nYour Sylpheed filtering rules can be converted by a\n"
387 "script available at %s."), TOOLS_URI);
388 gchar *tmp = g_strconcat(message, message2, NULL);
389 g_free(message2);
390 g_free(message);
391 message = tmp;
394 gint r = 0;
395 GtkWidget *window = NULL;
396 GtkWidget *keep_backup_chk;
397 gboolean backup = TRUE;
399 keep_backup_chk = gtk_check_button_new_with_label (_("Keep old configuration"));
400 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(keep_backup_chk), TRUE);
401 CLAWS_SET_TIP(keep_backup_chk,
402 _("Keeping a backup will allow you to go back to an "
403 "older version, but may take a while if you have "
404 "cached IMAP or News data, and will take some extra "
405 "room on your disk."));
407 g_signal_connect(G_OBJECT(keep_backup_chk), "toggled",
408 G_CALLBACK(chk_update_val), &backup);
410 if (alertpanel_full(_("Migration of configuration"), message,
411 GTK_STOCK_NO, GTK_STOCK_YES, NULL, ALERTFOCUS_SECOND, FALSE,
412 keep_backup_chk, ALERT_QUESTION) != G_ALERTALTERNATE) {
413 return FALSE;
416 /* we can either do a fast migration requiring not any extra disk
417 * space, or a slow one that copies the old configuration and leaves
418 * it in place. */
419 if (backup) {
420 backup_mode:
421 window = label_window_create(_("Copying configuration... This may take a while..."));
422 GTK_EVENTS_FLUSH();
424 r = copy_dir(old_cfg_dir, new_cfg_dir);
425 label_window_destroy(window);
427 /* if copy failed, we'll remove the partially copied
428 * new directory */
429 if (r != 0) {
430 alertpanel_error(_("Migration failed!"));
431 remove_dir_recursive(new_cfg_dir);
432 } else {
433 if (!backup) {
434 /* fast mode failed, but we don't want backup */
435 remove_dir_recursive(old_cfg_dir);
438 } else {
439 window = label_window_create(_("Migrating configuration..."));
440 GTK_EVENTS_FLUSH();
442 r = g_rename(old_cfg_dir, new_cfg_dir);
443 label_window_destroy(window);
445 /* if g_rename failed, we'll try to copy */
446 if (r != 0) {
447 FILE_OP_ERROR(new_cfg_dir, "g_rename");
448 debug_print("rename failed, trying copy\n");
449 goto backup_mode;
452 return (r == 0);
455 static int migrate_common_rc(const gchar *old_rc, const gchar *new_rc)
457 FILE *oldfp, *newfp;
458 gchar *plugin_path, *old_plugin_path, *new_plugin_path;
459 gchar buf[BUFFSIZE];
460 gboolean err = FALSE;
462 oldfp = claws_fopen(old_rc, "r");
463 if (!oldfp)
464 return -1;
465 newfp = claws_fopen(new_rc, "w");
466 if (!newfp) {
467 claws_fclose(oldfp);
468 return -1;
471 plugin_path = g_strdup(get_plugin_dir());
472 new_plugin_path = g_strdup(plugin_path);
474 if (strstr(plugin_path, "/claws-mail/")) {
475 gchar *end = g_strdup(strstr(plugin_path, "/claws-mail/")+strlen("/claws-mail/"));
476 *(strstr(plugin_path, "/claws-mail/")) = '\0';
477 old_plugin_path = g_strconcat(plugin_path, "/sylpheed-claws/", end, NULL);
478 g_free(end);
479 } else {
480 old_plugin_path = g_strdup(new_plugin_path);
482 debug_print("replacing %s with %s\n", old_plugin_path, new_plugin_path);
483 while (claws_fgets(buf, sizeof(buf), oldfp)) {
484 if (STRNCMP(buf, old_plugin_path)) {
485 err |= (claws_fputs(buf, newfp) == EOF);
486 } else {
487 debug_print("->replacing %s\n", buf);
488 debug_print(" with %s%s\n", new_plugin_path, buf+strlen(old_plugin_path));
489 err |= (claws_fputs(new_plugin_path, newfp) == EOF);
490 err |= (claws_fputs(buf+strlen(old_plugin_path), newfp) == EOF);
493 g_free(plugin_path);
494 g_free(new_plugin_path);
495 g_free(old_plugin_path);
496 claws_fclose(oldfp);
497 if (claws_safe_fclose(newfp) == EOF)
498 err = TRUE;
500 return (err ? -1:0);
503 #ifdef HAVE_LIBSM
504 static void
505 sc_client_set_value (MainWindow *mainwin,
506 gchar *name,
507 char *type,
508 int num_vals,
509 SmPropValue *vals)
511 SmProp *proplist[1];
512 SmProp prop;
514 prop.name = name;
515 prop.type = type;
516 prop.num_vals = num_vals;
517 prop.vals = vals;
519 proplist[0]= &prop;
520 if (mainwin->smc_conn)
521 SmcSetProperties ((SmcConn) mainwin->smc_conn, 1, proplist);
524 static void sc_die_callback (SmcConn smc_conn, SmPointer client_data)
526 clean_quit(NULL);
529 static void sc_save_complete_callback(SmcConn smc_conn, SmPointer client_data)
533 static void sc_shutdown_cancelled_callback (SmcConn smc_conn, SmPointer client_data)
535 MainWindow *mainwin = (MainWindow *)client_data;
536 if (mainwin->smc_conn)
537 SmcSaveYourselfDone ((SmcConn) mainwin->smc_conn, TRUE);
540 static void sc_save_yourself_callback (SmcConn smc_conn,
541 SmPointer client_data,
542 int save_style,
543 gboolean shutdown,
544 int interact_style,
545 gboolean fast) {
547 MainWindow *mainwin = (MainWindow *)client_data;
548 if (mainwin->smc_conn)
549 SmcSaveYourselfDone ((SmcConn) mainwin->smc_conn, TRUE);
552 static IceIOErrorHandler sc_ice_installed_handler;
554 static void sc_ice_io_error_handler (IceConn connection)
556 if (sc_ice_installed_handler)
557 (*sc_ice_installed_handler) (connection);
559 static gboolean sc_process_ice_messages (GIOChannel *source,
560 GIOCondition condition,
561 gpointer data)
563 IceConn connection = (IceConn) data;
564 IceProcessMessagesStatus status;
566 status = IceProcessMessages (connection, NULL, NULL);
568 if (status == IceProcessMessagesIOError) {
569 IcePointer context = IceGetConnectionContext (connection);
571 if (context && G_IS_OBJECT(context)) {
572 guint disconnect_id = g_signal_lookup ("disconnect", G_OBJECT_TYPE (context));
574 if (disconnect_id > 0)
575 g_signal_emit (context, disconnect_id, 0);
576 } else {
577 IceSetShutdownNegotiation (connection, False);
578 IceCloseConnection (connection);
582 return TRUE;
585 static void new_ice_connection (IceConn connection, IcePointer client_data, Bool opening,
586 IcePointer *watch_data)
588 guint input_id;
590 if (opening) {
591 GIOChannel *channel;
592 /* Make sure we don't pass on these file descriptors to any
593 exec'ed children */
594 fcntl(IceConnectionNumber(connection),F_SETFD,
595 fcntl(IceConnectionNumber(connection),F_GETFD,0) | FD_CLOEXEC);
597 channel = g_io_channel_unix_new (IceConnectionNumber (connection));
598 input_id = g_io_add_watch (channel,
599 G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_PRI,
600 sc_process_ice_messages,
601 connection);
602 g_io_channel_unref (channel);
604 *watch_data = (IcePointer) GUINT_TO_POINTER (input_id);
605 } else {
606 input_id = GPOINTER_TO_UINT ((gpointer) *watch_data);
607 g_source_remove (input_id);
611 static void sc_session_manager_connect(MainWindow *mainwin)
613 static gboolean connected = FALSE;
614 SmcCallbacks callbacks;
615 gchar *client_id;
616 IceIOErrorHandler default_handler;
618 if (connected)
619 return;
620 connected = TRUE;
623 sc_ice_installed_handler = IceSetIOErrorHandler (NULL);
624 default_handler = IceSetIOErrorHandler (sc_ice_io_error_handler);
626 if (sc_ice_installed_handler == default_handler)
627 sc_ice_installed_handler = NULL;
629 IceAddConnectionWatch (new_ice_connection, NULL);
632 callbacks.save_yourself.callback = sc_save_yourself_callback;
633 callbacks.die.callback = sc_die_callback;
634 callbacks.save_complete.callback = sc_save_complete_callback;
635 callbacks.shutdown_cancelled.callback = sc_shutdown_cancelled_callback;
637 callbacks.save_yourself.client_data =
638 callbacks.die.client_data =
639 callbacks.save_complete.client_data =
640 callbacks.shutdown_cancelled.client_data = (SmPointer) mainwin;
641 if (g_getenv ("SESSION_MANAGER")) {
642 gchar error_string_ret[256] = "";
644 mainwin->smc_conn = (gpointer)
645 SmcOpenConnection (NULL, mainwin,
646 SmProtoMajor, SmProtoMinor,
647 SmcSaveYourselfProcMask | SmcDieProcMask |
648 SmcSaveCompleteProcMask |
649 SmcShutdownCancelledProcMask,
650 &callbacks,
651 NULL, &client_id,
652 256, error_string_ret);
654 /* From https://www.x.org/releases/X11R7.7/doc/libSM/SMlib.txt:
655 * If SmcOpenConnection succeeds, it returns an opaque connection
656 * pointer of type SmcConn and the client_id_ret argument contains
657 * the client ID to be used for this session. The client_id_ret
658 * should be freed with a call to free when no longer needed. On
659 * failure, SmcOpenConnection returns NULL, and the reason for
660 * failure is returned in error_string_ret. */
661 if (mainwin->smc_conn != NULL)
662 g_free(client_id);
664 if (error_string_ret[0] || mainwin->smc_conn == NULL)
665 g_warning("while connecting to session manager: %s",
666 error_string_ret);
667 else {
668 SmPropValue *vals;
669 vals = g_new (SmPropValue, 1);
670 vals[0].length = strlen(argv0);
671 vals[0].value = argv0;
672 sc_client_set_value (mainwin, SmCloneCommand, SmLISTofARRAY8, 1, vals);
673 sc_client_set_value (mainwin, SmRestartCommand, SmLISTofARRAY8, 1, vals);
674 sc_client_set_value (mainwin, SmProgram, SmARRAY8, 1, vals);
676 vals[0].length = strlen(g_get_user_name()?g_get_user_name():"");
677 vals[0].value = g_strdup(g_get_user_name()?g_get_user_name():"");
678 sc_client_set_value (mainwin, SmUserID, SmARRAY8, 1, vals);
680 g_free(vals[0].value);
681 g_free(vals);
685 #endif
687 static gboolean sc_exiting = FALSE;
688 static gboolean show_at_startup = TRUE;
689 static gboolean claws_crashed_bool = FALSE;
691 gboolean claws_crashed(void) {
692 return claws_crashed_bool;
695 void main_set_show_at_startup(gboolean show)
697 show_at_startup = show;
700 #ifdef G_OS_WIN32
701 static HANDLE win32_debug_log = NULL;
702 static guint win32_log_handler_app_id;
703 static guint win32_log_handler_glib_id;
704 static guint win32_log_handler_gtk_id;
706 static void win32_log_WriteFile(const gchar *string)
708 BOOL ret;
709 DWORD bytes_written;
711 ret = WriteFile(win32_debug_log, string, strlen(string), &bytes_written, NULL);
712 if (!ret) {
713 DWORD err = GetLastError();
714 gchar *tmp;
716 tmp = g_strdup_printf("Error: WriteFile in failed with error 0x%lx. Buffer contents:\n%s", err, string);
717 OutputDebugString(tmp);
718 g_free(tmp);
722 static void win32_print_stdout(const gchar *string)
724 if (win32_debug_log) {
725 win32_log_WriteFile(string);
729 GLogWriterOutput win32_log_writer(GLogLevelFlags log_level, const GLogField *fields, gsize n_fields, gpointer user_data)
731 gchar *formatted;
732 gchar *out;
734 g_return_val_if_fail(win32_debug_log != NULL, G_LOG_WRITER_UNHANDLED);
735 g_return_val_if_fail(fields != NULL, G_LOG_WRITER_UNHANDLED);
736 g_return_val_if_fail(n_fields > 0, G_LOG_WRITER_UNHANDLED);
738 formatted = g_log_writer_format_fields(log_level, fields, n_fields, FALSE);
739 out = g_strdup_printf("%s\n", formatted);
741 win32_log_WriteFile(out);
743 g_free(formatted);
744 g_free(out);
746 return G_LOG_WRITER_HANDLED;
749 static void win32_log(const gchar *log_domain, GLogLevelFlags log_level, const gchar* message, gpointer user_data)
751 gchar *out;
753 if (win32_debug_log) {
754 const gchar* type;
756 switch(log_level & G_LOG_LEVEL_MASK)
758 case G_LOG_LEVEL_ERROR:
759 type="error";
760 break;
761 case G_LOG_LEVEL_CRITICAL:
762 type="critical";
763 break;
764 case G_LOG_LEVEL_WARNING:
765 type="warning";
766 break;
767 case G_LOG_LEVEL_MESSAGE:
768 type="message";
769 break;
770 case G_LOG_LEVEL_INFO:
771 type="info";
772 break;
773 case G_LOG_LEVEL_DEBUG:
774 type="debug";
775 break;
776 default:
777 type="N/A";
780 if (log_domain)
781 out = g_strdup_printf("%s: %s: %s", log_domain, type, message);
782 else
783 out = g_strdup_printf("%s: %s", type, message);
785 win32_log_WriteFile(out);
787 g_free(out);
791 static void win32_open_log(void)
793 gchar *logfile = win32_debug_log_path();
794 gchar *oldlogfile = g_strconcat(logfile, ".bak", NULL);
796 if (is_file_exist(logfile)) {
797 if (rename_force(logfile, oldlogfile) < 0)
798 FILE_OP_ERROR(logfile, "rename");
801 win32_debug_log = CreateFile(logfile,
802 GENERIC_WRITE,
803 FILE_SHARE_READ,
804 NULL,
805 CREATE_NEW,
806 FILE_ATTRIBUTE_NORMAL,
807 NULL);
809 if (win32_debug_log == INVALID_HANDLE_VALUE) {
810 win32_debug_log = NULL;
813 g_free(logfile);
814 g_free(oldlogfile);
816 if (win32_debug_log) {
817 g_set_print_handler(win32_print_stdout);
818 g_set_printerr_handler(win32_print_stdout);
820 win32_log_handler_app_id = g_log_set_handler(NULL, G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
821 | G_LOG_FLAG_RECURSION, win32_log, NULL);
822 win32_log_handler_glib_id = g_log_set_handler("GLib", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
823 | G_LOG_FLAG_RECURSION, win32_log, NULL);
824 win32_log_handler_gtk_id = g_log_set_handler("Gtk", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
825 | G_LOG_FLAG_RECURSION, win32_log, NULL);
827 g_log_set_writer_func(&win32_log_writer, NULL, NULL);
831 static void win32_close_log(void)
833 if (win32_debug_log) {
834 g_log_remove_handler("", win32_log_handler_app_id);
835 g_log_remove_handler("GLib", win32_log_handler_glib_id);
836 g_log_remove_handler("Gtk", win32_log_handler_gtk_id);
837 CloseHandle(win32_debug_log);
838 win32_debug_log = NULL;
841 #endif
843 static void main_dump_features_list(gboolean show_debug_only)
844 /* display compiled-in features list */
846 if (show_debug_only && !debug_get_mode())
847 return;
849 if (show_debug_only)
850 debug_print("runtime GTK+ %d.%d.%d / GLib %d.%d.%d\n",
851 gtk_major_version, gtk_minor_version, gtk_micro_version,
852 glib_major_version, glib_minor_version, glib_micro_version);
853 else
854 g_print("runtime GTK+ %d.%d.%d / GLib %d.%d.%d\n",
855 gtk_major_version, gtk_minor_version, gtk_micro_version,
856 glib_major_version, glib_minor_version, glib_micro_version);
857 if (show_debug_only)
858 debug_print("buildtime GTK+ %d.%d.%d / GLib %d.%d.%d\n",
859 GTK_MAJOR_VERSION, GTK_MINOR_VERSION, GTK_MICRO_VERSION,
860 GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION);
861 else
862 g_print("buildtime GTK+ %d.%d.%d / GLib %d.%d.%d\n",
863 GTK_MAJOR_VERSION, GTK_MINOR_VERSION, GTK_MICRO_VERSION,
864 GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION);
866 if (show_debug_only)
867 debug_print("Compiled-in features:\n");
868 else
869 g_print("Compiled-in features:\n");
870 #if HAVE_LIBCOMPFACE
871 if (show_debug_only)
872 debug_print(" compface\n");
873 else
874 g_print(" compface\n");
875 #endif
876 #if USE_ENCHANT
877 if (show_debug_only)
878 debug_print(" Enchant\n");
879 else
880 g_print(" Enchant\n");
881 #endif
882 #if USE_GNUTLS
883 if (show_debug_only)
884 debug_print(" GnuTLS\n");
885 else
886 g_print(" GnuTLS\n");
887 #endif
888 #if INET6
889 if (show_debug_only)
890 debug_print(" IPv6\n");
891 else
892 g_print(" IPv6\n");
893 #endif
894 #if HAVE_ICONV
895 if (show_debug_only)
896 debug_print(" iconv\n");
897 else
898 g_print(" iconv\n");
899 #endif
900 #if USE_JPILOT
901 if (show_debug_only)
902 debug_print(" JPilot\n");
903 else
904 g_print(" JPilot\n");
905 #endif
906 #if USE_LDAP
907 if (show_debug_only)
908 debug_print(" LDAP\n");
909 else
910 g_print(" LDAP\n");
911 #endif
912 #if HAVE_LIBETPAN
913 if (show_debug_only)
914 debug_print(" libetpan %d.%d\n", LIBETPAN_VERSION_MAJOR, LIBETPAN_VERSION_MINOR);
915 else
916 g_print(" libetpan %d.%d\n", LIBETPAN_VERSION_MAJOR, LIBETPAN_VERSION_MINOR);
917 #endif
918 #if HAVE_LIBSM
919 if (show_debug_only)
920 debug_print(" libSM\n");
921 else
922 g_print(" libSM\n");
923 #endif
924 #if HAVE_NETWORKMANAGER_SUPPORT
925 if (show_debug_only)
926 debug_print(" NetworkManager\n");
927 else
928 g_print(" NetworkManager\n");
929 #endif
930 #if HAVE_SVG
931 if (show_debug_only)
932 debug_print(" librSVG " LIBRSVG_VERSION "\n");
933 else
934 g_print(" librSVG " LIBRSVG_VERSION "\n");
935 #endif
938 #ifdef HAVE_DBUS_GLIB
939 static gulong dbus_item_hook_id = HOOK_NONE;
940 static gulong dbus_folder_hook_id = HOOK_NONE;
942 static void uninstall_dbus_status_handler(void)
944 if(awn_proxy)
945 g_object_unref(awn_proxy);
946 awn_proxy = NULL;
947 if (dbus_item_hook_id != HOOK_NONE)
948 hooks_unregister_hook(FOLDER_ITEM_UPDATE_HOOKLIST, dbus_item_hook_id);
949 if (dbus_folder_hook_id != HOOK_NONE)
950 hooks_unregister_hook(FOLDER_UPDATE_HOOKLIST, dbus_folder_hook_id);
953 static void dbus_update(FolderItem *removed_item)
955 guint new, unread, unreadmarked, marked, total;
956 guint replied, forwarded, locked, ignored, watched;
957 gchar *buf;
958 GError *error = NULL;
960 folder_count_total_msgs(&new, &unread, &unreadmarked, &marked, &total,
961 &replied, &forwarded, &locked, &ignored,
962 &watched);
963 if (removed_item) {
964 total -= removed_item->total_msgs;
965 new -= removed_item->new_msgs;
966 unread -= removed_item->unread_msgs;
969 if (new > 0) {
970 buf = g_strdup_printf("%d", new);
971 dbus_g_proxy_call(awn_proxy, "SetInfoByName", &error,
972 G_TYPE_STRING, "claws-mail",
973 G_TYPE_STRING, buf,
974 G_TYPE_INVALID, G_TYPE_INVALID);
975 g_free(buf);
977 } else {
978 dbus_g_proxy_call(awn_proxy, "UnsetInfoByName", &error, G_TYPE_STRING,
979 "claws-mail", G_TYPE_INVALID, G_TYPE_INVALID);
981 if (error) {
982 debug_print("%s\n", error->message);
983 g_error_free(error);
987 static gboolean dbus_status_update_folder_hook(gpointer source, gpointer data)
989 FolderUpdateData *hookdata;
990 hookdata = source;
991 if (hookdata->update_flags & FOLDER_REMOVE_FOLDERITEM)
992 dbus_update(hookdata->item);
993 else
994 dbus_update(NULL);
996 return FALSE;
999 static gboolean dbus_status_update_item_hook(gpointer source, gpointer data)
1001 dbus_update(NULL);
1003 return FALSE;
1006 static void install_dbus_status_handler(void)
1008 GError *tmp_error = NULL;
1009 DBusGConnection *connection = dbus_g_bus_get(DBUS_BUS_SESSION, &tmp_error);
1011 if(!connection) {
1012 /* If calling code doesn't do error checking, at least print some debug */
1013 debug_print("Failed to open connection to session bus: %s\n",
1014 tmp_error->message);
1015 g_error_free(tmp_error);
1016 return;
1018 awn_proxy = dbus_g_proxy_new_for_name(connection,
1019 "com.google.code.Awn",
1020 "/com/google/code/Awn",
1021 "com.google.code.Awn");
1022 dbus_item_hook_id = hooks_register_hook (FOLDER_ITEM_UPDATE_HOOKLIST, dbus_status_update_item_hook, NULL);
1023 if (dbus_item_hook_id == HOOK_NONE) {
1024 g_warning("failed to register folder item update hook");
1025 uninstall_dbus_status_handler();
1026 return;
1029 dbus_folder_hook_id = hooks_register_hook (FOLDER_UPDATE_HOOKLIST, dbus_status_update_folder_hook, NULL);
1030 if (dbus_folder_hook_id == HOOK_NONE) {
1031 g_warning("failed to register folder update hook");
1032 uninstall_dbus_status_handler();
1033 return;
1036 #endif
1038 static void reset_statistics(void)
1040 /* (re-)initialize session statistics */
1041 session_stats.received = 0;
1042 session_stats.sent = 0;
1043 session_stats.replied = 0;
1044 session_stats.forwarded = 0;
1045 session_stats.time_started = time(NULL);
1048 int main(int argc, char *argv[])
1050 #ifdef HAVE_DBUS_GLIB
1051 DBusGConnection *connection;
1052 GError *error;
1053 #endif
1054 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1055 DBusGProxy *nm_proxy;
1056 #endif
1057 gchar *userrc;
1058 MainWindow *mainwin;
1059 FolderView *folderview;
1060 GdkPixbuf *icon;
1061 gboolean crash_file_present = FALSE;
1062 guint num_folder_class = 0;
1063 gboolean asked_for_migration = FALSE;
1064 gboolean start_done = TRUE;
1065 GSList *plug_list = NULL;
1066 gboolean never_ran = FALSE;
1067 gboolean mainwin_shown = FALSE;
1068 gint ret;
1070 START_TIMING("startup");
1072 sc_starting = TRUE;
1074 #ifdef G_OS_WIN32
1075 win32_open_log();
1076 #endif
1077 if (!claws_init(&argc, &argv)) {
1078 #ifdef G_OS_WIN32
1079 win32_close_log();
1080 #endif
1081 return 0;
1084 prog_version = PROG_VERSION;
1085 #if (defined HAVE_LIBSM || defined CRASH_DIALOG)
1086 argv0 = g_strdup(argv[0]);
1087 #endif
1089 parse_cmd_opt(argc, argv);
1091 sock_init();
1093 /* check and create unix domain socket for remote operation */
1094 lock_socket = prohibit_duplicate_launch();
1095 if (lock_socket < 0) {
1096 #ifdef HAVE_STARTUP_NOTIFICATION
1097 if(gtk_init_check(&argc, &argv))
1098 startup_notification_complete(TRUE);
1099 #endif
1100 return 0;
1103 main_dump_features_list(TRUE);
1104 prefs_prepare_cache();
1106 #ifdef CRASH_DIALOG
1107 if (cmd.crash) {
1108 gtk_set_locale();
1109 gtk_init(&argc, &argv);
1110 crash_main(cmd.crash_params);
1111 #ifdef G_OS_WIN32
1112 win32_close_log();
1113 #endif
1114 return 0;
1116 crash_install_handlers();
1117 #endif
1118 install_basic_sighandlers();
1119 #if (defined linux && defined SIGIO)
1120 install_memory_sighandler();
1121 #endif
1123 if (cmd.status || cmd.status_full || cmd.search ||
1124 cmd.statistics || cmd.reset_statistics ||
1125 cmd.cancel_receiving || cmd.cancel_sending ||
1126 cmd.debug) {
1127 puts("0 Claws Mail not running.");
1128 lock_socket_remove();
1129 return 0;
1132 if (cmd.exit)
1133 return 0;
1135 reset_statistics();
1137 gtk_set_locale();
1138 gtk_init(&argc, &argv);
1140 #ifdef G_OS_WIN32
1141 gtk_settings_set_string_property(gtk_settings_get_default(),
1142 "gtk-theme-name",
1143 "MS-Windows",
1144 "XProperty");
1145 gtk_settings_set_long_property(gtk_settings_get_default(),
1146 "gtk-auto-mnemonics",
1147 TRUE,
1148 "XProperty");
1149 gtk_settings_set_long_property(gtk_settings_get_default(),
1150 "gtk-button-images",
1151 TRUE,
1152 "XProperty");
1153 #endif
1155 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1156 went_offline_nm = FALSE;
1157 nm_proxy = NULL;
1158 #endif
1159 #ifdef HAVE_DBUS_GLIB
1160 error = NULL;
1161 connection = dbus_g_bus_get(DBUS_BUS_SYSTEM, &error);
1163 if(!connection) {
1164 debug_print("Failed to open connection to system bus: %s\n", error->message);
1165 g_error_free(error);
1167 else {
1168 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1169 nm_proxy = dbus_g_proxy_new_for_name(connection,
1170 "org.freedesktop.NetworkManager",
1171 "/org/freedesktop/NetworkManager",
1172 "org.freedesktop.NetworkManager");
1173 if (nm_proxy) {
1174 dbus_g_proxy_add_signal(nm_proxy, "StateChanged", G_TYPE_UINT, G_TYPE_INVALID);
1175 dbus_g_proxy_connect_signal(nm_proxy, "StateChanged",
1176 G_CALLBACK(networkmanager_state_change_cb),
1177 NULL,NULL);
1179 #endif
1180 install_dbus_status_handler();
1182 #endif
1184 gtk_widget_set_default_colormap(
1185 gdk_screen_get_system_colormap(
1186 gdk_screen_get_default()));
1188 gtkut_create_ui_manager();
1190 /* Create container for all the menus we will be adding */
1191 MENUITEM_ADDUI("/", "Menus", NULL, GTK_UI_MANAGER_MENUBAR);
1193 #ifdef G_OS_WIN32
1194 CHDIR_EXEC_CODE_RETURN_VAL_IF_FAIL(get_home_dir(), 1, win32_close_log(););
1195 #else
1196 CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
1197 #endif
1199 /* no config dir exists. See if we can migrate an old config. */
1200 if (!is_dir_exist(get_rc_dir())) {
1201 prefs_destroy_cache();
1202 gboolean r = FALSE;
1204 /* if one of the old dirs exist, we'll ask if the user
1205 * want to migrates, and r will be TRUE if he said yes
1206 * and migration succeeded, and FALSE otherwise.
1208 if (is_dir_exist(OLD_GTK2_RC_DIR)) {
1209 r = migrate_old_config(OLD_GTK2_RC_DIR, get_rc_dir(),
1210 g_strconcat("Sylpheed-Claws 2.6.0 ", _("(or older)"), NULL));
1211 asked_for_migration = TRUE;
1212 } else if (is_dir_exist(OLDER_GTK2_RC_DIR)) {
1213 r = migrate_old_config(OLDER_GTK2_RC_DIR, get_rc_dir(),
1214 g_strconcat("Sylpheed-Claws 1.9.15 ",_("(or older)"), NULL));
1215 asked_for_migration = TRUE;
1216 } else if (is_dir_exist(OLD_GTK1_RC_DIR)) {
1217 r = migrate_old_config(OLD_GTK1_RC_DIR, get_rc_dir(),
1218 g_strconcat("Sylpheed-Claws 1.0.5 ",_("(or older)"), NULL));
1219 asked_for_migration = TRUE;
1220 } else if (is_dir_exist(SYLPHEED_RC_DIR)) {
1221 r = migrate_old_config(SYLPHEED_RC_DIR, get_rc_dir(), "Sylpheed");
1222 asked_for_migration = TRUE;
1225 /* If migration failed or the user didn't want to do it,
1226 * we create a new one (and we'll hit wizard later).
1228 if (r == FALSE && !is_dir_exist(get_rc_dir())) {
1229 #ifdef G_OS_UNIX
1230 if (copy_dir(SYSCONFDIR "/skel/.claws-mail", get_rc_dir()) < 0) {
1231 #endif
1232 if (!is_dir_exist(get_rc_dir()) && make_dir(get_rc_dir()) < 0) {
1233 #ifdef G_OS_WIN32
1234 win32_close_log();
1235 #endif
1236 exit(1);
1238 #ifdef G_OS_UNIX
1240 #endif
1245 if (!is_file_exist(RC_DIR G_DIR_SEPARATOR_S COMMON_RC) &&
1246 is_file_exist(RC_DIR G_DIR_SEPARATOR_S OLD_COMMON_RC)) {
1247 /* post 2.6 name change */
1248 migrate_common_rc(RC_DIR G_DIR_SEPARATOR_S OLD_COMMON_RC,
1249 RC_DIR G_DIR_SEPARATOR_S COMMON_RC);
1252 if (!cmd.exit)
1253 plugin_load_all("Common");
1255 userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, "gtkrc-2.0", NULL);
1256 gtk_rc_parse(userrc);
1257 g_free(userrc);
1259 userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
1260 gtk_accel_map_load (userrc);
1261 g_free(userrc);
1263 #ifdef G_OS_WIN32
1264 CHDIR_EXEC_CODE_RETURN_VAL_IF_FAIL(get_rc_dir(), 1, win32_close_log(););
1265 #else
1266 CHDIR_RETURN_VAL_IF_FAIL(get_rc_dir(), 1);
1267 #endif
1269 MAKE_DIR_IF_NOT_EXIST(get_mail_base_dir());
1270 MAKE_DIR_IF_NOT_EXIST(get_imap_cache_dir());
1271 MAKE_DIR_IF_NOT_EXIST(get_news_cache_dir());
1272 MAKE_DIR_IF_NOT_EXIST(get_mime_tmp_dir());
1273 MAKE_DIR_IF_NOT_EXIST(get_tmp_dir());
1274 MAKE_DIR_IF_NOT_EXIST(UIDL_DIR);
1276 crash_file_present = is_file_exist(get_crashfile_name());
1277 /* remove temporary files */
1278 remove_all_files(get_tmp_dir());
1279 remove_all_files(get_mime_tmp_dir());
1281 if (!cmd.crash && crash_file_present)
1282 claws_crashed_bool = TRUE;
1284 if (is_file_exist("claws.log")) {
1285 if (rename_force("claws.log", "claws.log.bak") < 0)
1286 FILE_OP_ERROR("claws.log", "rename");
1288 set_log_file(LOG_PROTOCOL, "claws.log");
1290 if (is_file_exist("filtering.log")) {
1291 if (rename_force("filtering.log", "filtering.log.bak") < 0)
1292 FILE_OP_ERROR("filtering.log", "rename");
1294 set_log_file(LOG_DEBUG_FILTERING, "filtering.log");
1296 #ifdef G_OS_WIN32
1297 CHDIR_EXEC_CODE_RETURN_VAL_IF_FAIL(get_home_dir(), 1, win32_close_log(););
1298 #else
1299 CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
1300 #endif
1302 folder_system_init();
1303 prefs_common_read_config();
1305 if (prefs_update_config_version_common() < 0) {
1306 debug_print("Main configuration file version upgrade failed, exiting\n");
1307 #ifdef G_OS_WIN32
1308 win32_close_log();
1309 #endif
1310 exit(200);
1313 prefs_themes_init();
1314 prefs_fonts_init();
1315 prefs_ext_prog_init();
1316 prefs_wrapping_init();
1317 prefs_compose_writing_init();
1318 prefs_msg_colors_init();
1319 image_viewer_init();
1320 prefs_image_viewer_init();
1321 prefs_quote_init();
1322 prefs_summaries_init();
1323 prefs_message_init();
1324 prefs_other_init();
1325 prefs_proxy_init();
1326 prefs_logging_init();
1327 prefs_receive_init();
1328 prefs_send_init();
1329 tags_read_tags();
1330 matcher_init();
1331 #ifdef USE_ENCHANT
1332 gtkaspell_checkers_init();
1333 prefs_spelling_init();
1334 #endif
1336 codeconv_set_allow_jisx0201_kana(prefs_common.allow_jisx0201_kana);
1337 codeconv_set_broken_are_utf8(prefs_common.broken_are_utf8);
1339 #ifdef G_OS_WIN32
1340 if(prefs_common.gtk_theme && strcmp(prefs_common.gtk_theme, DEFAULT_W32_GTK_THEME))
1341 gtk_settings_set_string_property(gtk_settings_get_default(),
1342 "gtk-theme-name",
1343 prefs_common.gtk_theme,
1344 "XProperty");
1345 #endif
1348 sock_set_io_timeout(prefs_common.io_timeout_secs);
1349 prefs_actions_read_config();
1350 prefs_display_header_read_config();
1351 /* prefs_filtering_read_config(); */
1352 #ifndef USE_ALT_ADDRBOOK
1353 addressbook_read_file();
1354 #else
1355 g_clear_error(&error);
1356 if (! addressbook_start_service(&error)) {
1357 g_warning("%s", error->message);
1358 g_clear_error(&error);
1360 else {
1361 addressbook_install_hooks(&error);
1363 #endif
1364 gtkut_widget_init();
1365 priv_pixbuf_gdk(PRIV_PIXMAP_CLAWS_MAIL_ICON, &icon);
1366 gtk_window_set_default_icon(icon);
1368 folderview_initialize();
1370 mh_gtk_init();
1371 imap_gtk_init();
1372 news_gtk_init();
1374 mainwin = main_window_create();
1376 if (!check_file_integrity())
1377 exit(1);
1379 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1380 networkmanager_state_change_cb(nm_proxy,NULL,mainwin);
1381 #endif
1383 manage_window_focus_in(mainwin->window, NULL, NULL);
1384 folderview = mainwin->folderview;
1386 folderview_freeze(mainwin->folderview);
1387 folder_item_update_freeze();
1389 if ((ret = passwd_store_read_config()) < 0) {
1390 debug_print("Password store configuration file version upgrade failed (%d), exiting\n", ret);
1391 #ifdef G_OS_WIN32
1392 win32_close_log();
1393 #endif
1394 exit(202);
1397 prefs_account_init();
1398 account_read_config_all();
1400 if (prefs_update_config_version_accounts() < 0) {
1401 debug_print("Accounts configuration file version upgrade failed, exiting\n");
1402 #ifdef G_OS_WIN32
1403 win32_close_log();
1404 #endif
1405 exit(201);
1408 #ifdef HAVE_LIBETPAN
1409 imap_main_init(prefs_common.skip_ssl_cert_check);
1410 imap_main_set_timeout(prefs_common.io_timeout_secs);
1411 nntp_main_init(prefs_common.skip_ssl_cert_check);
1412 #endif
1413 /* If we can't read a folder list or don't have accounts,
1414 * it means the configuration's not done. Either this is
1415 * a brand new install, a failed/refused migration,
1416 * or a failed config_version upgrade.
1418 if ((ret = folder_read_list()) < 0) {
1419 debug_print("Folderlist read failed (%d)\n", ret);
1420 prefs_destroy_cache();
1422 if (ret == -2) {
1423 /* config_version update failed in folder_read_list(). We
1424 * do not want to run the wizard, just exit. */
1425 debug_print("Folderlist version upgrade failed, exiting\n");
1426 #ifdef G_OS_WIN32
1427 win32_close_log();
1428 #endif
1429 exit(203);
1432 /* if run_wizard returns FALSE it's because it's
1433 * been cancelled. We can't do much but exit.
1434 * however, if the user was asked for a migration,
1435 * we remove the newly created directory so that
1436 * he's asked again for migration on next launch.*/
1437 if (!run_wizard(mainwin, TRUE)) {
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 main_window_reflect_prefs_all_now();
1446 folder_write_list();
1447 never_ran = TRUE;
1450 if (!account_get_list()) {
1451 prefs_destroy_cache();
1452 if (!run_wizard(mainwin, FALSE)) {
1453 if (asked_for_migration)
1454 remove_dir_recursive(RC_DIR);
1455 #ifdef G_OS_WIN32
1456 win32_close_log();
1457 #endif
1458 exit(1);
1460 if(!account_get_list()) {
1461 exit_claws(mainwin);
1462 exit(1);
1464 never_ran = TRUE;
1468 toolbar_main_set_sensitive(mainwin);
1469 main_window_set_menu_sensitive(mainwin);
1471 /* if crashed, show window early so that the user
1472 * sees what's happening */
1473 if (claws_crashed()) {
1474 main_window_popup(mainwin);
1475 mainwin_shown = TRUE;
1478 account_set_missing_folder();
1479 folder_set_missing_folders();
1480 folderview_set(folderview);
1482 prefs_matcher_read_config();
1483 quicksearch_set_search_strings(mainwin->summaryview->quicksearch);
1485 /* make one all-folder processing before using claws */
1486 main_window_cursor_wait(mainwin);
1487 folder_func_to_all_folders(initial_processing, (gpointer *)mainwin);
1489 /* if claws crashed, rebuild caches */
1490 if (claws_crashed()) {
1491 GTK_EVENTS_FLUSH();
1492 debug_print("Claws Mail crashed, checking for new messages in local folders\n");
1493 folder_item_update_thaw();
1494 folderview_check_new(NULL);
1495 folder_clean_cache_memory_force();
1496 folder_item_update_freeze();
1498 /* make the crash-indicator file */
1499 if (str_write_to_file("foo", get_crashfile_name(), FALSE) < 0) {
1500 g_warning("can't create the crash-indicator file");
1503 inc_autocheck_timer_init(mainwin);
1505 /* ignore SIGPIPE signal for preventing sudden death of program */
1506 #ifdef G_OS_UNIX
1507 signal(SIGPIPE, SIG_IGN);
1508 #endif
1509 if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
1510 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
1512 if (cmd.online_mode == ONLINE_MODE_ONLINE) {
1513 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
1516 if (cmd.status_folders) {
1517 g_ptr_array_free(cmd.status_folders, TRUE);
1518 cmd.status_folders = NULL;
1520 if (cmd.status_full_folders) {
1521 g_ptr_array_free(cmd.status_full_folders, TRUE);
1522 cmd.status_full_folders = NULL;
1525 claws_register_idle_function(claws_gtk_idle);
1527 avatars_init();
1528 prefs_toolbar_init();
1530 num_folder_class = g_list_length(folder_get_list());
1532 plugin_load_all("GTK2");
1534 if (g_list_length(folder_get_list()) != num_folder_class) {
1535 debug_print("new folders loaded, reloading processing rules\n");
1536 prefs_matcher_read_config();
1539 if ((plug_list = plugin_get_unloaded_list()) != NULL) {
1540 GSList *cur;
1541 gchar *list = NULL;
1542 gint num_plugins = 0;
1543 for (cur = plug_list; cur; cur = cur->next) {
1544 Plugin *plugin = (Plugin *)cur->data;
1545 gchar *tmp = g_strdup_printf("%s\n%s",
1546 list? list:"",
1547 plugin_get_name(plugin));
1548 g_free(list);
1549 list = tmp;
1550 num_plugins++;
1552 main_window_cursor_normal(mainwin);
1553 main_window_popup(mainwin);
1554 mainwin_shown = TRUE;
1555 alertpanel_warning(ngettext(
1556 "The following plugin failed to load. "
1557 "Check the Plugins configuration "
1558 "for more information:\n%s",
1559 "The following plugins failed to load. "
1560 "Check the Plugins configuration "
1561 "for more information:\n%s",
1562 num_plugins),
1563 list);
1564 main_window_cursor_wait(mainwin);
1565 g_free(list);
1566 g_slist_free(plug_list);
1569 if (never_ran) {
1570 prefs_common_write_config();
1571 plugin_load_standard_plugins ();
1574 /* if not crashed, show window now */
1575 if (!mainwin_shown) {
1576 /* apart if something told not to show */
1577 if (show_at_startup)
1578 main_window_popup(mainwin);
1581 if (cmd.geometry != NULL) {
1582 if (!gtk_window_parse_geometry(GTK_WINDOW(mainwin->window), cmd.geometry))
1583 g_warning("failed to parse geometry '%s'", cmd.geometry);
1584 else {
1585 int width, height;
1587 if (sscanf(cmd.geometry, "%ux%u+", &width, &height) == 2)
1588 gtk_window_resize(GTK_WINDOW(mainwin->window), width, height);
1589 else
1590 g_warning("failed to parse geometry's width/height");
1594 if (!folder_have_mailbox()) {
1595 prefs_destroy_cache();
1596 main_window_cursor_normal(mainwin);
1597 if (folder_get_list() != NULL) {
1598 alertpanel_error(_("Claws Mail has detected a configured "
1599 "mailbox, but it is incomplete. It is "
1600 "possibly due to a failing IMAP account. Use "
1601 "\"Rebuild folder tree\" on the mailbox parent "
1602 "folder's context menu to try to fix it."));
1603 } else {
1604 alertpanel_error(_("Claws Mail has detected a configured "
1605 "mailbox, but could not load it. It is "
1606 "probably provided by an out-of-date "
1607 "external plugin. Please reinstall the "
1608 "plugin and try again."));
1609 exit_claws(mainwin);
1610 exit(1);
1614 static_mainwindow = mainwin;
1616 #ifdef HAVE_STARTUP_NOTIFICATION
1617 startup_notification_complete(FALSE);
1618 #endif
1619 #ifdef HAVE_LIBSM
1620 sc_session_manager_connect(mainwin);
1621 #endif
1623 folder_item_update_thaw();
1624 folderview_thaw(mainwin->folderview);
1625 main_window_cursor_normal(mainwin);
1627 if (!cmd.target && prefs_common.goto_last_folder_on_startup &&
1628 folder_find_item_from_identifier(prefs_common.last_opened_folder) != NULL &&
1629 !claws_crashed()) {
1630 cmd.target = prefs_common.last_opened_folder;
1633 if (cmd.receive_all && !cmd.target) {
1634 start_done = FALSE;
1635 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(FALSE));
1636 } else if (prefs_common.chk_on_startup && !cmd.target) {
1637 start_done = FALSE;
1638 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(TRUE));
1639 } else if (cmd.receive && !cmd.target) {
1640 start_done = FALSE;
1641 g_timeout_add(1000, defer_check, NULL);
1643 folderview_grab_focus(folderview);
1645 if (cmd.compose) {
1646 open_compose_new(cmd.compose_mailto, cmd.attach_files);
1648 if (cmd.attach_files) {
1649 list_free_strings_full(cmd.attach_files);
1650 cmd.attach_files = NULL;
1652 if (cmd.subscribe) {
1653 folder_subscribe(cmd.subscribe_uri);
1656 if (cmd.send) {
1657 send_queue();
1660 if (cmd.target) {
1661 start_done = FALSE;
1662 g_timeout_add(500, defer_jump, (gpointer)cmd.target);
1665 prefs_destroy_cache();
1667 compose_reopen_exit_drafts();
1669 if (start_done) {
1670 sc_starting = FALSE;
1671 main_window_set_menu_sensitive(mainwin);
1672 toolbar_main_set_sensitive(mainwin);
1675 /* register the callback of unix domain socket input */
1676 lock_socket_tag = claws_input_add(lock_socket,
1677 G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_PRI,
1678 lock_socket_input_cb,
1679 mainwin, TRUE);
1681 END_TIMING();
1683 gtk_main();
1685 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1686 if(nm_proxy)
1687 g_object_unref(nm_proxy);
1688 #endif
1689 #ifdef HAVE_DBUS_GLIB
1690 uninstall_dbus_status_handler();
1691 if(connection)
1692 dbus_g_connection_unref(connection);
1693 #endif
1694 utils_free_regex();
1695 exit_claws(mainwin);
1697 return 0;
1700 static void save_all_caches(FolderItem *item, gpointer data)
1702 if (!item->cache) {
1703 return;
1706 if (item->opened) {
1707 folder_item_close(item);
1710 folder_item_free_cache(item, TRUE);
1713 static void exit_claws(MainWindow *mainwin)
1715 gchar *filename;
1716 gboolean have_connectivity;
1717 FolderItem *item;
1719 sc_exiting = TRUE;
1721 debug_print("shutting down\n");
1722 inc_autocheck_timer_remove();
1724 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1725 if (prefs_common.work_offline && went_offline_nm)
1726 prefs_common.work_offline = FALSE;
1727 #endif
1729 /* save prefs for opened folder */
1730 if((item = folderview_get_opened_item(mainwin->folderview)) != NULL) {
1731 summary_save_prefs_to_folderitem(
1732 mainwin->summaryview, item);
1733 if (prefs_common.last_opened_folder != NULL)
1734 g_free(prefs_common.last_opened_folder);
1735 prefs_common.last_opened_folder =
1736 !prefs_common.goto_last_folder_on_startup ? NULL :
1737 folder_item_get_identifier(item);
1740 /* save all state before exiting */
1741 folder_func_to_all_folders(save_all_caches, NULL);
1742 folder_write_list();
1744 main_window_get_size(mainwin);
1745 main_window_get_position(mainwin);
1747 prefs_common_write_config();
1748 account_write_config_all();
1749 passwd_store_write_config();
1750 #ifndef USE_ALT_ADDRBOOK
1751 addressbook_export_to_file();
1752 #endif
1753 filename = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
1754 gtk_accel_map_save(filename);
1755 g_free(filename);
1757 /* delete temporary files */
1758 remove_all_files(get_tmp_dir());
1759 remove_all_files(get_mime_tmp_dir());
1761 close_log_file(LOG_PROTOCOL);
1762 close_log_file(LOG_DEBUG_FILTERING);
1764 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1765 have_connectivity = networkmanager_is_online(NULL);
1766 #else
1767 have_connectivity = TRUE;
1768 #endif
1769 #ifdef HAVE_LIBETPAN
1770 imap_main_done(have_connectivity);
1771 nntp_main_done(have_connectivity);
1772 #endif
1773 /* delete crashfile */
1774 if (!cmd.crash)
1775 claws_unlink(get_crashfile_name());
1777 lock_socket_remove();
1779 #ifdef HAVE_LIBSM
1780 if (mainwin->smc_conn)
1781 SmcCloseConnection ((SmcConn)mainwin->smc_conn, 0, NULL);
1782 mainwin->smc_conn = NULL;
1783 #endif
1785 main_window_destroy_all();
1787 plugin_unload_all("GTK2");
1789 matcher_done();
1790 prefs_toolbar_done();
1791 avatars_done();
1793 #ifndef USE_ALT_ADDRBOOK
1794 addressbook_destroy();
1795 #endif
1796 prefs_themes_done();
1797 prefs_fonts_done();
1798 prefs_ext_prog_done();
1799 prefs_wrapping_done();
1800 prefs_compose_writing_done();
1801 prefs_msg_colors_done();
1802 prefs_image_viewer_done();
1803 image_viewer_done();
1804 prefs_quote_done();
1805 prefs_summaries_done();
1806 prefs_message_done();
1807 prefs_other_done();
1808 prefs_proxy_done();
1809 prefs_receive_done();
1810 prefs_logging_done();
1811 prefs_send_done();
1812 tags_write_tags();
1813 #ifdef USE_ENCHANT
1814 prefs_spelling_done();
1815 gtkaspell_checkers_quit();
1816 #endif
1817 plugin_unload_all("Common");
1818 #ifdef G_OS_WIN32
1819 win32_close_log();
1820 #endif
1821 claws_done();
1824 #define G_PRINT_EXIT(msg) \
1826 g_print(msg); \
1827 exit(1); \
1830 static void parse_cmd_compose_from_file(const gchar *fn, GString *body)
1832 GString *headers = g_string_new(NULL);
1833 gchar *to = NULL;
1834 gchar *h;
1835 gchar *v;
1836 gchar fb[BUFFSIZE];
1837 FILE *fp;
1838 gboolean isstdin;
1840 if (fn == NULL || *fn == '\0')
1841 G_PRINT_EXIT(_("Missing filename\n"));
1842 isstdin = (*fn == '-' && *(fn + 1) == '\0');
1843 if (isstdin)
1844 fp = stdin;
1845 else {
1846 fp = claws_fopen(fn, "r");
1847 if (!fp)
1848 G_PRINT_EXIT(_("Cannot open filename for reading\n"));
1851 while (claws_fgets(fb, sizeof(fb), fp)) {
1852 gchar *tmp;
1853 strretchomp(fb);
1854 if (*fb == '\0')
1855 break;
1856 h = fb;
1857 while (*h && *h != ':') { ++h; } /* search colon */
1858 if (*h == '\0')
1859 G_PRINT_EXIT(_("Malformed header\n"));
1860 v = h + 1;
1861 while (*v && *v == ' ') { ++v; } /* trim value start */
1862 *h = '\0';
1863 tmp = g_ascii_strdown(fb, -1); /* get header name */
1864 if (!strcmp(tmp, "to")) {
1865 if (to != NULL)
1866 G_PRINT_EXIT(_("Duplicated 'To:' header\n"));
1867 to = g_strdup(v);
1868 } else {
1869 g_string_append_c(headers, '&');
1870 g_string_append(headers, tmp);
1871 g_string_append_c(headers, '=');
1872 g_string_append_uri_escaped(headers, v, NULL, TRUE);
1874 g_free(tmp);
1876 if (to == NULL)
1877 G_PRINT_EXIT(_("Missing required 'To:' header\n"));
1878 g_string_append(body, to);
1879 g_free(to);
1880 g_string_append(body, "?body=");
1881 while (claws_fgets(fb, sizeof(fb), fp)) {
1882 g_string_append_uri_escaped(body, fb, NULL, TRUE);
1884 if (!isstdin)
1885 claws_fclose(fp);
1886 /* append the remaining headers */
1887 g_string_append(body, headers->str);
1888 g_string_free(headers, TRUE);
1891 #undef G_PRINT_EXIT
1893 static void parse_cmd_opt_error(char *errstr, char* optstr)
1895 gchar tmp[BUFSIZ];
1897 cm_return_if_fail(errstr != NULL);
1898 cm_return_if_fail(optstr != NULL);
1900 g_snprintf(tmp, sizeof(tmp), errstr, optstr);
1901 g_print(_("%s. Try -h or --help for usage.\n"), tmp);
1902 exit(1);
1905 static GString mailto; /* used to feed cmd.compose_mailto when --compose-from-file is used */
1907 static void parse_cmd_opt(int argc, char *argv[])
1909 AttachInfo *ainfo;
1910 gint i;
1912 for (i = 1; i < argc; i++) {
1913 if (!strcmp(argv[i], "--receive-all")) {
1914 cmd.receive_all = TRUE;
1915 } else if (!strcmp(argv[i], "--receive")) {
1916 cmd.receive = TRUE;
1917 } else if (!strcmp(argv[i], "--cancel-receiving")) {
1918 cmd.cancel_receiving = TRUE;
1919 } else if (!strcmp(argv[i], "--cancel-sending")) {
1920 cmd.cancel_sending = TRUE;
1921 } else if (!strcmp(argv[i], "--compose-from-file")) {
1922 if (i+1 < argc) {
1923 const gchar *p = argv[i+1];
1925 parse_cmd_compose_from_file(p, &mailto);
1926 cmd.compose = TRUE;
1927 cmd.compose_mailto = mailto.str;
1928 i++;
1929 } else {
1930 parse_cmd_opt_error(_("Missing file argument for option %s"), argv[i]);
1932 } else if (!strcmp(argv[i], "--compose")) {
1933 const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
1935 cmd.compose = TRUE;
1936 cmd.compose_mailto = NULL;
1937 if (p && *p != '\0' && *p != '-') {
1938 if (!STRNCMP(p, "mailto:")) {
1939 cmd.compose_mailto = p + 7;
1940 } else {
1941 cmd.compose_mailto = p;
1943 i++;
1945 } else if (!strcmp(argv[i], "--subscribe")) {
1946 if (i+1 < argc) {
1947 const gchar *p = argv[i+1];
1948 if (p && *p != '\0' && *p != '-') {
1949 cmd.subscribe = TRUE;
1950 cmd.subscribe_uri = p;
1951 } else {
1952 parse_cmd_opt_error(_("Missing or empty uri argument for option %s"), argv[i]);
1954 } else {
1955 parse_cmd_opt_error(_("Missing uri argument for option %s"), argv[i]);
1957 } else if (!strcmp(argv[i], "--attach") ||
1958 !strcmp(argv[i], "--insert")) {
1959 if (i+1 < argc) {
1960 const gchar *p = argv[i+1];
1961 gint ii = i;
1962 gchar *file = NULL;
1963 gboolean insert = !strcmp(argv[i], "--insert");
1965 while (p && *p != '\0' && *p != '-') {
1966 if ((file = g_filename_from_uri(p, NULL, NULL)) != NULL) {
1967 if (!is_file_exist(file)) {
1968 g_free(file);
1969 file = NULL;
1972 if (file == NULL && *p != G_DIR_SEPARATOR) {
1973 file = g_strconcat(claws_get_startup_dir(),
1974 G_DIR_SEPARATOR_S,
1975 p, NULL);
1976 } else if (file == NULL) {
1977 file = g_strdup(p);
1980 ainfo = g_new0(AttachInfo, 1);
1981 ainfo->file = file;
1982 ainfo->insert = insert;
1983 cmd.attach_files = g_list_append(cmd.attach_files, ainfo);
1984 ii++;
1985 p = (ii+1 < argc)?argv[ii+1]:NULL;
1987 if (ii==i) {
1988 parse_cmd_opt_error(_("Missing at least one non-empty file argument for option %s"), argv[i]);
1989 } else {
1990 i=ii;
1992 } else {
1993 parse_cmd_opt_error(_("Missing file argument for option %s"), argv[i]);
1995 } else if (!strcmp(argv[i], "--send")) {
1996 cmd.send = TRUE;
1997 } else if (!strcmp(argv[i], "--version-full") ||
1998 !strcmp(argv[i], "-V")) {
1999 g_print("Claws Mail version " VERSION_GIT_FULL "\n");
2000 main_dump_features_list(FALSE);
2001 exit(0);
2002 } else if (!strcmp(argv[i], "--version") ||
2003 !strcmp(argv[i], "-v")) {
2004 g_print("Claws Mail version " VERSION "\n");
2005 exit(0);
2006 } else if (!strcmp(argv[i], "--status-full")) {
2007 const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
2009 cmd.status_full = TRUE;
2010 while (p && *p != '\0' && *p != '-') {
2011 if (!cmd.status_full_folders) {
2012 cmd.status_full_folders =
2013 g_ptr_array_new();
2015 g_ptr_array_add(cmd.status_full_folders,
2016 g_strdup(p));
2017 i++;
2018 p = (i+1 < argc)?argv[i+1]:NULL;
2020 } else if (!strcmp(argv[i], "--status")) {
2021 const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
2023 cmd.status = TRUE;
2024 while (p && *p != '\0' && *p != '-') {
2025 if (!cmd.status_folders)
2026 cmd.status_folders = g_ptr_array_new();
2027 g_ptr_array_add(cmd.status_folders,
2028 g_strdup(p));
2029 i++;
2030 p = (i+1 < argc)?argv[i+1]:NULL;
2032 } else if (!strcmp(argv[i], "--search")) {
2033 if (i+3 < argc) { /* 3 first arguments are mandatory */
2034 const char* p;
2035 /* only set search parameters if they are valid */
2036 p = argv[i+1];
2037 cmd.search_folder = (p && *p != '\0' && *p != '-')?p:NULL;
2038 p = argv[i+2];
2039 cmd.search_type = (p && *p != '\0' && *p != '-')?p:NULL;
2040 p = argv[i+3];
2041 cmd.search_request = (p && *p != '\0' && *p != '-')?p:NULL;
2042 p = (i+4 < argc)?argv[i+4]:NULL;
2043 const char* rec = (p && *p != '\0' && *p != '-')?p:NULL;
2044 cmd.search_recursive = TRUE;
2045 if (rec) {
2046 i++;
2047 if (tolower(*rec)=='n' || tolower(*rec)=='f' || *rec=='0')
2048 cmd.search_recursive = FALSE;
2050 if (cmd.search_folder && cmd.search_type && cmd.search_request) {
2051 cmd.search = TRUE;
2052 i+=3;
2054 } else {
2055 switch (argc-i-1) {
2056 case 0:
2057 parse_cmd_opt_error(_("Missing folder, type and request arguments for option %s"), argv[i]);
2058 break;
2059 case 1:
2060 parse_cmd_opt_error(_("Missing type and request arguments for option %s"), argv[i]);
2061 break;
2062 case 2:
2063 parse_cmd_opt_error(_("Missing request argument for option %s"), argv[i]);
2066 } else if (!strcmp(argv[i], "--online")) {
2067 cmd.online_mode = ONLINE_MODE_ONLINE;
2068 } else if (!strcmp(argv[i], "--offline")) {
2069 cmd.online_mode = ONLINE_MODE_OFFLINE;
2070 } else if (!strcmp(argv[i], "--toggle-debug")) {
2071 cmd.debug = TRUE;
2072 } else if (!strcmp(argv[i], "--statistics")) {
2073 cmd.statistics = TRUE;
2074 } else if (!strcmp(argv[i], "--reset-statistics")) {
2075 cmd.reset_statistics = TRUE;
2076 } else if (!strcmp(argv[i], "--help") ||
2077 !strcmp(argv[i], "-h")) {
2078 gchar *base = g_path_get_basename(argv[0]);
2079 g_print(_("Usage: %s [OPTION]...\n"), base);
2081 g_print("%s\n", _(" --compose [address] open composition window"));
2082 g_print("%s\n", _(" --compose-from-file file\n"
2083 " open composition window with data from given file;\n"
2084 " use - as file name for reading from standard input;\n"
2085 " content format: headers first (To: required) until an\n"
2086 " empty line, then mail body until end of file."));
2087 g_print("%s\n", _(" --subscribe uri subscribe to the given URI if possible"));
2088 g_print("%s\n", _(" --attach file1 [file2]...\n"
2089 " open composition window with specified files\n"
2090 " attached"));
2091 g_print("%s\n", _(" --insert file1 [file2]...\n"
2092 " open composition window with specified files\n"
2093 " inserted"));
2094 g_print("%s\n", _(" --receive receive new messages"));
2095 g_print("%s\n", _(" --receive-all receive new messages of all accounts"));
2096 g_print("%s\n", _(" --cancel-receiving cancel receiving of messages"));
2097 g_print("%s\n", _(" --cancel-sending cancel sending of messages"));
2098 g_print("%s\n", _(" --search folder type request [recursive]\n"
2099 " searches mail\n"
2100 " folder ex.: \"#mh/Mailbox/inbox\" or \"Mail\"\n"
2101 " type: s[ubject],f[rom],t[o],e[xtended],m[ixed] or g: tag\n"
2102 " request: search string\n"
2103 " recursive: false if arg. starts with 0, n, N, f or F"));
2105 g_print("%s\n", _(" --send send all queued messages"));
2106 g_print("%s\n", _(" --status [folder]... show the total number of messages"));
2107 g_print("%s\n", _(" --status-full [folder]...\n"
2108 " show the status of each folder"));
2109 g_print("%s\n", _(" --statistics show session statistics"));
2110 g_print("%s\n", _(" --reset-statistics reset session statistics"));
2111 g_print("%s\n", _(" --select folder[/msg] jump to the specified folder/message\n"
2112 " folder is a folder id like 'folder/sub_folder', a file:// uri or an absolute path"));
2113 g_print("%s\n", _(" --online switch to online mode"));
2114 g_print("%s\n", _(" --offline switch to offline mode"));
2115 g_print("%s\n", _(" --exit --quit -q exit Claws Mail"));
2116 g_print("%s\n", _(" --debug -d debug mode"));
2117 g_print("%s\n", _(" --toggle-debug toggle debug mode"));
2118 g_print("%s\n", _(" --help -h display this help"));
2119 g_print("%s\n", _(" --version -v output version information"));
2120 g_print("%s\n", _(" --version-full -V output version and built-in features information"));
2121 g_print("%s\n", _(" --config-dir output configuration directory"));
2122 g_print("%s\n", _(" --alternate-config-dir directory\n"
2123 " use specified configuration directory"));
2124 g_print("%s\n", _(" --geometry -geometry [WxH][+X+Y]\n"
2125 " set geometry for main window"));
2127 g_free(base);
2128 exit(1);
2129 } else if (!strcmp(argv[i], "--crash")) {
2130 cmd.crash = TRUE;
2131 cmd.crash_params = g_strdup((i+1 < argc)?argv[i+1]:NULL);
2132 i++;
2133 } else if (!strcmp(argv[i], "--config-dir")) {
2134 g_print(RC_DIR "\n");
2135 exit(0);
2136 } else if (!strcmp(argv[i], "--alternate-config-dir")) {
2137 if (i+1 < argc) {
2138 set_rc_dir(argv[i+1]);
2139 i++;
2140 } else {
2141 parse_cmd_opt_error(_("Missing directory argument for option %s"), argv[i]);
2143 } else if (!strcmp(argv[i], "--geometry") ||
2144 !strcmp(argv[i], "-geometry")) {
2145 if (i+1 < argc) {
2146 cmd.geometry = argv[i+1];
2147 i++;
2148 } else {
2149 parse_cmd_opt_error(_("Missing geometry argument for option %s"), argv[i]);
2151 } else if (!strcmp(argv[i], "--exit") ||
2152 !strcmp(argv[i], "--quit") ||
2153 !strcmp(argv[i], "-q")) {
2154 cmd.exit = TRUE;
2155 } else if (!strcmp(argv[i], "--select")) {
2156 if (i+1 < argc) {
2157 cmd.target = argv[i+1];
2158 i++;
2159 } else {
2160 parse_cmd_opt_error(_("Missing folder argument for option %s"), argv[i]);
2162 } else if (i == 1 && argc == 2) {
2163 /* only one parameter. Do something intelligent about it */
2164 if ((strstr(argv[i], "@") || !STRNCMP(argv[i], "mailto:")) && !strstr(argv[i], "://")) {
2165 const gchar *p = argv[i];
2167 cmd.compose = TRUE;
2168 cmd.compose_mailto = NULL;
2169 if (p && *p != '\0' && *p != '-') {
2170 if (!STRNCMP(p, "mailto:")) {
2171 cmd.compose_mailto = p + 7;
2172 } else {
2173 cmd.compose_mailto = p;
2176 } else if (!STRNCMP(argv[i], "file://")) {
2177 cmd.target = argv[i];
2178 } else if (!STRNCMP(argv[i], "?attach=file://")) {
2179 /* Thunar support as per 3.3.0cvs19 */
2180 cmd.compose = TRUE;
2181 cmd.compose_mailto = argv[i];
2182 } else if (strstr(argv[i], "://")) {
2183 const gchar *p = argv[i];
2184 if (p && *p != '\0' && *p != '-') {
2185 cmd.subscribe = TRUE;
2186 cmd.subscribe_uri = p;
2188 } else if (!strcmp(argv[i], "--sync")) {
2189 /* gtk debug */
2190 } else if (is_dir_exist(argv[i]) || is_file_exist(argv[i])) {
2191 cmd.target = argv[i];
2192 } else {
2193 parse_cmd_opt_error(_("Unknown option %s"), argv[i]);
2195 } else {
2196 parse_cmd_opt_error(_("Unknown option %s"), argv[i]);
2200 if (cmd.attach_files && cmd.compose == FALSE) {
2201 cmd.compose = TRUE;
2202 cmd.compose_mailto = NULL;
2206 static void initial_processing(FolderItem *item, gpointer data)
2208 MainWindow *mainwin = (MainWindow *)data;
2209 gchar *buf;
2211 cm_return_if_fail(item);
2212 buf = g_strdup_printf(_("Processing (%s)..."),
2213 item->path
2214 ? item->path
2215 : _("top level folder"));
2216 g_free(buf);
2218 if (folder_item_parent(item) != NULL && item->prefs->enable_processing) {
2219 item->processing_pending = TRUE;
2220 folder_item_apply_processing(item);
2221 item->processing_pending = FALSE;
2224 STATUSBAR_POP(mainwin);
2227 static gboolean draft_all_messages(void)
2229 const GList *compose_list = NULL;
2231 compose_clear_exit_drafts();
2232 compose_list = compose_get_compose_list();
2233 while (compose_list != NULL) {
2234 Compose *c = (Compose*)compose_list->data;
2235 if (!compose_draft(c, COMPOSE_DRAFT_FOR_EXIT))
2236 return FALSE;
2237 compose_list = compose_get_compose_list();
2239 return TRUE;
2241 gboolean clean_quit(gpointer data)
2243 static gboolean firstrun = TRUE;
2245 if (!firstrun) {
2246 return FALSE;
2248 firstrun = FALSE;
2250 /*!< Good idea to have the main window stored in a
2251 * static variable so we can check that variable
2252 * to see if we're really allowed to do things
2253 * that actually the spawner is supposed to
2254 * do (like: sending mail, composing messages).
2255 * Because, really, if we're the spawnee, and
2256 * we touch GTK stuff, we're hosed. See the
2257 * next fixme. */
2259 /* FIXME: Use something else to signal that we're
2260 * in the original spawner, and not in a spawned
2261 * child. */
2262 if (!static_mainwindow) {
2263 return FALSE;
2266 draft_all_messages();
2267 emergency_exit = TRUE;
2268 exit_claws(static_mainwindow);
2269 exit(0);
2271 return FALSE;
2274 void app_will_exit(GtkWidget *widget, gpointer data)
2276 MainWindow *mainwin = data;
2278 if (gtk_main_level() == 0) {
2279 debug_print("not even started\n");
2280 return;
2282 if (sc_exiting == TRUE) {
2283 debug_print("exit pending\n");
2284 return;
2286 sc_exiting = TRUE;
2287 debug_print("exiting\n");
2288 if (compose_get_compose_list()) {
2289 if (!draft_all_messages()) {
2290 main_window_popup(mainwin);
2291 sc_exiting = FALSE;
2292 return;
2296 if (prefs_common.warn_queued_on_exit && procmsg_have_queued_mails_fast()) {
2297 if (alertpanel(_("Queued messages"),
2298 _("Some unsent messages are queued. Exit now?"),
2299 GTK_STOCK_CANCEL, GTK_STOCK_OK, NULL, ALERTFOCUS_FIRST)
2300 != G_ALERTALTERNATE) {
2301 main_window_popup(mainwin);
2302 sc_exiting = FALSE;
2303 return;
2305 manage_window_focus_in(mainwin->window, NULL, NULL);
2308 sock_cleanup();
2309 #ifdef HAVE_VALGRIND
2310 if (RUNNING_ON_VALGRIND) {
2311 summary_clear_list(mainwin->summaryview);
2313 #endif
2314 if (folderview_get_selected_item(mainwin->folderview))
2315 folder_item_close(folderview_get_selected_item(mainwin->folderview));
2316 gtk_main_quit();
2319 gboolean claws_is_exiting(void)
2321 return sc_exiting;
2324 gboolean claws_is_starting(void)
2326 return sc_starting;
2329 #ifdef G_OS_UNIX
2331 * CLAWS: want this public so crash dialog can delete the
2332 * lock file too
2334 gchar *claws_get_socket_name(void)
2336 static gchar *filename = NULL;
2337 gchar *socket_dir = NULL;
2338 gchar md5sum[33];
2340 if (filename == NULL) {
2341 GStatBuf st;
2342 gint stat_ok;
2344 socket_dir = g_strdup_printf("%s%cclaws-mail",
2345 g_get_user_runtime_dir(), G_DIR_SEPARATOR);
2346 stat_ok = g_stat(socket_dir, &st);
2347 if (stat_ok < 0 && errno != ENOENT) {
2348 g_print("Error stat'ing socket_dir %s: %s\n",
2349 socket_dir, g_strerror(errno));
2350 } else if (stat_ok == 0 && S_ISSOCK(st.st_mode)) {
2351 /* old versions used a sock in $TMPDIR/claws-mail-$UID */
2352 debug_print("Using legacy socket %s\n", socket_dir);
2353 filename = g_strdup(socket_dir);
2354 g_free(socket_dir);
2355 return filename;
2358 if (!is_dir_exist(socket_dir) && make_dir(socket_dir) < 0) {
2359 g_print("Error creating socket_dir %s: %s\n",
2360 socket_dir, g_strerror(errno));
2363 md5_hex_digest(md5sum, get_rc_dir());
2365 filename = g_strdup_printf("%s%c%s", socket_dir, G_DIR_SEPARATOR,
2366 md5sum);
2367 g_free(socket_dir);
2368 debug_print("Using control socket %s\n", filename);
2371 return filename;
2373 #endif
2375 static gchar *get_crashfile_name(void)
2377 static gchar *filename = NULL;
2379 if (filename == NULL) {
2380 filename = g_strdup_printf("%s%cclaws-crashed",
2381 get_tmp_dir(), G_DIR_SEPARATOR);
2384 return filename;
2387 static gint prohibit_duplicate_launch(void)
2389 gint sock;
2390 GList *curr;
2391 #ifdef G_OS_UNIX
2392 gchar *path;
2394 path = claws_get_socket_name();
2395 /* Try to connect to the control socket */
2396 sock = fd_connect_unix(path);
2398 if (x_display == NULL)
2399 x_display = g_strdup(g_getenv("DISPLAY"));
2401 if (sock < 0) {
2402 gint ret;
2403 #if HAVE_FLOCK
2404 gchar *socket_lock;
2405 gint lock_fd;
2406 /* If connect failed, no other process is running.
2407 * Unlink the potentially existing socket, then
2408 * open it. This has to be done locking a temporary
2409 * file to avoid the race condition where another
2410 * process could have created the socket just in
2411 * between.
2413 socket_lock = g_strconcat(path, ".lock",
2414 NULL);
2415 lock_fd = g_open(socket_lock, O_RDWR|O_CREAT, 0);
2416 if (lock_fd < 0) {
2417 debug_print("Couldn't open %s: %s (%d)\n", socket_lock,
2418 g_strerror(errno), errno);
2419 g_free(socket_lock);
2420 return -1;
2422 if (flock(lock_fd, LOCK_EX) < 0) {
2423 debug_print("Couldn't lock %s: %s (%d)\n", socket_lock,
2424 g_strerror(errno), errno);
2425 close(lock_fd);
2426 g_free(socket_lock);
2427 return -1;
2429 #endif
2431 claws_unlink(path);
2432 debug_print("Opening socket %s\n", path);
2433 ret = fd_open_unix(path);
2434 #if HAVE_FLOCK
2435 flock(lock_fd, LOCK_UN);
2436 close(lock_fd);
2437 claws_unlink(socket_lock);
2438 g_free(socket_lock);
2439 #endif
2440 return ret;
2442 #else
2443 HANDLE hmutex;
2445 hmutex = CreateMutexA(NULL, FALSE, "ClawsMail");
2446 if (!hmutex) {
2447 debug_print("cannot create Mutex\n");
2448 return -1;
2450 if (GetLastError() != ERROR_ALREADY_EXISTS) {
2451 sock = fd_open_inet(50216);
2452 if (sock < 0)
2453 return 0;
2454 return sock;
2457 sock = fd_connect_inet(50216);
2458 if (sock < 0)
2459 return -1;
2460 #endif
2461 /* remote command mode */
2463 debug_print("another Claws Mail instance is already running.\n");
2465 if (cmd.receive_all) {
2466 CM_FD_WRITE_ALL("receive_all\n");
2467 } else if (cmd.receive) {
2468 CM_FD_WRITE_ALL("receive\n");
2469 } else if (cmd.cancel_receiving) {
2470 CM_FD_WRITE_ALL("cancel_receiving\n");
2471 } else if (cmd.cancel_sending) {
2472 CM_FD_WRITE_ALL("cancel_sending\n");
2473 } else if (cmd.compose && cmd.attach_files) {
2474 gchar *str, *compose_str;
2476 if (cmd.compose_mailto) {
2477 compose_str = g_strdup_printf("compose_attach %s\n",
2478 cmd.compose_mailto);
2479 } else {
2480 compose_str = g_strdup("compose_attach\n");
2483 CM_FD_WRITE_ALL(compose_str);
2484 g_free(compose_str);
2486 for (curr = cmd.attach_files; curr != NULL ; curr = curr->next) {
2487 str = (gchar *) ((AttachInfo *)curr->data)->file;
2488 if (((AttachInfo *)curr->data)->insert)
2489 CM_FD_WRITE_ALL("insert ");
2490 else
2491 CM_FD_WRITE_ALL("attach ");
2492 CM_FD_WRITE_ALL(str);
2493 CM_FD_WRITE_ALL("\n");
2496 CM_FD_WRITE_ALL(".\n");
2497 } else if (cmd.compose) {
2498 gchar *compose_str;
2500 if (cmd.compose_mailto) {
2501 compose_str = g_strdup_printf
2502 ("compose %s\n", cmd.compose_mailto);
2503 } else {
2504 compose_str = g_strdup("compose\n");
2507 CM_FD_WRITE_ALL(compose_str);
2508 g_free(compose_str);
2509 } else if (cmd.subscribe) {
2510 gchar *str = g_strdup_printf("subscribe %s\n", cmd.subscribe_uri);
2511 CM_FD_WRITE_ALL(str);
2512 g_free(str);
2513 } else if (cmd.send) {
2514 CM_FD_WRITE_ALL("send\n");
2515 } else if (cmd.online_mode == ONLINE_MODE_ONLINE) {
2516 CM_FD_WRITE("online\n");
2517 } else if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
2518 CM_FD_WRITE("offline\n");
2519 } else if (cmd.debug) {
2520 CM_FD_WRITE("debug\n");
2521 } else if (cmd.status || cmd.status_full) {
2522 gchar buf[BUFFSIZE];
2523 gint i;
2524 const gchar *command;
2525 GPtrArray *folders;
2526 gchar *folder;
2528 command = cmd.status_full ? "status-full\n" : "status\n";
2529 folders = cmd.status_full ? cmd.status_full_folders :
2530 cmd.status_folders;
2532 CM_FD_WRITE_ALL(command);
2533 for (i = 0; folders && i < folders->len; ++i) {
2534 folder = g_ptr_array_index(folders, i);
2535 CM_FD_WRITE_ALL(folder);
2536 CM_FD_WRITE_ALL("\n");
2538 CM_FD_WRITE_ALL(".\n");
2539 for (;;) {
2540 fd_gets(sock, buf, sizeof(buf) - 1);
2541 buf[sizeof(buf) - 1] = '\0';
2542 if (!STRNCMP(buf, ".\n")) break;
2543 if (claws_fputs(buf, stdout) == EOF) {
2544 g_warning("writing to stdout failed");
2545 break;
2548 } else if (cmd.exit) {
2549 CM_FD_WRITE_ALL("exit\n");
2550 } else if (cmd.statistics) {
2551 gchar buf[BUFSIZ];
2552 CM_FD_WRITE("statistics\n");
2553 for (;;) {
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");
2559 break;
2562 } else if (cmd.reset_statistics) {
2563 CM_FD_WRITE("reset_statistics\n");
2564 } else if (cmd.target) {
2565 gchar *str = g_strdup_printf("select %s\n", cmd.target);
2566 CM_FD_WRITE_ALL(str);
2567 g_free(str);
2568 } else if (cmd.search) {
2569 gchar buf[BUFFSIZE];
2570 gchar *str =
2571 g_strdup_printf("search %s\n%s\n%s\n%c\n",
2572 cmd.search_folder, cmd.search_type, cmd.search_request,
2573 (cmd.search_recursive==TRUE)?'1':'0');
2574 CM_FD_WRITE_ALL(str);
2575 g_free(str);
2576 for (;;) {
2577 fd_gets(sock, buf, sizeof(buf) - 1);
2578 buf[sizeof(buf) - 1] = '\0';
2579 if (!STRNCMP(buf, ".\n")) break;
2580 if (claws_fputs(buf, stdout) == EOF) {
2581 g_warning("writing to stdout failed");
2582 break;
2585 } else {
2586 #ifdef G_OS_UNIX
2587 gchar buf[BUFSIZ];
2588 CM_FD_WRITE_ALL("get_display\n");
2589 memset(buf, 0, sizeof(buf));
2590 fd_gets(sock, buf, sizeof(buf) - 1);
2591 buf[sizeof(buf) - 1] = '\0';
2592 if (g_strcmp0(buf, x_display)) {
2593 g_print("Claws Mail is already running on display %s.\n",
2594 buf);
2595 } else {
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 CM_FD_WRITE_ALL(x_display);
2682 #endif
2683 } else if (!STRNCMP(buf, "receive_all")) {
2684 inc_all_account_mail(mainwin, FALSE, FALSE,
2685 prefs_common.newmail_notify_manu);
2686 } else if (!STRNCMP(buf, "receive")) {
2687 inc_mail(mainwin, prefs_common.newmail_notify_manu);
2688 } else if (!STRNCMP(buf, "cancel_receiving")) {
2689 inc_cancel_all();
2690 imap_cancel_all();
2691 } else if (!STRNCMP(buf, "cancel_sending")) {
2692 send_cancel();
2693 } else if (!STRNCMP(buf, "compose_attach")) {
2694 GList *files = NULL, *curr;
2695 AttachInfo *ainfo;
2696 gchar *mailto;
2698 mailto = g_strdup(buf + strlen("compose_attach") + 1);
2699 while (fd_gets(sock, buf, sizeof(buf) - 1) > 0) {
2700 buf[sizeof(buf) - 1] = '\0';
2701 strretchomp(buf);
2702 if (!g_strcmp0(buf, "."))
2703 break;
2705 ainfo = g_new0(AttachInfo, 1);
2706 ainfo->file = g_strdup(strstr(buf, " ") + 1);
2707 ainfo->insert = !STRNCMP(buf, "insert ");
2708 files = g_list_append(files, ainfo);
2710 open_compose_new(mailto, files);
2712 curr = g_list_first(files);
2713 while (curr != NULL) {
2714 ainfo = (AttachInfo *)curr->data;
2715 g_free(ainfo->file);
2716 g_free(ainfo);
2717 curr = curr->next;
2719 g_list_free(files);
2720 g_free(mailto);
2721 } else if (!STRNCMP(buf, "compose")) {
2722 open_compose_new(buf + strlen("compose") + 1, NULL);
2723 } else if (!STRNCMP(buf, "subscribe")) {
2724 main_window_popup(mainwin);
2725 folder_subscribe(buf + strlen("subscribe") + 1);
2726 } else if (!STRNCMP(buf, "send")) {
2727 send_queue();
2728 } else if (!STRNCMP(buf, "online")) {
2729 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
2730 } else if (!STRNCMP(buf, "offline")) {
2731 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
2732 } else if (!STRNCMP(buf, "debug")) {
2733 debug_set_mode(debug_get_mode() ? FALSE : TRUE);
2734 } else if (!STRNCMP(buf, "status-full") ||
2735 !STRNCMP(buf, "status")) {
2736 gchar *status;
2737 GPtrArray *folders;
2739 folders = get_folder_item_list(sock);
2740 status = folder_get_status
2741 (folders, !STRNCMP(buf, "status-full"));
2742 CM_FD_WRITE_ALL(status);
2743 CM_FD_WRITE_ALL(".\n");
2744 g_free(status);
2745 if (folders) g_ptr_array_free(folders, TRUE);
2746 } else if (!STRNCMP(buf, "statistics")) {
2747 gchar tmp[BUFSIZ];
2749 g_snprintf(tmp, sizeof(tmp), _("Session statistics\n"));
2750 CM_FD_WRITE_ALL(tmp);
2752 if (prefs_common.date_format) {
2753 struct tm *lt;
2754 gint len = 100;
2755 gchar date[len];
2757 lt = localtime(&session_stats.time_started);
2758 fast_strftime(date, len, prefs_common.date_format, lt);
2759 g_snprintf(tmp, sizeof(tmp), _("Started: %s\n"),
2760 lt ? date : ctime(&session_stats.time_started));
2761 } else
2762 g_snprintf(tmp, sizeof(tmp), _("Started: %s\n"),
2763 ctime(&session_stats.time_started));
2764 CM_FD_WRITE_ALL(tmp);
2766 CM_FD_WRITE_ALL("\n");
2768 g_snprintf(tmp, sizeof(tmp), _("Incoming traffic\n"));
2769 CM_FD_WRITE_ALL(tmp);
2771 g_snprintf(tmp, sizeof(tmp), _("Received messages: %d\n"),
2772 session_stats.received);
2773 CM_FD_WRITE_ALL(tmp);
2775 CM_FD_WRITE_ALL("\n");
2777 g_snprintf(tmp, sizeof(tmp), _("Outgoing traffic\n"));
2778 CM_FD_WRITE_ALL(tmp);
2780 g_snprintf(tmp, sizeof(tmp), _("New/redirected messages: %d\n"),
2781 session_stats.sent);
2782 CM_FD_WRITE_ALL(tmp);
2784 g_snprintf(tmp, sizeof(tmp), _("Replied messages: %d\n"),
2785 session_stats.replied);
2786 CM_FD_WRITE_ALL(tmp);
2788 g_snprintf(tmp, sizeof(tmp), _("Forwarded messages: %d\n"),
2789 session_stats.forwarded);
2790 CM_FD_WRITE_ALL(tmp);
2792 g_snprintf(tmp, sizeof(tmp), _("Total outgoing messages: %d\n"),
2793 (session_stats.sent + session_stats.replied +
2794 session_stats.forwarded));
2795 CM_FD_WRITE_ALL(tmp);
2797 CM_FD_WRITE_ALL(".\n");
2798 } else if (!STRNCMP(buf, "reset_statistics")) {
2799 reset_statistics();
2800 } else if (!STRNCMP(buf, "select ")) {
2801 const gchar *target = buf+7;
2802 mainwindow_jump_to(target, TRUE);
2803 } else if (!STRNCMP(buf, "search ")) {
2804 FolderItem* folderItem = NULL;
2805 GSList *messages = NULL;
2806 gchar *folder_name = NULL;
2807 gchar *request = NULL;
2808 AdvancedSearch *search;
2809 gboolean recursive;
2810 AdvancedSearchType searchType = ADVANCED_SEARCH_EXTENDED;
2812 search = advsearch_new();
2814 folder_name = g_strdup(buf+7);
2815 strretchomp(folder_name);
2817 if (fd_gets(sock, buf, sizeof(buf) - 1) <= 0)
2818 goto search_exit;
2819 buf[sizeof(buf) - 1] = '\0';
2821 switch (toupper(buf[0])) {
2822 case 'S': searchType = ADVANCED_SEARCH_SUBJECT; break;
2823 case 'F': searchType = ADVANCED_SEARCH_FROM; break;
2824 case 'T': searchType = ADVANCED_SEARCH_TO; break;
2825 case 'M': searchType = ADVANCED_SEARCH_MIXED; break;
2826 case 'G': searchType = ADVANCED_SEARCH_TAG; break;
2827 case 'E': searchType = ADVANCED_SEARCH_EXTENDED; break;
2830 if (fd_gets(sock, buf, sizeof(buf) - 1) <= 0)
2831 goto search_exit;
2833 buf[sizeof(buf) - 1] = '\0';
2834 request = g_strdup(buf);
2835 strretchomp(request);
2837 recursive = TRUE;
2838 if (fd_gets(sock, buf, sizeof(buf) - 1) > 0)
2839 recursive = buf[0] != '0';
2841 buf[sizeof(buf) - 1] = '\0';
2843 debug_print("search: %s %i %s %i\n", folder_name, searchType, request, recursive);
2845 folderItem = folder_find_item_from_identifier(folder_name);
2847 if (folderItem == NULL) {
2848 debug_print("Unknown folder item : '%s', searching folder\n",folder_name);
2849 Folder* folder = folder_find_from_path(folder_name);
2850 if (folder != NULL)
2851 folderItem = FOLDER_ITEM(folder->node->data);
2852 else
2853 debug_print("Unknown folder: '%s'\n",folder_name);
2854 } else {
2855 debug_print("%s %s\n",folderItem->name, folderItem->path);
2858 if (folderItem != NULL) {
2859 advsearch_set(search, searchType, request);
2860 advsearch_search_msgs_in_folders(search, &messages, folderItem, recursive);
2861 } else {
2862 g_print("Folder '%s' not found.\n'", folder_name);
2865 GSList *cur;
2866 for (cur = messages; cur != NULL; cur = cur->next) {
2867 MsgInfo* msg = (MsgInfo *)cur->data;
2868 gchar *file = procmsg_get_message_file_path(msg);
2869 CM_FD_WRITE_ALL(file);
2870 CM_FD_WRITE_ALL("\n");
2871 g_free(file);
2873 CM_FD_WRITE_ALL(".\n");
2875 search_exit:
2876 g_free(folder_name);
2877 g_free(request);
2878 advsearch_free(search);
2879 if (messages != NULL)
2880 procmsg_msg_list_free(messages);
2881 } else if (!STRNCMP(buf, "exit")) {
2882 if (prefs_common.clean_on_exit && !prefs_common.ask_on_clean) {
2883 procmsg_empty_all_trash();
2885 app_will_exit(NULL, mainwin);
2887 fd_close(sock);
2891 static void open_compose_new(const gchar *address, GList *attach_files)
2893 gchar *addr = NULL;
2895 if (address) {
2896 Xstrdup_a(addr, address, return);
2897 g_strstrip(addr);
2900 compose_new(NULL, addr, attach_files);
2903 static void send_queue(void)
2905 GList *list;
2906 gchar *errstr = NULL;
2907 gboolean error = FALSE;
2908 for (list = folder_get_list(); list != NULL; list = list->next) {
2909 Folder *folder = list->data;
2911 if (folder->queue) {
2912 gint res = procmsg_send_queue
2913 (folder->queue, prefs_common.savemsg,
2914 &errstr);
2916 if (res) {
2917 folder_item_scan(folder->queue);
2920 if (res < 0)
2921 error = TRUE;
2924 if (errstr) {
2925 alertpanel_error_log(_("Some errors occurred "
2926 "while sending queued messages:\n%s"), errstr);
2927 g_free(errstr);
2928 } else if (error) {
2929 alertpanel_error_log("Some errors occurred "
2930 "while sending queued messages.");
2934 #ifndef G_OS_WIN32
2935 static void quit_signal_handler(int sig)
2937 debug_print("Quitting on signal %d\n", sig);
2939 g_timeout_add(0, clean_quit, NULL);
2941 #endif
2943 static void install_basic_sighandlers()
2945 #ifndef G_OS_WIN32
2946 sigset_t mask;
2947 struct sigaction act;
2949 sigemptyset(&mask);
2951 #ifdef SIGTERM
2952 sigaddset(&mask, SIGTERM);
2953 #endif
2954 #ifdef SIGINT
2955 sigaddset(&mask, SIGINT);
2956 #endif
2957 #ifdef SIGHUP
2958 sigaddset(&mask, SIGHUP);
2959 #endif
2961 act.sa_handler = quit_signal_handler;
2962 act.sa_mask = mask;
2963 act.sa_flags = 0;
2965 #ifdef SIGTERM
2966 sigaction(SIGTERM, &act, 0);
2967 #endif
2968 #ifdef SIGINT
2969 sigaction(SIGINT, &act, 0);
2970 #endif
2971 #ifdef SIGHUP
2972 sigaction(SIGHUP, &act, 0);
2973 #endif
2975 sigprocmask(SIG_UNBLOCK, &mask, 0);
2976 #endif /* !G_OS_WIN32 */
2979 #if (defined linux && defined SIGIO)
2980 static int mem_notify_fd = 0;
2982 static gboolean clean_caches(gpointer unused)
2984 if (static_mainwindow && static_mainwindow->lock_count > 0)
2985 return TRUE;
2986 debug_print("/dev/mem_notify: callback: Freeing some memory now!\n");
2987 folder_clean_cache_memory_force();
2988 return FALSE;
2991 static void memory_signal_handler(int sig)
2993 debug_print("/dev/mem_notify: Kernel says we should free up some memory!\n");
2994 g_timeout_add(10, clean_caches, NULL);
2997 static void install_memory_sighandler()
2999 sigset_t mask;
3000 struct sigaction act;
3001 int flags;
3003 mem_notify_fd = g_open("/dev/mem_notify", O_RDONLY|O_NONBLOCK, 0);
3004 if (mem_notify_fd == -1) {
3005 debug_print("/dev/mem_notify not available (%s)\n",
3006 g_strerror(errno));
3007 return;
3010 fcntl(mem_notify_fd, F_SETOWN, getpid());
3011 flags = fcntl(mem_notify_fd, F_GETFL);
3012 fcntl(mem_notify_fd, flags|FASYNC);
3014 sigemptyset(&mask);
3016 sigaddset(&mask, SIGIO);
3018 act.sa_handler = memory_signal_handler;
3019 act.sa_mask = mask;
3020 act.sa_flags = 0;
3022 sigaction(SIGIO, &act, 0);
3024 sigprocmask(SIG_UNBLOCK, &mask, 0);
3026 debug_print("/dev/mem_notify: installed handler\n");
3028 #endif /* linux && SIGIO */
3030 #ifdef HAVE_NETWORKMANAGER_SUPPORT
3031 static void networkmanager_state_change_cb(DBusGProxy *proxy, gchar *dev,
3032 gpointer data)
3034 MainWindow *mainWin;
3036 mainWin = NULL;
3037 if (static_mainwindow)
3038 mainWin = static_mainwindow;
3039 else if (data)
3040 mainWin = (MainWindow*)data;
3042 if (!prefs_common.use_networkmanager)
3043 return;
3045 if (mainWin) {
3046 GError *error = NULL;
3047 gboolean online;
3049 online = networkmanager_is_online(&error);
3050 if(!error) {
3051 if(online && went_offline_nm) {
3052 went_offline_nm = FALSE;
3053 main_window_toggle_work_offline(mainWin, FALSE, FALSE);
3054 debug_print("NetworkManager: Went online\n");
3055 log_message(LOG_PROTOCOL, _("NetworkManager: network is online.\n"));
3057 else if(!online) {
3058 went_offline_nm = TRUE;
3059 main_window_toggle_work_offline(mainWin, TRUE, FALSE);
3060 debug_print("NetworkManager: Went offline\n");
3061 log_message(LOG_PROTOCOL, _("NetworkManager: network is offline.\n"));
3064 else {
3065 debug_print("Failed to get online information from NetworkManager: %s\n",
3066 error->message);
3067 g_error_free(error);
3070 else
3071 debug_print("NetworkManager: Cannot change connection state because "
3072 "main window does not exist\n");
3075 /* Returns true (and sets error appropriately, if given) in case of error */
3076 gboolean networkmanager_is_online(GError **error)
3078 DBusGConnection *connection;
3079 DBusGProxy *proxy;
3080 GError *tmp_error = NULL;
3081 gboolean retVal;
3082 guint32 state;
3084 if (!prefs_common.use_networkmanager)
3085 return TRUE;
3087 tmp_error = NULL;
3088 proxy = NULL;
3089 connection = dbus_g_bus_get(DBUS_BUS_SYSTEM, &tmp_error);
3091 if(!connection) {
3092 /* If calling code doesn't do error checking, at least print some debug */
3093 if((error == NULL) || (*error == NULL))
3094 debug_print("Failed to open connection to system bus: %s\n",
3095 tmp_error->message);
3096 g_propagate_error(error, tmp_error);
3097 return TRUE;
3100 proxy = dbus_g_proxy_new_for_name(connection,
3101 "org.freedesktop.NetworkManager",
3102 "/org/freedesktop/NetworkManager",
3103 "org.freedesktop.NetworkManager");
3105 retVal = dbus_g_proxy_call(proxy,"state",&tmp_error, G_TYPE_INVALID,
3106 G_TYPE_UINT, &state, G_TYPE_INVALID);
3108 if(proxy)
3109 g_object_unref(proxy);
3110 if(connection)
3111 dbus_g_connection_unref(connection);
3113 if(!retVal) {
3114 /* If calling code doesn't do error checking, at least print some debug */
3115 if((error == NULL) || (*error == NULL))
3116 debug_print("Failed to get state info from NetworkManager: %s\n",
3117 tmp_error->message);
3118 g_propagate_error(error, tmp_error);
3119 return TRUE;
3121 return (state == NM_STATE_CONNECTED_LOCAL ||
3122 state == NM_STATE_CONNECTED_SITE ||
3123 state == NM_STATE_CONNECTED_GLOBAL ||
3124 state == NM_STATE_UNKNOWN);
3126 #endif