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