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