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