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