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