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