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