7c90a39aea3623c78a235f091ef267fba5124479
[modest] / src / modest-tny-account-store.c
1 /* Copyright (c) 2006, Nokia Corporation
2  * All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
8  * * Redistributions of source code must retain the above copyright
9  *   notice, this list of conditions and the following disclaimer.
10  * * Redistributions in binary form must reproduce the above copyright
11  *   notice, this list of conditions and the following disclaimer in the
12  *   documentation and/or other materials provided with the distribution.
13  * * Neither the name of the Nokia Corporation nor the names of its
14  *   contributors may be used to endorse or promote products derived from
15  *   this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
18  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
19  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
20  * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
21  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #include <string.h>
31 #include <glib/gi18n.h>
32
33 #include <tny-account.h>
34 #include <tny-account-store.h>
35 #include <tny-store-account.h>
36 #include <tny-error.h>
37 #include <tny-transport-account.h>
38 #include <tny-simple-list.h>
39 #include <tny-account-store.h>
40 #include <tny-camel-transport-account.h>
41 #include <tny-camel-imap-store-account.h>
42 #include <tny-camel-pop-store-account.h>
43
44 #include <modest-runtime.h>
45 #include <modest-marshal.h>
46 #include <modest-protocol-info.h>
47 #include <modest-local-folder-info.h>
48 #include <modest-tny-account.h>
49 #include <modest-tny-local-folders-account.h>
50 #include <modest-account-mgr.h>
51 #include <modest-account-mgr-helpers.h>
52 #include <widgets/modest-window-mgr.h>
53 #include <modest-account-settings-dialog.h>
54 #include <maemo/modest-maemo-utils.h>
55
56
57 #include "modest-tny-account-store.h"
58 #include "modest-tny-platform-factory.h"
59 #include <tny-gtk-lockable.h>
60 #include <camel/camel.h>
61
62 #ifdef MODEST_PLATFORM_MAEMO
63 #include <tny-maemo-conic-device.h>
64 #ifdef MODEST_HAVE_HILDON0_WIDGETS
65 #include <hildon-widgets/hildon-note.h>
66 #include <hildon-widgets/hildon-banner.h>
67 #else
68 #include <hildon/hildon-note.h>
69 #include <hildon/hildon-banner.h>
70 #endif
71 #endif
72
73 #include <libgnomevfs/gnome-vfs-volume-monitor.h>
74
75 /* 'private'/'protected' functions */
76 static void    modest_tny_account_store_class_init   (ModestTnyAccountStoreClass *klass);
77
78 static void    modest_tny_account_store_finalize     (GObject *obj);
79
80 static void    modest_tny_account_store_instance_init (ModestTnyAccountStore *obj);
81
82 static void    modest_tny_account_store_init          (gpointer g, gpointer iface_data);
83
84 static void    modest_tny_account_store_base_init     (gpointer g_class);
85
86 static void    on_account_inserted         (ModestAccountMgr *acc_mgr, 
87                                             const gchar *account,
88                                             gpointer user_data);
89
90 static void    add_existing_accounts       (ModestTnyAccountStore *self);
91
92 static void    insert_account              (ModestTnyAccountStore *self,
93                                             const gchar *account,
94                                             gboolean notify);
95
96 static void    on_account_removed          (ModestAccountMgr *acc_mgr, 
97                                             const gchar *account,
98                                             gpointer user_data);
99
100 static gchar*  get_password                (TnyAccount *account, 
101                                             const gchar * prompt_not_used, 
102                                             gboolean *cancel);
103
104 static void    forget_password             (TnyAccount *account);
105
106 static void    on_vfs_volume_mounted       (GnomeVFSVolumeMonitor *volume_monitor, 
107                                             GnomeVFSVolume *volume, 
108                                             gpointer user_data);
109
110 static void    on_vfs_volume_unmounted     (GnomeVFSVolumeMonitor *volume_monitor, 
111                                             GnomeVFSVolume *volume, 
112                                             gpointer user_data);
113
114 static void    modest_tny_account_store_forget_password_in_memory (ModestTnyAccountStore *self, 
115                                                                    const gchar *server_account_name);
116
117 static void    add_connection_specific_transport_accounts         (ModestTnyAccountStore *self,
118                                                                    const gchar *account_name);
119
120 /* list my signals */
121 enum {
122         ACCOUNT_CHANGED_SIGNAL,
123         ACCOUNT_INSERTED_SIGNAL,
124         ACCOUNT_REMOVED_SIGNAL,
125
126         PASSWORD_REQUESTED_SIGNAL,
127         LAST_SIGNAL
128 };
129
130 typedef struct _ModestTnyAccountStorePrivate ModestTnyAccountStorePrivate;
131 struct _ModestTnyAccountStorePrivate {
132         gchar              *cache_dir;  
133         GHashTable         *password_hash;
134         GHashTable         *account_settings_dialog_hash;
135         ModestAccountMgr   *account_mgr;
136         TnySessionCamel    *session;
137         TnyDevice          *device;
138
139         gulong acc_inserted_handler;
140         gulong acc_changed_handler;
141         gulong acc_removed_handler;
142         gulong volume_mounted_handler;
143         gulong volume_unmounted_handler;
144         
145         /* We cache the lists of accounts here */
146         TnyList             *store_accounts;
147         TnyList             *transport_accounts;
148         TnyList             *store_accounts_outboxes;
149 };
150
151 #define MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(o)      (G_TYPE_INSTANCE_GET_PRIVATE((o), \
152                                                       MODEST_TYPE_TNY_ACCOUNT_STORE, \
153                                                       ModestTnyAccountStorePrivate))
154
155 /* globals */
156 static GObjectClass *parent_class = NULL;
157
158 static guint signals[LAST_SIGNAL] = {0};
159
160 GType
161 modest_tny_account_store_get_type (void)
162 {
163         static GType my_type = 0;
164
165         if (!my_type) {
166                 static const GTypeInfo my_info = {
167                         sizeof(ModestTnyAccountStoreClass),
168                         modest_tny_account_store_base_init,     /* base init */
169                         NULL,           /* base finalize */
170                         (GClassInitFunc) modest_tny_account_store_class_init,
171                         NULL,           /* class finalize */
172                         NULL,           /* class data */
173                         sizeof(ModestTnyAccountStore),
174                         0,              /* n_preallocs */
175                         (GInstanceInitFunc) modest_tny_account_store_instance_init,
176                         NULL
177                 };
178
179                 static const GInterfaceInfo iface_info = {
180                         (GInterfaceInitFunc) modest_tny_account_store_init,
181                         NULL,         /* interface_finalize */
182                         NULL          /* interface_data */
183                 };
184                 /* hack hack */
185                 my_type = g_type_register_static (G_TYPE_OBJECT,
186                                                   "ModestTnyAccountStore",
187                                                   &my_info, 0);
188                 g_type_add_interface_static (my_type, TNY_TYPE_ACCOUNT_STORE,
189                                              &iface_info);
190         }
191         return my_type;
192 }
193
194
195 static void
196 modest_tny_account_store_base_init (gpointer g_class)
197 {
198         static gboolean tny_account_store_initialized = FALSE;
199
200         if (!tny_account_store_initialized) {
201
202                 signals[ACCOUNT_CHANGED_SIGNAL] =
203                         g_signal_new ("account_changed",
204                                       MODEST_TYPE_TNY_ACCOUNT_STORE,
205                                       G_SIGNAL_RUN_FIRST,
206                                       G_STRUCT_OFFSET (ModestTnyAccountStoreClass, account_changed),
207                                       NULL, NULL,
208                                       g_cclosure_marshal_VOID__OBJECT,
209                                       G_TYPE_NONE, 1, TNY_TYPE_ACCOUNT);
210
211                 signals[ACCOUNT_INSERTED_SIGNAL] =
212                         g_signal_new ("account_inserted",
213                                       MODEST_TYPE_TNY_ACCOUNT_STORE,
214                                       G_SIGNAL_RUN_FIRST,
215                                       G_STRUCT_OFFSET (ModestTnyAccountStoreClass, account_inserted),
216                                       NULL, NULL,
217                                       g_cclosure_marshal_VOID__OBJECT,
218                                       G_TYPE_NONE, 1, TNY_TYPE_ACCOUNT);
219                 
220                 signals[ACCOUNT_REMOVED_SIGNAL] =
221                         g_signal_new ("account_removed",
222                                       MODEST_TYPE_TNY_ACCOUNT_STORE,
223                                       G_SIGNAL_RUN_FIRST,
224                                       G_STRUCT_OFFSET (ModestTnyAccountStoreClass, account_removed),
225                                       NULL, NULL,
226                                       g_cclosure_marshal_VOID__OBJECT,
227                                       G_TYPE_NONE, 1, TNY_TYPE_ACCOUNT);
228                 
229 /*              signals[TNY_ACCOUNT_STORE_CONNECTING_FINISHED] = */
230 /*                      g_signal_new ("connecting_finished", */
231 /*                                    TNY_TYPE_ACCOUNT_STORE, */
232 /*                                    G_SIGNAL_RUN_FIRST, */
233 /*                                    G_STRUCT_OFFSET (TnyAccountStoreIface, connecting_finished), */
234 /*                                    NULL, NULL, */
235 /*                                    g_cclosure_marshal_VOID__VOID,  */
236 /*                                    G_TYPE_NONE, 0); */
237
238                 signals[PASSWORD_REQUESTED_SIGNAL] =
239                         g_signal_new ("password_requested",
240                                       MODEST_TYPE_TNY_ACCOUNT_STORE,
241                                       G_SIGNAL_RUN_FIRST,
242                                       G_STRUCT_OFFSET(ModestTnyAccountStoreClass, password_requested),
243                                       NULL, NULL,
244                                       modest_marshal_VOID__STRING_POINTER_POINTER_POINTER_POINTER,
245                                       G_TYPE_NONE, 5, G_TYPE_STRING, G_TYPE_POINTER, G_TYPE_POINTER, G_TYPE_POINTER,
246                                       G_TYPE_POINTER);          
247
248                 tny_account_store_initialized = TRUE;
249         }
250 }
251
252
253 static void
254 modest_tny_account_store_class_init (ModestTnyAccountStoreClass *klass)
255 {
256         GObjectClass *gobject_class;
257         gobject_class = (GObjectClass*) klass;
258
259         parent_class            = g_type_class_peek_parent (klass);
260         gobject_class->finalize = modest_tny_account_store_finalize;
261
262         g_type_class_add_private (gobject_class,
263                                   sizeof(ModestTnyAccountStorePrivate));
264 }
265      
266 static void
267 modest_tny_account_store_instance_init (ModestTnyAccountStore *obj)
268 {
269         GnomeVFSVolumeMonitor* monitor = NULL;
270         ModestTnyAccountStorePrivate *priv;
271
272         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(obj);
273
274         priv->cache_dir              = NULL;
275         priv->account_mgr            = NULL;
276         priv->session                = NULL;
277         priv->device                 = NULL;
278         
279         /* An in-memory store of passwords, 
280          * for passwords that are not remembered in the configuration,
281          * so they need to be asked for from the user once in each session:
282          */
283         priv->password_hash = g_hash_table_new_full (g_str_hash, g_str_equal,
284                                                      g_free, g_free);
285                                                              
286         /* A hash-map of modest account names to dialog pointers,
287          * so we can avoid showing the account settings twice for the same modest account: */                                 
288         priv->account_settings_dialog_hash = g_hash_table_new_full (g_str_hash, g_str_equal, 
289                                                                     g_free, NULL);
290                                                               
291         /* Respond to volume mounts and unmounts, such 
292          * as the insertion/removal of the memory card: */
293         monitor = gnome_vfs_get_volume_monitor();
294
295         priv->volume_mounted_handler = g_signal_connect (G_OBJECT(monitor), 
296                                                          "volume-mounted",
297                                                          G_CALLBACK(on_vfs_volume_mounted),
298                                                          obj);
299
300         priv->volume_unmounted_handler = g_signal_connect (G_OBJECT(monitor), "volume-unmounted",
301                                                            G_CALLBACK(on_vfs_volume_unmounted),
302                                                            obj);
303 }
304
305 /* disconnect the list of TnyAccounts */
306 static void
307 foreach_account_disconnect (gpointer data, 
308                             gpointer user_data)
309 {
310         tny_camel_account_set_online (TNY_CAMEL_ACCOUNT(data), FALSE, NULL);
311 }
312
313
314 static void
315 foreach_account_append_to_list (gpointer data, 
316                                 gpointer user_data)
317 {
318         TnyList *list;
319
320         list = TNY_LIST (user_data);
321         tny_list_append (list, G_OBJECT (data));
322 }
323
324 /********************************************************************/
325 /*           Control the state of the MMC local account             */
326 /********************************************************************/
327 static void
328 on_vfs_volume_mounted(GnomeVFSVolumeMonitor *volume_monitor, 
329                       GnomeVFSVolume *volume, 
330                       gpointer user_data)
331 {
332         ModestTnyAccountStore *self;
333         ModestTnyAccountStorePrivate *priv;
334  
335         gchar *uri = NULL;
336
337         self = MODEST_TNY_ACCOUNT_STORE(user_data);
338         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
339         
340         /* Check whether this was the external MMC1 card: */
341         uri = gnome_vfs_volume_get_activation_uri (volume);
342
343         if (uri && (!strcmp (uri, MODEST_MCC1_VOLUMEPATH_URI))) {
344                 TnyAccount *mmc_account;
345
346                 mmc_account = modest_tny_account_new_for_local_folders (priv->account_mgr, 
347                                                                         priv->session, 
348                                                                         MODEST_MCC1_VOLUMEPATH);
349
350                 /* Add to the list of store accounts */
351                 tny_list_append (priv->store_accounts, G_OBJECT (mmc_account));
352
353                 g_signal_emit (G_OBJECT (self), 
354                                signals [ACCOUNT_INSERTED_SIGNAL],
355                                0, mmc_account);
356                 /* Free */
357                 g_object_unref (mmc_account);
358         }
359         g_free (uri);
360 }
361
362 static void
363 on_vfs_volume_unmounted(GnomeVFSVolumeMonitor *volume_monitor, 
364                         GnomeVFSVolume *volume, 
365                         gpointer user_data)
366 {
367         ModestTnyAccountStore *self;
368         ModestTnyAccountStorePrivate *priv;
369         gchar *uri = NULL;
370
371         self = MODEST_TNY_ACCOUNT_STORE(user_data);
372         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
373         
374         /* Check whether this was the external MMC1 card: */
375         uri = gnome_vfs_volume_get_activation_uri (volume);
376         if (uri && (strcmp (uri, MODEST_MCC1_VOLUMEPATH_URI) == 0)) {
377                 TnyAccount *mmc_account = NULL;
378                 gboolean found = FALSE;
379                 TnyIterator *iter = NULL;
380
381                 iter = tny_list_create_iterator (priv->store_accounts);
382                 while (!tny_iterator_is_done (iter) && !found) {
383                         TnyAccount *account;
384
385                         account = TNY_ACCOUNT (tny_iterator_get_current (iter));
386                         if (modest_tny_account_is_memory_card_account (account)) {
387                                 found = TRUE;
388                                 mmc_account = g_object_ref (account);
389                         }
390                         g_object_unref (account);
391                         tny_iterator_next (iter);
392                 }
393                 g_object_unref (iter);
394
395                 if (found) {
396                         /* Remove from the list */
397                         tny_list_remove (priv->store_accounts, G_OBJECT (mmc_account));
398                        
399                         /* Notify observers */
400                         g_signal_emit (G_OBJECT (self),
401                                        signals [ACCOUNT_REMOVED_SIGNAL],
402                                        0, mmc_account);
403
404                         g_object_unref (mmc_account);
405                 } else {
406                         g_warning ("%s: there was no store account for the unmounted MMC",
407                                    __FUNCTION__);
408                 }
409         }
410         g_free (uri);
411 }
412
413 /**
414  * modest_tny_account_store_forget_password_in_memory
415  * @self: a TnyAccountStore instance
416  * @account: A server account.
417  * 
418  * Forget any password stored in memory for this account.
419  * For instance, this should be called when the user has changed the password in the account settings.
420  */
421 static void
422 modest_tny_account_store_forget_password_in_memory (ModestTnyAccountStore *self, const gchar * server_account_name)
423 {
424         /* printf ("DEBUG: %s\n", __FUNCTION__); */
425         ModestTnyAccountStorePrivate *priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
426
427         if (server_account_name && priv->password_hash) {
428                 g_hash_table_remove (priv->password_hash, server_account_name);
429         }
430 }
431
432
433 static gboolean
434 update_tny_account_for_account (ModestTnyAccountStore *self, ModestAccountMgr *acc_mgr,
435                                 const gchar *account_name, TnyAccountType type)
436 {
437         ModestTnyAccountStorePrivate *priv;
438         TnyList* account_list;
439         gboolean found = FALSE;
440         TnyIterator *iter = NULL;
441
442         g_return_val_if_fail (self, FALSE);
443         g_return_val_if_fail (account_name, FALSE);
444         g_return_val_if_fail (type == TNY_ACCOUNT_TYPE_STORE || 
445                               type == TNY_ACCOUNT_TYPE_TRANSPORT,
446                               FALSE);
447
448         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
449         account_list = (type == TNY_ACCOUNT_TYPE_STORE ? priv->store_accounts : priv->transport_accounts);
450         
451         iter = tny_list_create_iterator (account_list);
452         while (!tny_iterator_is_done (iter) && !found) {
453                 TnyAccount *tny_account;
454                 tny_account = TNY_ACCOUNT (tny_iterator_get_current (iter));
455                 if (tny_account) {
456                         const gchar* parent_name =
457                                 modest_tny_account_get_parent_modest_account_name_for_server_account (tny_account);
458                         if (parent_name && strcmp (parent_name, account_name) == 0) {
459                                 found = TRUE;
460                                 modest_tny_account_update_from_account (tny_account, acc_mgr, account_name, type);
461                                 g_signal_emit (G_OBJECT(self), signals[ACCOUNT_CHANGED_SIGNAL], 0, tny_account);
462                         }
463                         g_object_unref (tny_account);
464                 }
465                 tny_iterator_next (iter);
466         }
467
468         if (iter)
469                 g_object_unref (iter);
470         
471         return found;
472 }
473
474
475 static void
476 on_account_changed (ModestAccountMgr *acc_mgr, 
477                     const gchar *account_name,
478                     const gchar *key, 
479                     gboolean server_account, 
480                     gpointer user_data)
481 {
482         printf ("DEBUG: modest: %s\n", __FUNCTION__);
483         
484         ModestTnyAccountStore *self = MODEST_TNY_ACCOUNT_STORE(user_data);
485         
486         /* Ignore the change if it's a change in the last_updated value */
487         if (key && g_str_has_suffix ((const gchar *) key, MODEST_ACCOUNT_LAST_UPDATED))
488                 return;
489         
490         if (!server_account && FALSE) { /* FIXME FALSE: turned off for now */
491                 if (!update_tny_account_for_account (self, acc_mgr, account_name, TNY_ACCOUNT_TYPE_STORE))
492                         g_warning ("%s: failed to update store account for %s", __FUNCTION__, account_name);
493                 if (!update_tny_account_for_account (self, acc_mgr, account_name, TNY_ACCOUNT_TYPE_TRANSPORT))
494                         g_warning ("%s: failed to update transport account for %s", __FUNCTION__, account_name);
495         }
496
497         /* TODO: This doesn't actually work, because
498          * a) The account name is not sent correctly per key:
499          * b) We should test the end of the key, not the whole keym
500          * c) We don't seem to be getting all keys here.
501          * Instead, we just forget the password for all accounts when we create them,
502          * for now.
503          */
504 }
505
506 static void 
507 on_account_settings_hide (GtkWidget *widget, gpointer user_data)
508 {
509         TnyAccount *account = (TnyAccount*)user_data;
510         
511         /* This is easier than using a struct for the user_data: */
512         ModestTnyAccountStore *self = modest_runtime_get_account_store();
513         ModestTnyAccountStorePrivate *priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
514         
515         const gchar *modest_account_name = 
516                         modest_tny_account_get_parent_modest_account_name_for_server_account (account);
517         if (modest_account_name)
518                 g_hash_table_remove (priv->account_settings_dialog_hash, modest_account_name);
519 }
520
521 static gboolean 
522 on_idle_wrong_password_warning_only (gpointer user_data)
523 {
524         gdk_threads_enter();
525         
526         ModestWindow *main_window = 
527                                 modest_window_mgr_get_main_window (modest_runtime_get_window_mgr ());
528                                 
529         /* Show an explanatory temporary banner: */
530         hildon_banner_show_information ( 
531                 GTK_WIDGET(main_window), NULL, _("mcen_ib_username_pw_incorrect"));
532                 
533         gdk_threads_leave();
534         
535         return FALSE; /* Don't show again. */
536 }
537                 
538 static gboolean 
539 on_idle_wrong_password (gpointer user_data)
540
541         TnyAccount *account = (TnyAccount*)user_data;
542         /* This is easier than using a struct for the user_data: */
543         ModestTnyAccountStore *self = modest_runtime_get_account_store();
544         ModestTnyAccountStorePrivate *priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
545         
546         const gchar *modest_account_name = 
547                         modest_tny_account_get_parent_modest_account_name_for_server_account (account);
548         if (!modest_account_name) {
549                 g_warning ("%s: modest_tny_account_get_parent_modest_account_name_for_server_account() failed.\n", 
550                         __FUNCTION__);
551                         
552                 g_object_unref (account);
553                 return FALSE;
554         }
555         
556         
557         /* Check whether this window is already open,
558          * for instance because of a previous get_password() call: 
559          */
560         gpointer dialog_as_gpointer = NULL;
561         gboolean found = FALSE;
562         if (priv->account_settings_dialog_hash) {
563                 found = g_hash_table_lookup_extended (priv->account_settings_dialog_hash,
564                         modest_account_name, NULL, (gpointer*)&dialog_as_gpointer);
565         }
566         ModestAccountSettingsDialog *dialog = dialog_as_gpointer;
567                                         
568         ModestWindow *main_window = 
569                                 modest_window_mgr_get_main_window (modest_runtime_get_window_mgr ());
570
571         gdk_threads_enter ();
572         gboolean created_dialog = FALSE;
573         if (!found || !dialog) {
574                 dialog = modest_account_settings_dialog_new ();
575                 modest_account_settings_dialog_set_account_name (dialog, modest_account_name);
576                 modest_account_settings_dialog_switch_to_user_info (dialog);
577                 
578                 g_hash_table_insert (priv->account_settings_dialog_hash, g_strdup (modest_account_name), dialog);
579                 
580                 created_dialog = TRUE;
581         }
582         
583         /* Show an explanatory temporary banner: */
584         hildon_banner_show_information ( 
585                 GTK_WIDGET(dialog), NULL, _("mcen_ib_username_pw_incorrect"));
586                 
587         if (created_dialog) {
588                 /* Forget it when it closes: */
589                 g_signal_connect_object (G_OBJECT (dialog), "hide", G_CALLBACK (on_account_settings_hide), 
590                         account, 0);
591                         
592                 /* Show it and delete it when it closes: */
593                 modest_maemo_show_dialog_and_forget (GTK_WINDOW (main_window), GTK_DIALOG (dialog));
594         }
595         else {
596                 /* Just show it instead of showing it and deleting it when it closes,
597                  * though it is probably open already: */
598                 gtk_window_present (GTK_WINDOW (dialog));
599         }
600         
601         g_object_unref (account);
602         gdk_threads_leave ();
603         
604         return FALSE; /* Dont' call this again. */
605 }
606
607 typedef struct 
608 {
609         GMainLoop *loop;
610         ModestTnyAccountStore* account_store;
611         const gchar* server_account_id;
612         gchar **username;
613         gchar **password;
614         gboolean *cancel;
615         gboolean *remember;
616 } IdlePasswordRequest;
617
618 static gboolean 
619 on_idle_request_password (gpointer user_data)
620 {
621         gdk_threads_enter();
622         
623         IdlePasswordRequest* info = (IdlePasswordRequest*)user_data;
624         g_signal_emit (G_OBJECT(info->account_store), signals[PASSWORD_REQUESTED_SIGNAL], 0,
625                                info->server_account_id, /* server_account_name */
626                                info->username, info->password, info->cancel, info->remember);
627                                
628         if (info->loop)
629                 g_main_loop_quit (info->loop);
630         
631         gdk_threads_leave();
632         
633         return FALSE; /* Don't call again. */
634 }
635
636 static void
637 request_password_in_main_loop_and_wait (ModestTnyAccountStore *account_store, 
638                                          const gchar* server_account_id,
639                                          gchar **username,
640                                          gchar **password,
641                                          gboolean *cancel, 
642                                          gboolean *remember)
643 {
644         IdlePasswordRequest *data = g_slice_new0 (IdlePasswordRequest);
645         data->account_store = account_store;
646         data->server_account_id = server_account_id;
647         data->username = username;
648         data->password = password;
649         data->cancel = cancel;
650         data->remember = remember;
651
652         data->loop = g_main_loop_new (NULL, FALSE /* not running */);
653         
654         /* Cause the function to be run in an idle-handler, which is always 
655          * in the main thread:
656          */
657         g_idle_add (&on_idle_request_password, data);
658         
659         /* This main loop will run until the idle handler has stopped it: */
660         printf ("DEBUG: %s: before g_main_loop_run()\n", __FUNCTION__);
661         GDK_THREADS_LEAVE();
662         g_main_loop_run (data->loop);
663         GDK_THREADS_ENTER();
664         printf ("DEBUG: %s: after g_main_loop_run()\n", __FUNCTION__);
665         printf ("DEBUG: %s: Finished\n", __FUNCTION__);
666         g_main_loop_unref (data->loop);
667
668         g_slice_free (IdlePasswordRequest, data);
669 }
670
671 /* This callback will be called by Tinymail when it needs the password
672  * from the user or the account settings.
673  * It can also call forget_password() before calling this,
674  * so that we clear wrong passwords out of our account settings.
675  * Note that TnyAccount here will be the server account. */
676 static gchar*
677 get_password (TnyAccount *account, const gchar * prompt_not_used, gboolean *cancel)
678 {
679         /* TODO: Settting cancel to FALSE does not actually cancel everything.
680          * We still get multiple requests afterwards, so we end up showing the 
681          * same dialogs repeatedly.
682          */
683          
684         printf ("DEBUG: modest: %s: prompt (not shown) = %s\n", __FUNCTION__, prompt_not_used);
685           
686         g_return_val_if_fail (account, NULL);
687           
688         const TnyAccountStore *account_store = NULL;
689         ModestTnyAccountStore *self = NULL;
690         ModestTnyAccountStorePrivate *priv;
691         gchar *username = NULL;
692         gchar *pwd = NULL;
693         gpointer pwd_ptr = NULL;
694         gboolean already_asked = FALSE;
695
696         /* Initialize the output parameter: */
697         if (cancel)
698                 *cancel = FALSE;
699                 
700         const gchar *server_account_name = tny_account_get_id (account);
701         account_store = TNY_ACCOUNT_STORE(g_object_get_data (G_OBJECT(account),
702                                                              "account_store"));
703
704         if (!server_account_name || !account_store) {
705                 g_warning ("modest: %s: could not retrieve account_store for account %s",
706                            __FUNCTION__, server_account_name ? server_account_name : "<NULL>");
707                 if (cancel)
708                         *cancel = TRUE;
709                 
710                 return NULL;
711         }
712
713         self = MODEST_TNY_ACCOUNT_STORE (account_store);
714         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
715         
716         /* This hash map stores passwords, including passwords that are not stored in gconf. */
717         /* Is it in the hash? if it's already there, it must be wrong... */
718         pwd_ptr = (gpointer)&pwd; /* pwd_ptr so the compiler does not complained about
719                                    * type-punned ptrs...*/
720         already_asked = priv->password_hash && 
721                                 g_hash_table_lookup_extended (priv->password_hash,
722                                                       server_account_name,
723                                                       NULL,
724                                                       (gpointer*)&pwd_ptr);
725                                                       
726         printf ("DEBUG: modest: %s: Already asked = %d\n", __FUNCTION__, already_asked);
727
728         /* If the password is not already there, try ModestConf */
729         if (!already_asked) {
730                 pwd  = modest_server_account_get_password (priv->account_mgr,
731                                                       server_account_name);
732                 g_hash_table_insert (priv->password_hash, g_strdup (server_account_name), g_strdup (pwd));
733         }
734
735         /* If it was already asked, it must have been wrong, so ask again */
736         if (already_asked || !pwd || strlen(pwd) == 0) {
737                 /* As per the UI spec, if no password was set in the account settings, 
738                  * ask for it now. But if the password is wrong in the account settings, 
739                  * then show a banner and the account settings dialog so it can be corrected:
740                  */
741                 const gboolean settings_have_password = 
742                         modest_server_account_get_has_password (priv->account_mgr, server_account_name);
743                 printf ("DEBUG: modest: %s: settings_have_password=%d\n", __FUNCTION__, settings_have_password);
744                 if (settings_have_password) {
745         
746                         
747                         /* The password must be wrong, so show the account settings dialog so it can be corrected: */
748                         /* We show it in the main loop, because this function might not be in the main loop. */
749                         g_object_ref (account); /* unrefed in the idle handler. */
750                         g_idle_add (on_idle_wrong_password, account);
751                         
752                         if (cancel)
753                                 *cancel = TRUE;
754                                 
755                         return NULL;
756                 }
757         
758                 /* we don't have it yet. Get the password from the user */
759                 const gchar* account_id = tny_account_get_id (account);
760                 gboolean remember = FALSE;
761                 pwd = NULL;
762                 
763                 if (already_asked) {
764                         /* Show an info banner, before we show the protected password dialog: */
765                         g_idle_add (on_idle_wrong_password_warning_only, NULL);
766                 }
767                 
768                 request_password_in_main_loop_and_wait (self, account_id, 
769                                &username, &pwd, cancel, &remember);
770                 
771                 if (!*cancel) {
772                         /* The password will be returned as the result,
773                          * but we need to tell tinymail about the username too: */
774                         tny_account_set_user (account, username);
775                         
776                         /* Do not save the password in gconf, 
777                          * because the UI spec says "The password will never be saved in the account": */
778                         /*
779                         if (remember) {
780                                 printf ("%s: Storing username=%s, password=%s\n", 
781                                         __FUNCTION__, username, pwd);
782                                 modest_server_account_set_username (priv->account_mgr, server_account_name,
783                                                                username);
784                                 modest_server_account_set_password (priv->account_mgr, server_account_name,
785                                                                pwd);
786                         }
787                         */
788
789                         /* We need to dup the string even knowing that
790                            it's already a dup of the contents of an
791                            entry, because it if it's wrong, then camel
792                            will free it */
793                         g_hash_table_insert (priv->password_hash, g_strdup (server_account_name), g_strdup(pwd));
794                 } else {
795                         g_hash_table_remove (priv->password_hash, server_account_name);
796                         
797                         g_free (pwd);
798                         pwd = NULL;
799                 }
800
801                 g_free (username);
802                 username = NULL;
803         } else
804                 *cancel = FALSE;
805  
806     /* printf("  DEBUG: %s: returning %s\n", __FUNCTION__, pwd); */
807         
808         return pwd;
809 }
810
811 /* tinymail calls this if the connection failed due to an incorrect password.
812  * And it seems to call this for any general connection failure. */
813 static void
814 forget_password (TnyAccount *account)
815 {
816         printf ("DEBUG: %s\n", __FUNCTION__);
817         ModestTnyAccountStore *self;
818         ModestTnyAccountStorePrivate *priv;
819         const TnyAccountStore *account_store;
820         gchar *pwd;
821         const gchar *key;
822         
823         account_store = TNY_ACCOUNT_STORE(g_object_get_data (G_OBJECT(account),
824                                                              "account_store"));
825         self = MODEST_TNY_ACCOUNT_STORE (account_store);
826         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
827         key  = tny_account_get_id (account);
828
829         /* Do not remove the key, this will allow us to detect that we
830            have already asked for it at least once */
831         pwd = g_hash_table_lookup (priv->password_hash, key);
832         if (pwd) {
833                 memset (pwd, 0, strlen (pwd));
834                 g_hash_table_insert (priv->password_hash, g_strdup (key), NULL);
835         }
836
837         /* Remove from configuration system */
838         /*
839         modest_account_mgr_unset (priv->account_mgr,
840                                   key, MODEST_ACCOUNT_PASSWORD, TRUE);
841         */
842 }
843
844 static void
845 modest_tny_account_store_finalize (GObject *obj)
846 {
847         GnomeVFSVolumeMonitor *volume_monitor;
848         ModestTnyAccountStore *self        = MODEST_TNY_ACCOUNT_STORE(obj);
849         ModestTnyAccountStorePrivate *priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
850
851         g_free (priv->cache_dir);
852         priv->cache_dir = NULL;
853         
854         if (priv->password_hash) {
855                 g_hash_table_destroy (priv->password_hash);
856                 priv->password_hash = NULL;
857         }
858
859         /* Disconnect VFS signals */
860         volume_monitor = gnome_vfs_get_volume_monitor ();
861         if (g_signal_handler_is_connected (volume_monitor, 
862                                            priv->volume_mounted_handler))
863                 g_signal_handler_disconnect (volume_monitor, 
864                                              priv->volume_mounted_handler);
865         if (g_signal_handler_is_connected (volume_monitor, 
866                                            priv->volume_unmounted_handler))
867                 g_signal_handler_disconnect (volume_monitor, 
868                                              priv->volume_unmounted_handler);
869
870         if (priv->account_mgr) {
871                 /* Disconnect signals */
872                 if (g_signal_handler_is_connected (priv->account_mgr, 
873                                                    priv->acc_inserted_handler))
874                         g_signal_handler_disconnect (priv->account_mgr, 
875                                                      priv->acc_inserted_handler);
876                 if (g_signal_handler_is_connected (priv->account_mgr, 
877                                                    priv->acc_changed_handler))
878                         g_signal_handler_disconnect (priv->account_mgr, 
879                                                      priv->acc_changed_handler);
880                 if (g_signal_handler_is_connected (priv->account_mgr, 
881                                                    priv->acc_removed_handler))
882                         g_signal_handler_disconnect (priv->account_mgr, 
883                                                      priv->acc_removed_handler);
884
885                 g_object_unref (G_OBJECT(priv->account_mgr));
886                 priv->account_mgr = NULL;
887         }
888
889         if (priv->device) {
890                 g_object_unref (G_OBJECT(priv->device));
891                 priv->device = NULL;
892         }
893
894         /* Destroy all accounts. Disconnect all accounts before they are destroyed */
895         if (priv->store_accounts) {
896                 tny_list_foreach (priv->store_accounts, foreach_account_disconnect, NULL);
897                 g_object_unref (priv->store_accounts);
898                 priv->store_accounts = NULL;
899         }
900
901         if (priv->transport_accounts) {
902                 tny_list_foreach (priv->transport_accounts, foreach_account_disconnect, NULL);
903                 g_object_unref (priv->transport_accounts);
904                 priv->transport_accounts = NULL;
905         }
906
907         if (priv->store_accounts_outboxes) {
908                 g_object_unref (priv->store_accounts_outboxes);
909                 priv->store_accounts_outboxes = NULL;
910         }
911                 
912         if (priv->session) {
913                 camel_object_unref (CAMEL_OBJECT(priv->session));
914                 priv->session = NULL;
915         }
916         
917         G_OBJECT_CLASS(parent_class)->finalize (obj);
918 }
919
920
921 ModestTnyAccountStore*
922 modest_tny_account_store_new (ModestAccountMgr *account_mgr, 
923                               TnyDevice *device) 
924 {
925         GObject *obj;
926         ModestTnyAccountStorePrivate *priv;
927         TnyAccount *local_account = NULL;
928         
929         g_return_val_if_fail (account_mgr, NULL);
930         g_return_val_if_fail (device, NULL);
931
932         obj  = G_OBJECT(g_object_new(MODEST_TYPE_TNY_ACCOUNT_STORE, NULL));
933         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(obj);
934
935         priv->account_mgr = g_object_ref (G_OBJECT(account_mgr));
936         priv->device = g_object_ref (device);
937         
938         priv->session = tny_session_camel_new (TNY_ACCOUNT_STORE(obj));
939         if (!priv->session) {
940                 g_warning ("failed to get TnySessionCamel");
941                 return NULL;
942         }
943
944         /* Set the ui locker */ 
945         tny_session_camel_set_ui_locker (priv->session,  tny_gtk_lockable_new ());
946                 
947         /* Connect signals */
948         priv->acc_inserted_handler = g_signal_connect (G_OBJECT(account_mgr), "account_inserted",
949                                                       G_CALLBACK (on_account_inserted), obj);
950         priv->acc_changed_handler = g_signal_connect (G_OBJECT(account_mgr), "account_changed",
951                                                       G_CALLBACK (on_account_changed), obj);
952         priv->acc_removed_handler = g_signal_connect (G_OBJECT(account_mgr), "account_removed",
953                                                       G_CALLBACK (on_account_removed), obj);
954
955         /* Create the lists of accounts */
956         priv->store_accounts = tny_simple_list_new ();
957         priv->transport_accounts = tny_simple_list_new ();
958         priv->store_accounts_outboxes = tny_simple_list_new ();
959
960         /* Create the local folders account */
961         local_account = 
962                 modest_tny_account_new_for_local_folders (priv->account_mgr, priv->session, NULL);
963         tny_list_append (priv->store_accounts, G_OBJECT(local_account));
964         g_object_unref (local_account); 
965
966         /* Add the other remote accounts. Do this before adding the
967            local account, because we need to add our outboxes to the
968            global OUTBOX hosted in the local account */
969         add_existing_accounts (MODEST_TNY_ACCOUNT_STORE (obj));
970
971         return MODEST_TNY_ACCOUNT_STORE(obj);
972 }
973
974 static void
975 modest_tny_account_store_get_accounts  (TnyAccountStore *self, 
976                                         TnyList *list,
977                                         TnyGetAccountsRequestType request_type)
978 {
979         ModestTnyAccountStorePrivate *priv;
980         
981         g_return_if_fail (self);
982         g_return_if_fail (TNY_IS_LIST(list));
983         
984         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
985         
986         switch (request_type) {
987         case TNY_ACCOUNT_STORE_BOTH:
988                 tny_list_foreach (priv->store_accounts, foreach_account_append_to_list, list);
989                 tny_list_foreach (priv->transport_accounts, foreach_account_append_to_list, list);
990                 break;
991         case TNY_ACCOUNT_STORE_STORE_ACCOUNTS:
992                 tny_list_foreach (priv->store_accounts, foreach_account_append_to_list, list);
993                 break;
994         case TNY_ACCOUNT_STORE_TRANSPORT_ACCOUNTS:
995                 tny_list_foreach (priv->transport_accounts, foreach_account_append_to_list, list);
996                 break;
997         default:
998                 g_return_if_reached ();
999         }
1000
1001         /* Initialize session. Why do we need this ??? */
1002         tny_session_camel_set_initialized (priv->session);
1003 }
1004
1005
1006 static const gchar*
1007 modest_tny_account_store_get_cache_dir (TnyAccountStore *self)
1008 {
1009         ModestTnyAccountStorePrivate *priv;
1010         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1011         
1012         if (!priv->cache_dir)
1013                 priv->cache_dir = g_build_filename (g_get_home_dir(), 
1014                                                     MODEST_DIR, MODEST_CACHE_DIR, NULL);
1015         return priv->cache_dir;
1016 }
1017
1018
1019 /*
1020  * callers need to unref
1021  */
1022 static TnyDevice*
1023 modest_tny_account_store_get_device (TnyAccountStore *self)
1024 {
1025         ModestTnyAccountStorePrivate *priv;
1026
1027         g_return_val_if_fail (self, NULL);
1028         
1029         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1030
1031         if (priv->device)
1032                 return g_object_ref (G_OBJECT(priv->device));
1033         else
1034                 return NULL;
1035 }
1036
1037
1038 static TnyAccount*
1039 modest_tny_account_store_find_account_by_url (TnyAccountStore *self, const gchar* url_string)
1040 {
1041         return modest_tny_account_store_get_tny_account_by (MODEST_TNY_ACCOUNT_STORE (self), 
1042                                                             MODEST_TNY_ACCOUNT_STORE_QUERY_URL,
1043                                                             url_string);
1044 }
1045
1046
1047
1048 static gboolean
1049 modest_tny_account_store_alert (TnyAccountStore *self, TnyAccount *account, TnyAlertType type,
1050                                 gboolean question, const GError *error)
1051 {
1052         g_return_val_if_fail (error, FALSE);
1053
1054         if ((error->domain != TNY_ACCOUNT_ERROR) 
1055                 && (error->domain != TNY_ACCOUNT_STORE_ERROR)) {
1056                 g_warning("modest: %s: Unexpected error domain: != TNY_ACCOUNT_ERROR: %d, message=%s", 
1057                         __FUNCTION__, error->domain, error->message); 
1058                         
1059                 return FALSE;
1060         }
1061         
1062         printf("DEBUG: %s: GError code: %d, message=%s\n", 
1063                                 __FUNCTION__, error->code, error->message);
1064         
1065         /* Get the server name: */
1066         const gchar* server_name = NULL;
1067         if (account && TNY_IS_ACCOUNT (account)) {
1068                 server_name = tny_account_get_hostname (account);
1069                 printf ("modest: %s: account name = %s, server_name=%s\n", __FUNCTION__, 
1070                         tny_account_get_id (account), server_name);
1071         }
1072         
1073         if (!server_name)
1074                 server_name = _("Unknown Server");      
1075                 
1076         ModestTransportStoreProtocol proto = MODEST_PROTOCOL_STORE_POP; /* Arbitrary default. */
1077         if (account) {
1078                 const gchar *proto_name = tny_account_get_proto (account);
1079                 if (proto_name)
1080                         proto = modest_protocol_info_get_transport_store_protocol (proto_name);
1081                 else {
1082                         g_warning("modest: %s: account with id=%s has no proto.\n", __FUNCTION__, 
1083                                 tny_account_get_id (account));
1084                 }
1085         }
1086                 
1087         /* const gchar *prompt = NULL; */
1088         gchar *prompt = NULL;
1089         switch (error->code) {
1090                 case TNY_ACCOUNT_STORE_ERROR_CANCEL_ALERT:
1091                 case TNY_ACCOUNT_ERROR_TRY_CONNECT_USER_CANCEL:
1092                         /* Don't show waste the user's time by showing him a dialog telling 
1093                          * him that he has just cancelled something: */
1094                         g_debug ("%s: Handling GError domain=%d, code=%d (cancelled) without showing a dialog, message=%s", 
1095                                 __FUNCTION__, error->domain, error->code, error->message);
1096                         prompt = NULL;
1097                         break;
1098                         
1099                 case TNY_ACCOUNT_ERROR_TRY_CONNECT_HOST_LOOKUP_FAILED:
1100                         /* TODO: Show the appropriate message, depending on whether it's POP or IMAP: */
1101                         g_debug ("%s: Handling GError domain=%d, code=%d (lookup failed), message=%s", 
1102                                 __FUNCTION__, error->domain, error->code, error->message);
1103                                 
1104                         switch (proto) {
1105                                 case MODEST_PROTOCOL_STORE_POP:
1106                                         prompt = g_strdup_printf (_("emev_ni_ui_pop3_msg_connect_error"), server_name);
1107                                         break;
1108                                 case MODEST_PROTOCOL_STORE_IMAP:
1109                                         prompt = g_strdup_printf (_("emev_ni_ui_imap_connect_server_error"), server_name);
1110                                         break;
1111                                 case MODEST_PROTOCOL_TRANSPORT_SMTP:
1112                                 default: /* Arbitrary default. */
1113                                         prompt = g_strdup_printf (_("emev_ib_ui_smtp_server_invalid"), server_name);
1114                                         break;
1115                         }
1116         
1117                         /*
1118                         prompt = g_strdup_printf(
1119                                 _("Incorrect Account Settings:\n Host lookup failed.%s"), 
1120                                 error->message);
1121                         */
1122                         break;
1123                         
1124                 case TNY_ACCOUNT_ERROR_TRY_CONNECT_AUTHENTICATION_NOT_SUPPORTED:
1125                         g_debug ("%s: Handling GError domain=%d, code=%d (authentication not supported), message=%s", 
1126                                 __FUNCTION__, error->domain, error->code, error->message);
1127                         /* TODO: This needs a logical ID for the string: */
1128                         prompt = g_strdup_printf(
1129                                 _("Incorrect Account Settings:\nThe secure authentication method is not supported.\n%s"), 
1130                                 error->message);
1131                         break;
1132                         
1133                 case TNY_ACCOUNT_ERROR_TRY_CONNECT_CERTIFICATE:
1134                         g_debug ("%s: Handling GError domain=%d, code=%d (certificatae), message=%s", 
1135                                 __FUNCTION__, error->domain, error->code, error->message);
1136                         prompt = g_strdup_printf(
1137                                 _("Certificate Problem:\n%s"), 
1138                                 error->message);
1139                         break;
1140                 
1141                 case TNY_ACCOUNT_ERROR_TRY_CONNECT:
1142                 /* The tinymail camel implementation just sends us this for almost 
1143                  * everything, so we have to guess at the cause.
1144                  * It could be a wrong password, or inability to resolve a hostname, 
1145                  * or lack of network, or incorrect authentication method, or something entirely different: */
1146                 /* TODO: Fix camel to provide specific error codes, and then use the 
1147                  * specific dialog messages from Chapter 12 of the UI spec.
1148                  */
1149                 case TNY_ACCOUNT_STORE_ERROR_UNKNOWN_ALERT: 
1150                         /* This debug output is useful. Please keep it uncommented until 
1151                          * we have fixed the problems in this function: */
1152                         g_debug ("%s: Handling GError domain=%d, code=%d, message=%s", 
1153                                 __FUNCTION__, error->domain, error->code, error->message);
1154                         
1155                         /* TODO: Remove the internal error message for the real release.
1156                          * This is just so the testers can give us more information: */
1157                         /* prompt = _("Modest account not yet fully configured."); */
1158                         prompt = g_strdup_printf(
1159                                 "%s\n (Internal error message, often very misleading):\n%s", 
1160                                 _("Incorrect Account Settings"), 
1161                                 error->message);
1162                                 
1163                         /* Note: If the password was wrong then get_password() would be called again,
1164                          * instead of this vfunc being called. */
1165                          
1166                         break;
1167                 
1168                 default:
1169                         g_warning ("%s: Unhandled GError code: %d, message=%s", 
1170                                 __FUNCTION__, error->code, error->message);
1171                         prompt = NULL;
1172                 break;
1173         }
1174         
1175         if (!prompt)
1176                 return FALSE;
1177
1178         ModestWindow *main_window = 
1179                 modest_window_mgr_get_main_window (modest_runtime_get_window_mgr ());
1180         gboolean retval = TRUE;
1181         if (question) {
1182                 /* The Tinymail documentation says that we should show Yes and No buttons, 
1183                  * when it is a question.
1184                  * Obviously, we need tinymail to use more specific error codes instead,
1185                  * so we know what buttons to show. */
1186         
1187                 /* TODO: Do this in the main context: */
1188                 GtkWidget *dialog = GTK_WIDGET (hildon_note_new_confirmation (GTK_WINDOW (main_window), 
1189                         prompt));
1190                 const int response = gtk_dialog_run (GTK_DIALOG (dialog));
1191                 if (question) {
1192                         retval = (response == GTK_RESPONSE_YES) ||
1193                                          (response == GTK_RESPONSE_OK);
1194                 }
1195         
1196                 gtk_widget_destroy (dialog);
1197         
1198          } else {
1199                 /* Just show the error text and use the default response: */
1200                 modest_maemo_show_information_note_in_main_context_and_forget (GTK_WINDOW (main_window), 
1201                         prompt);
1202          }
1203         
1204         /* TODO: Don't free this when we no longer strdup the message for testers. */
1205         g_free (prompt);
1206
1207
1208         /* printf("DEBUG: %s: returning %d\n", __FUNCTION__, retval); */
1209         return retval;
1210 }
1211
1212
1213 static void
1214 modest_tny_account_store_init (gpointer g, gpointer iface_data)
1215 {
1216         TnyAccountStoreIface *klass;
1217
1218         g_return_if_fail (g);
1219
1220         klass = (TnyAccountStoreIface *)g;
1221
1222         klass->get_accounts_func =
1223                 modest_tny_account_store_get_accounts;
1224         klass->get_cache_dir_func =
1225                 modest_tny_account_store_get_cache_dir;
1226         klass->get_device_func =
1227                 modest_tny_account_store_get_device;
1228         klass->alert_func =
1229                 modest_tny_account_store_alert;
1230         klass->find_account_func =
1231                 modest_tny_account_store_find_account_by_url;
1232 }
1233
1234 void
1235 modest_tny_account_store_set_get_pass_func (ModestTnyAccountStore *self,
1236                                             ModestTnyGetPassFunc func)
1237 {
1238         /* not implemented, we use signals */
1239         g_printerr ("modest: set_get_pass_func not implemented\n");
1240 }
1241
1242 TnySessionCamel*
1243 modest_tny_account_store_get_session  (TnyAccountStore *self)
1244 {
1245         g_return_val_if_fail (self, NULL);
1246         return MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE (self)->session;
1247 }
1248
1249 static TnyAccount*
1250 get_tny_account_by (TnyList *accounts,
1251                     ModestTnyAccountStoreQueryType type,
1252                     const gchar *str)
1253 {
1254         TnyIterator *iter = NULL;
1255         gboolean found = FALSE;
1256         TnyAccount *retval = NULL;
1257
1258         iter = tny_list_create_iterator (accounts);
1259         while (!tny_iterator_is_done (iter) && !found) {
1260                 TnyAccount *tmp_account = NULL;
1261                 const gchar *val = NULL;
1262
1263                 tmp_account = TNY_ACCOUNT (tny_iterator_get_current (iter));
1264                 switch (type) {
1265                 case MODEST_TNY_ACCOUNT_STORE_QUERY_ID:
1266                         val = tny_account_get_id (tmp_account);
1267                         break;
1268                 case MODEST_TNY_ACCOUNT_STORE_QUERY_URL:
1269                         val = tny_account_get_url_string (tmp_account);
1270                         break;
1271                 }
1272                 
1273                 if (type == MODEST_TNY_ACCOUNT_STORE_QUERY_URL && 
1274                     tny_account_matches_url_string (tmp_account, str)) {
1275                         retval = g_object_ref (tmp_account);
1276                         found = TRUE;
1277                 } else {
1278                         if (strcmp (val, str) == 0) {
1279                                 retval = g_object_ref (tmp_account);
1280                                 found = TRUE;
1281                         }
1282                 }
1283                 g_object_unref (tmp_account);
1284                 tny_iterator_next (iter);
1285         }
1286         g_object_unref (iter);
1287
1288         return retval;
1289 }
1290
1291 TnyAccount*
1292 modest_tny_account_store_get_tny_account_by (ModestTnyAccountStore *self, 
1293                                              ModestTnyAccountStoreQueryType type,
1294                                              const gchar *str)
1295 {
1296         TnyAccount *account = NULL;
1297         ModestTnyAccountStorePrivate *priv;     
1298         
1299         g_return_val_if_fail (self, NULL);
1300         g_return_val_if_fail (str, NULL);
1301         
1302         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1303         
1304         /* Search in store accounts */
1305         account = get_tny_account_by (priv->store_accounts, type, str);
1306
1307         /* If we already found something, no need to search the transport accounts */
1308         if (!account) {
1309                 account = get_tny_account_by (priv->transport_accounts, type, str);
1310
1311                 /* If we already found something, no need to search the
1312                    per-account outbox accounts */
1313                 if (!account)
1314                         account = get_tny_account_by (priv->store_accounts_outboxes, type, str);
1315         }
1316
1317         /* Warn if nothing was found. This is generally unusual. */
1318         if (!account) {
1319                 g_warning("%s: Failed to find account with %s=%s\n", 
1320                           __FUNCTION__, 
1321                           (type == MODEST_TNY_ACCOUNT_STORE_QUERY_ID) ? "ID" : "URL",                     
1322                           str);
1323         }
1324
1325         /* Returns a new reference to the account if found */   
1326         return account;
1327 }
1328
1329 TnyAccount*
1330 modest_tny_account_store_get_server_account (ModestTnyAccountStore *self,
1331                                              const gchar *account_name,
1332                                              TnyAccountType type)
1333 {
1334         ModestTnyAccountStorePrivate *priv = NULL;
1335         TnyAccount *retval = NULL;
1336         TnyList *account_list = NULL;
1337         TnyIterator *iter = NULL;
1338         gboolean found;
1339
1340         g_return_val_if_fail (self, NULL);
1341         g_return_val_if_fail (account_name, NULL);
1342         g_return_val_if_fail (type == TNY_ACCOUNT_TYPE_STORE || 
1343                               type == TNY_ACCOUNT_TYPE_TRANSPORT,
1344                               NULL);
1345         
1346         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1347
1348         account_list = (type == TNY_ACCOUNT_TYPE_STORE) ? 
1349                 priv->store_accounts : 
1350                 priv->transport_accounts;
1351
1352         if (!account_list) {
1353                 g_printerr ("%s: No server accounts of type %s\n", __FUNCTION__, 
1354                         (type == TNY_ACCOUNT_TYPE_STORE) ? "store" : "transport");
1355                 return NULL;
1356         }
1357         
1358         /* Look for the server account */
1359         found = FALSE;
1360         iter = tny_list_create_iterator (account_list);
1361         while (!tny_iterator_is_done (iter) && !found) {
1362                 const gchar *modest_acc_name;
1363                 TnyAccount *tmp_account;
1364
1365                 tmp_account = TNY_ACCOUNT (tny_iterator_get_current (iter));
1366                 modest_acc_name = 
1367                         modest_tny_account_get_parent_modest_account_name_for_server_account (tmp_account);
1368                 
1369                 if (!strcmp (account_name, modest_acc_name)) {
1370                         found = TRUE;
1371                         retval = g_object_ref (tmp_account);
1372                 }
1373                 /* Free and continue */
1374                 g_object_unref (tmp_account);
1375                 tny_iterator_next (iter);
1376         }
1377
1378         if (!found) {
1379                 g_printerr ("modest: %s: could not get tny %s account for %s\n." \
1380                             "Number of server accounts of this type=%d\n", __FUNCTION__,
1381                             (type == TNY_ACCOUNT_TYPE_STORE) ? "store" : "transport",
1382                             account_name, tny_list_get_length (account_list));
1383         }
1384
1385         /* Returns a new reference */
1386         return retval;
1387 }
1388
1389 static TnyAccount*
1390 get_smtp_specific_transport_account_for_open_connection (ModestTnyAccountStore *self,
1391                                                          const gchar *account_name)
1392 {
1393         /* Get the current connection: */
1394         TnyDevice *device = modest_runtime_get_device ();
1395         
1396         if (!tny_device_is_online (device))
1397                 return NULL;
1398
1399         g_return_val_if_fail (self, NULL);
1400         g_return_val_if_fail (account_name, NULL);
1401         
1402         
1403 #ifdef MODEST_PLATFORM_MAEMO
1404         g_assert (TNY_IS_MAEMO_CONIC_DEVICE (device));
1405         TnyMaemoConicDevice *maemo_device = TNY_MAEMO_CONIC_DEVICE (device);    
1406         const gchar* iap_id = tny_maemo_conic_device_get_current_iap_id (maemo_device);
1407         /* printf ("DEBUG: %s: iap_id=%s\n", __FUNCTION__, iap_id); */
1408         if (!iap_id)
1409                 return NULL;
1410                 
1411         ConIcIap* connection = tny_maemo_conic_device_get_iap (maemo_device, iap_id);
1412         if (!connection)
1413                 return NULL;
1414                 
1415         const gchar *connection_name = con_ic_iap_get_name (connection);
1416         /* printf ("DEBUG: %s: connection_name=%s\n", __FUNCTION__, connection_name); */
1417         if (!connection_name)
1418                 return NULL;
1419         
1420         /*  Get the connection-specific transport acccount, if any: */
1421         ModestAccountMgr *account_manager = modest_runtime_get_account_mgr ();
1422         gchar* server_account_name = modest_account_mgr_get_connection_specific_smtp (account_manager, 
1423                 account_name, connection_name);
1424
1425         /* printf ("DEBUG: %s: server_account_name=%s\n", __FUNCTION__, server_account_name); */
1426         if (!server_account_name) {
1427                 return NULL; /* No connection-specific SMTP server was specified for this connection. */
1428         }
1429                 
1430         TnyAccount* account = modest_tny_account_store_get_tny_account_by (self, 
1431                                                                            MODEST_TNY_ACCOUNT_STORE_QUERY_ID, 
1432                                                                            server_account_name);
1433
1434         /* printf ("DEBUG: %s: account=%p\n", __FUNCTION__, account); */
1435         g_free (server_account_name);   
1436
1437         /* Unref the get()ed object, as required by the tny_maemo_conic_device_get_iap() documentation. */
1438         g_object_unref (connection);
1439         
1440         return account;
1441 #else
1442         return NULL; /* TODO: Implement this for GNOME, instead of just Maemo? */
1443 #endif /* MODEST_PLATFORM_MAEMO */
1444 }
1445
1446                                                                  
1447 TnyAccount*
1448 modest_tny_account_store_get_transport_account_for_open_connection (ModestTnyAccountStore *self,
1449                                                                     const gchar *account_name)
1450 {
1451         g_return_val_if_fail (self, NULL);
1452         g_return_val_if_fail (account_name, NULL);
1453
1454         if (!account_name || !self)
1455                 return NULL;
1456         
1457         /*  Get the connection-specific transport acccount, if any: */
1458         TnyAccount *account =
1459                 get_smtp_specific_transport_account_for_open_connection (self, account_name);
1460                         
1461         /* If there is no connection-specific transport account (the common case), 
1462          * just get the regular transport account: */
1463         if (!account) {
1464                 /* The special local folders don't have transport accounts. */
1465                 if (strcmp (account_name, MODEST_LOCAL_FOLDERS_ACCOUNT_ID) == 0)
1466                         account = NULL;
1467                 else
1468                         account = modest_tny_account_store_get_server_account (self, account_name, 
1469                                                      TNY_ACCOUNT_TYPE_TRANSPORT);
1470         }
1471                              
1472         return account;
1473 }
1474
1475 TnyAccount*
1476 modest_tny_account_store_get_local_folders_account (ModestTnyAccountStore *self)
1477 {
1478         TnyAccount *account = NULL;
1479         ModestTnyAccountStorePrivate *priv;
1480         TnyIterator *iter;
1481         gboolean found;
1482
1483         g_return_val_if_fail (MODEST_IS_TNY_ACCOUNT_STORE (self), NULL);
1484         
1485         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1486
1487         found = FALSE;
1488         iter = tny_list_create_iterator (priv->store_accounts);
1489         while (!tny_iterator_is_done (iter) && !found) {
1490                 TnyAccount *tmp_account;
1491
1492                 tmp_account = TNY_ACCOUNT (tny_iterator_get_current (iter));
1493                 if (modest_tny_account_is_virtual_local_folders (tmp_account)) {
1494                         account = g_object_ref (tmp_account);
1495                         found = TRUE;
1496                 }
1497                 g_object_unref (tmp_account);
1498                 tny_iterator_next (iter);
1499         }
1500         g_object_unref (iter);
1501
1502         /* Returns a new reference to the account */
1503         return account;
1504 }
1505
1506 /*********************************************************************************/
1507 static void
1508 add_existing_accounts (ModestTnyAccountStore *self)
1509 {
1510         GSList *account_names = NULL, *iter = NULL;
1511         ModestTnyAccountStorePrivate *priv = NULL;
1512         
1513         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1514
1515         /* These are account names, not server_account names */
1516         account_names = modest_account_mgr_account_names (priv->account_mgr, FALSE);
1517
1518         for (iter = account_names; iter != NULL; iter = g_slist_next (iter)) {
1519                 const gchar *account_name = (const gchar*) iter->data;
1520                 
1521                 /* Insert all enabled accounts without notifying */
1522                 if (modest_account_mgr_get_enabled (priv->account_mgr, account_name))
1523                         insert_account (self, account_name, FALSE);
1524         }
1525         modest_account_mgr_free_account_names (account_names);
1526 }
1527
1528 static TnyAccount*
1529 create_tny_account (ModestTnyAccountStore *self,
1530                     const gchar *name,
1531                     TnyAccountType type)
1532 {
1533         TnyAccount *account = NULL;
1534         ModestTnyAccountStorePrivate *priv = NULL;
1535         
1536         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1537
1538         account = modest_tny_account_new_from_account (priv->account_mgr,
1539                                                        name, type, 
1540                                                        priv->session,
1541                                                        get_password,
1542                                                        forget_password);
1543
1544         if (account) {
1545                 /* Forget any cached password for the account, so that
1546                    we use a new account if any */
1547                 modest_tny_account_store_forget_password_in_memory (self, 
1548                                                                     tny_account_get_id (account));
1549                 /* Set the account store */                             
1550                 g_object_set_data (G_OBJECT(account), "account_store", self);
1551         } else {
1552                 g_printerr ("modest: failed to create account for %s\n", name);
1553         }
1554
1555         return account;
1556 }
1557
1558 /*
1559  * This function will be used for both adding new accounts and for the
1560  * initialization. In the initialization we do not want to emit
1561  * signals so notify will be FALSE, in the case of account additions
1562  * we do want to notify the observers
1563  */
1564 static void
1565 insert_account (ModestTnyAccountStore *self,
1566                 const gchar *account,
1567                 gboolean notify)
1568 {
1569         ModestTnyAccountStorePrivate *priv = NULL;
1570         TnyAccount *store_account = NULL, *transport_account = NULL;
1571         
1572         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1573
1574         /* Get the server and the transport account */
1575         store_account = create_tny_account (self, account, TNY_ACCOUNT_TYPE_STORE);
1576         transport_account = create_tny_account (self, account, TNY_ACCOUNT_TYPE_TRANSPORT);
1577
1578         /* Add to the list, and notify the observers */
1579         if (store_account) {
1580                 tny_list_append (priv->store_accounts, G_OBJECT (store_account));
1581                 if (notify)
1582                         g_signal_emit (G_OBJECT (self), signals [ACCOUNT_INSERTED_SIGNAL], 0, store_account);
1583                 g_object_unref (store_account);
1584         }
1585
1586         /* Add to the list, and notify the observers */
1587         if (transport_account) {
1588                 TnyAccount *account_outbox = NULL, *local_account = NULL;
1589                 TnyFolder *per_account_outbox = NULL;
1590                 TnyList *folders;
1591                 TnyIterator *iter_folders;
1592
1593                 /* Add account to the list */
1594                 tny_list_append (priv->transport_accounts, G_OBJECT (transport_account));
1595
1596                 /* Add connection-specific transport accounts */
1597                 add_connection_specific_transport_accounts (self, account);
1598
1599                 /* Create per account local outbox */
1600                 account_outbox = 
1601                         modest_tny_account_new_for_per_account_local_outbox_folder (priv->account_mgr, 
1602                                                                                     account, 
1603                                                                                     priv->session);
1604                 tny_list_append (priv->store_accounts_outboxes, G_OBJECT (account_outbox));
1605
1606                 /* Get the outbox folder */
1607                 folders = tny_simple_list_new ();
1608                 tny_folder_store_get_folders (TNY_FOLDER_STORE (account_outbox),
1609                                               folders, NULL, NULL);
1610                 g_assert (tny_list_get_length (folders) == 1);
1611                 iter_folders = tny_list_create_iterator (folders);
1612                 per_account_outbox = TNY_FOLDER (tny_iterator_get_current (iter_folders));
1613                 g_object_unref (iter_folders);
1614                 g_object_unref (account_outbox);
1615
1616                 /* Add the outbox of the new per-account-local-outbox
1617                    account to the global local merged OUTBOX of the
1618                    local folders account */
1619                 local_account = modest_tny_account_store_get_local_folders_account (MODEST_TNY_ACCOUNT_STORE (self));
1620                 modest_tny_local_folders_account_add_folder_to_outbox (MODEST_TNY_LOCAL_FOLDERS_ACCOUNT (local_account), 
1621                                                                        per_account_outbox);
1622                 g_object_unref (local_account);
1623                 g_object_unref (per_account_outbox);
1624
1625                 /* Notify the observers */
1626                 if (notify)
1627                         g_signal_emit (G_OBJECT (self), signals [ACCOUNT_INSERTED_SIGNAL], 0, transport_account);
1628                 g_object_unref (transport_account);
1629         }
1630 }
1631
1632 static void
1633 on_account_inserted (ModestAccountMgr *acc_mgr, 
1634                      const gchar *account,
1635                      gpointer user_data)
1636 {
1637         /* Insert the account and notify the observers */
1638         insert_account (MODEST_TNY_ACCOUNT_STORE (user_data), account, TRUE);
1639 }
1640
1641 static void
1642 on_account_removed (ModestAccountMgr *acc_mgr, 
1643                     const gchar *account,
1644                     gpointer user_data)
1645 {
1646         TnyAccount *store_account = NULL, *transport_account = NULL;
1647         ModestTnyAccountStore *self = MODEST_TNY_ACCOUNT_STORE(user_data);
1648         
1649         /* Get the server and the transport account */
1650         store_account = 
1651                 modest_tny_account_store_get_server_account (self, account, TNY_ACCOUNT_TYPE_STORE);
1652         transport_account = 
1653                 modest_tny_account_store_get_server_account (self, account, TNY_ACCOUNT_TYPE_TRANSPORT);
1654
1655         /* If there was any problem creating the account, for example,
1656            with the configuration system this could not exist */
1657         if (store_account) {
1658                 /* Clear the cache */
1659                 tny_store_account_delete_cache (TNY_STORE_ACCOUNT (store_account));
1660
1661                 /* Notify the observers */
1662                 g_signal_emit (G_OBJECT (self), signals [ACCOUNT_REMOVED_SIGNAL], 0, store_account);
1663                 g_object_unref (store_account);
1664         } else {
1665                 g_warning ("There is no store account for account %s\n", account);
1666         }
1667
1668         /* If there was any problem creating the account, for example,
1669            with the configuration system this could not exist */
1670         if (transport_account) {
1671                 /* Notify the observers */
1672                 g_signal_emit (G_OBJECT (self), signals [ACCOUNT_REMOVED_SIGNAL], 0, transport_account);
1673                 g_object_unref (transport_account);
1674         } else {
1675                 g_warning ("There is no transport account for account %s\n", account);
1676         }
1677 }
1678
1679 static void
1680 add_connection_specific_transport_accounts (ModestTnyAccountStore *self,
1681                                             const gchar *account_name)
1682 {
1683         ModestTnyAccountStorePrivate *priv = NULL;
1684         GSList *list_specifics = NULL, *iter = NULL;
1685
1686         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1687
1688         list_specifics = modest_account_mgr_get_list (priv->account_mgr,
1689                                                       account_name, 
1690                                                       MODEST_ACCOUNT_CONNECTION_SPECIFIC_SMTP_LIST,
1691                                                       MODEST_CONF_VALUE_STRING, FALSE);
1692                                 
1693         /* Look at each connection-specific transport account for the 
1694          * modest account: */
1695         iter = list_specifics;
1696         while (iter) {
1697                 /* The list alternates between the connection name and the transport name: */
1698                 iter = g_slist_next (iter);
1699                 if (iter) {
1700                         const gchar* transport_account_name = (const gchar*) (iter->data);
1701                         if (transport_account_name) {
1702                                 TnyAccount * tny_account = NULL;
1703                                 /* Add the account: */
1704                                 tny_account = 
1705                                         modest_tny_account_new_from_server_account_name (priv->account_mgr, 
1706                                                                                          priv->session, 
1707                                                                                          transport_account_name);
1708                                 if (tny_account) {
1709                                         modest_tny_account_set_parent_modest_account_name_for_server_account (tny_account, 
1710                                                                                                               account_name);
1711                                         g_object_set_data (G_OBJECT(tny_account), 
1712                                                            "account_store", 
1713                                                            (gpointer)self);
1714
1715                                         tny_list_append (priv->transport_accounts, G_OBJECT (tny_account));
1716                                 } else
1717                                         g_printerr ("modest: failed to create smtp-specific account for %s\n",
1718                                                     transport_account_name);
1719                         }
1720                 }                               
1721                 iter = g_slist_next (iter);
1722         }
1723 }