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