Activate a modal dialog only on UI DBus requests
[modest] / src / dbus_api / modest-dbus-callbacks.c
1 /* Copyright (c) 2007, 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 "modest-dbus-callbacks.h"
31 #include "modest-runtime.h"
32 #include "modest-account-mgr.h"
33 #include "modest-account-mgr-helpers.h"
34 #include "modest-tny-account.h"
35 #include "modest-tny-folder.h"
36 #include "modest-ui-actions.h"
37 #include "modest-utils.h"
38 #include "modest-debug.h"
39 #include "modest-search.h"
40 #include "widgets/modest-msg-edit-window.h"
41 #include "widgets/modest-window-mgr.h"
42 #include "modest-tny-msg.h"
43 #include "modest-platform.h"
44 #include "modest-defs.h"
45 #include <libmodest-dbus-client/libmodest-dbus-client.h>
46 #include <libgnomevfs/gnome-vfs-utils.h>
47 #include <stdio.h>
48 #include <string.h>
49 #include <glib/gstdio.h>
50 #include <hildon/hildon-program.h>
51 #include <libgnomevfs/gnome-vfs-mime.h>
52 #include <tny-fs-stream.h>
53
54 #ifdef MODEST_TOOLKIT_HILDON2
55 #include <hildon/hildon.h>
56 #include <modest-accounts-window.h>
57 #include <modest-folder-window.h>
58 #include <modest-mailboxes-window.h>
59 #include <modest-maemo-utils.h>
60 #endif
61
62 #include <tny-list.h>
63 #include <tny-iterator.h>
64 #include <tny-simple-list.h>
65 #include <tny-merge-folder.h>
66 #include <tny-account.h>
67
68 #include <modest-text-utils.h>
69
70 #define DISABLE_GET_UNREAD_MSGS_FOR_MULTI_MAILBOX 1
71
72 typedef struct 
73 {
74         gchar *to;
75         gchar *cc;
76         gchar *bcc;
77         gchar *subject;
78         gchar *body;
79         gchar *attachments;
80 } ComposeMailIdleData;
81
82
83 static gboolean notify_error_in_dbus_callback (gpointer user_data);
84 static gboolean on_idle_compose_mail(gpointer user_data);
85 static gboolean on_idle_top_application (gpointer user_data);
86
87 /** uri_unescape:
88  * @uri An escaped URI. URIs should always be escaped.
89  * @len The length of the @uri string, or -1 if the string is null terminated.
90  * 
91  * Decode a URI, or URI fragment, as per RFC 1738.
92  * http://www.ietf.org/rfc/rfc1738.txt
93  * 
94  * Return value: An unescaped string. This should be freed with g_free().
95  */
96 static gchar* 
97 uri_unescape(const gchar* uri, size_t len)
98 {
99         if (!uri)
100                 return NULL;
101                 
102         if (len == -1)
103                 len = strlen (uri);
104         
105         /* Allocate an extra string so we can be sure that it is null-terminated,
106          * so we can use gnome_vfs_unescape_string().
107          * This is not efficient. */
108         gchar * escaped_nullterminated = g_strndup (uri, len);
109         gchar *result = gnome_vfs_unescape_string (escaped_nullterminated, NULL);
110         g_free (escaped_nullterminated);
111         
112         return result;
113 }
114
115 /** uri_parse_mailto:
116  * @mailto A mailto URI, with the mailto: prefix.
117  * @list_items_and_values: A pointer to a list that should be filled with item namesand value strings, 
118  * with each name item being followed by a value item. This list should be freed with g_slist_free) after 
119  * all the string items have been freed. This parameter may be NULL.
120  * Parse a mailto URI as per RFC2368.
121  * http://www.ietf.org/rfc/rfc2368.txt
122  * 
123  * Return value: The to address, unescaped. This should be freed with g_free().
124  */
125 static gchar* 
126 uri_parse_mailto (const gchar* mailto, GSList** list_items_and_values)
127 {
128         /* The URL must begin with mailto: */
129         if (strncmp (mailto, "mailto:", 7) != 0) {
130                 return NULL;
131         }
132         const gchar* start_to = mailto + 7;
133
134         /* Look for ?, or the end of the string, marking the end of the to address: */
135         const size_t len_to = strcspn (start_to, "?");
136         gchar* result_to = uri_unescape (start_to, len_to);
137         printf("debug: result_to=%s\n", result_to);
138
139         if (list_items_and_values == NULL) {
140                 return result_to;
141         }
142
143         /* Get any other items: */
144         const size_t len_mailto = strlen (start_to);
145         const gchar* p = start_to + len_to + 1; /* parsed so far. */
146         const gchar* end = start_to + len_mailto;
147         while (p < end) {
148                 const gchar *name, *value, *name_start, *name_end, *value_start, *value_end;
149                 name_start = p;
150                 name_end = strchr (name_start, '='); /* Separator between name and value */
151                 if (name_end == NULL) {
152                         g_debug ("Malformed URI: %s\n", mailto);
153                         return result_to;
154                 }
155                 value_start = name_end + 1;
156                 value_end = strchr (value_start, '&'); /* Separator between value and next parameter */
157
158                 name = g_strndup(name_start, name_end - name_start);
159                 if (value_end != NULL) {
160                         value = uri_unescape(value_start, value_end - value_start);
161                         p = value_end + 1;
162                 } else {
163                         value = uri_unescape(value_start, -1);
164                         p = end;
165                 }
166                 *list_items_and_values = g_slist_append (*list_items_and_values, (gpointer) name);
167                 *list_items_and_values = g_slist_append (*list_items_and_values, (gpointer) value);
168         }
169         
170         return result_to;
171 }
172
173 static gboolean
174 check_and_offer_account_creation()
175 {
176         gboolean result = TRUE;
177         
178         /* This is called from idle handlers, so lock gdk: */
179         gdk_threads_enter ();
180         
181         if (!modest_account_mgr_has_accounts(modest_runtime_get_account_mgr(), TRUE)) {
182                 const gboolean created = modest_ui_actions_run_account_setup_wizard (NULL);
183                 if (!created) {
184                         g_debug ("modest: %s: no account exists even after offering, "
185                                  "or account setup was already underway.\n", __FUNCTION__);
186                         result = FALSE;
187                 }
188         }
189         
190         gdk_threads_leave ();
191         
192         return result;
193 }
194
195 static gboolean
196 on_idle_mail_to(gpointer user_data)
197 {
198         gchar *uri = (gchar*)user_data;
199         GSList *list_names_and_values = NULL;
200         gchar *to = NULL;
201         const gchar *cc = NULL;
202         const gchar *bcc = NULL;
203         const gchar *subject = NULL;
204         const gchar *body = NULL;
205
206         if (!check_and_offer_account_creation ()) {
207                 g_idle_add (notify_error_in_dbus_callback, NULL);
208                 goto cleanup;
209         }
210
211         /* Get the relevant items from the list: */
212         to = uri_parse_mailto (uri, &list_names_and_values);
213         GSList *list = list_names_and_values;
214         while (list) {
215                 GSList *list_value = g_slist_next (list);
216                 const gchar * name = (const gchar*)list->data;
217                 const gchar * value = (const gchar*)list_value->data;
218
219                 if (strcmp (name, "cc") == 0) {
220                         cc = value;
221                 } else if (strcmp (name, "bcc") == 0) {
222                         bcc = value;
223                 } else if (strcmp (name, "subject") == 0) {
224                         subject = value;
225                 } else if (strcmp (name, "body") == 0) {
226                         body = value;
227                 }
228
229                 list = g_slist_next (list_value);
230         }
231
232         gdk_threads_enter (); /* CHECKED */
233         modest_ui_actions_compose_msg(NULL, to, cc, bcc, subject, body, NULL, FALSE);
234         gdk_threads_leave (); /* CHECKED */
235
236 cleanup:
237         /* Free the to: and the list, as required by uri_parse_mailto() */
238         g_free(to);
239         g_slist_foreach (list_names_and_values, (GFunc)g_free, NULL);
240         g_slist_free (list_names_and_values);
241
242         g_free(uri);
243
244         return FALSE; /* Do not call this callback again. */
245 }
246
247 static gint 
248 on_mail_to(GArray * arguments, gpointer data, osso_rpc_t * retval)
249 {
250         osso_rpc_t val;
251         gchar *uri;
252
253         /* Get arguments */
254         val = g_array_index(arguments, osso_rpc_t, MODEST_DBUS_MAIL_TO_ARG_URI);
255         uri = g_strdup (val.value.s);
256         
257         g_idle_add(on_idle_mail_to, (gpointer)uri);
258         
259         /* Note that we cannot report failures during sending, 
260          * because that would be asynchronous. */
261         return OSSO_OK;
262 }
263
264
265 static gboolean
266 on_idle_compose_mail(gpointer user_data)
267 {
268         GSList *attachments = NULL;
269         ComposeMailIdleData *idle_data = (ComposeMailIdleData*)user_data;
270
271         if (!check_and_offer_account_creation ()) {
272                 g_idle_add (notify_error_in_dbus_callback, NULL);
273                 goto cleanup;
274         }
275
276         /* it seems Sketch at least sends a leading ',' -- take that into account,
277          * ie strip that ,*/
278         if (idle_data->attachments && idle_data->attachments[0]==',') {
279                 gchar *tmp = g_strdup (idle_data->attachments + 1);
280                 g_free(idle_data->attachments);
281                 idle_data->attachments = tmp;
282         }
283
284         if (idle_data->attachments != NULL) {
285                 gchar **list = g_strsplit(idle_data->attachments, ",", 0);
286                 gint i = 0;
287                 for (i=0; list[i] != NULL; i++) {
288                         attachments = g_slist_append(attachments, g_uri_unescape_string (list[i], NULL));
289                 }
290                 g_strfreev(list);
291         }
292
293         /* If the message has nothing then mark the buffers as not
294            modified. This happens in Maemo for example when opening a
295            new message from Contacts plugin, it sends "" instead of
296            NULLs */
297         gdk_threads_enter (); /* CHECKED */
298         if (!strncmp (idle_data->to, "", 1) &&
299             !strncmp (idle_data->to, "", 1) &&
300             !strncmp (idle_data->cc, "", 1) &&
301             !strncmp (idle_data->bcc, "", 1) &&
302             !strncmp (idle_data->subject, "", 1) &&
303             !strncmp (idle_data->body, "", 1) &&
304             attachments == NULL) {
305                 modest_ui_actions_compose_msg(NULL, NULL, NULL, NULL, NULL, NULL, NULL, FALSE);
306         } else {
307                 modest_ui_actions_compose_msg(NULL, idle_data->to, idle_data->cc,
308                                               idle_data->bcc, idle_data->subject,
309                                               idle_data->body, attachments, TRUE);
310         }
311         gdk_threads_leave (); /* CHECKED */
312 cleanup:
313         g_slist_foreach(attachments, (GFunc)g_free, NULL);
314         g_slist_free(attachments);
315         g_free (idle_data->to);
316         g_free (idle_data->cc);
317         g_free (idle_data->bcc);
318         g_free (idle_data->subject);
319         g_free (idle_data->body);
320         g_free (idle_data->attachments);
321         g_free(idle_data);
322
323         return FALSE; /* Do not call this callback again. */
324 }
325
326 static gint 
327 on_compose_mail(GArray * arguments, gpointer data, osso_rpc_t * retval)
328 {
329         ComposeMailIdleData *idle_data;
330         osso_rpc_t val;
331         
332         idle_data = g_new0(ComposeMailIdleData, 1); /* Freed in the idle callback. */
333         
334         /* Get the arguments: */
335         val = g_array_index(arguments, osso_rpc_t, MODEST_DBUS_COMPOSE_MAIL_ARG_TO);
336         idle_data->to = g_strdup (val.value.s);
337         
338         val = g_array_index(arguments, osso_rpc_t, MODEST_DBUS_COMPOSE_MAIL_ARG_CC);
339         idle_data->cc = g_strdup (val.value.s);
340         
341         val = g_array_index(arguments, osso_rpc_t, MODEST_DBUS_COMPOSE_MAIL_ARG_BCC);
342         idle_data->bcc = g_strdup (val.value.s);
343         
344         val = g_array_index(arguments, osso_rpc_t, MODEST_DBUS_COMPOSE_MAIL_ARG_SUBJECT);
345         idle_data->subject = g_strdup (val.value.s);
346         
347         val = g_array_index(arguments, osso_rpc_t, MODEST_DBUS_COMPOSE_MAIL_ARG_BODY);
348         idle_data->body = g_strdup (val.value.s);
349         
350         val = g_array_index(arguments, osso_rpc_t, MODEST_DBUS_COMPOSE_MAIL_ARG_ATTACHMENTS);
351         idle_data->attachments = g_strdup (val.value.s);
352
353         /* Use g_idle to context-switch into the application's thread: */
354         g_idle_add(on_idle_compose_mail, (gpointer)idle_data);
355         
356         return OSSO_OK;
357 }
358
359 static TnyMsg *
360 find_message_by_url (const char *uri,  TnyAccount **ac_out)
361 {
362         ModestTnyAccountStore *astore;
363         TnyAccount *account = NULL;
364         TnyFolder *folder = NULL;
365         TnyMsg *msg = NULL;
366
367         astore = modest_runtime_get_account_store ();
368         
369         if (astore == NULL)
370                 return NULL;
371
372         if (uri && g_str_has_prefix (uri, "merge://")) {
373                 /* we assume we're talking about outbox folder, as this 
374                  * is the only merge folder we work with in modest */
375                 return modest_tny_account_store_find_msg_in_outboxes (astore, uri, ac_out);
376         }
377         account = tny_account_store_find_account (TNY_ACCOUNT_STORE (astore),
378                                                   uri);
379         
380         if (account == NULL || !TNY_IS_STORE_ACCOUNT (account))
381                 goto out;
382         *ac_out = account;
383
384         folder = tny_store_account_find_folder (TNY_STORE_ACCOUNT (account), uri, NULL);
385
386         if (folder == NULL)
387                 goto out;
388         
389         msg = tny_folder_find_msg (folder, uri, NULL);
390         
391 out:
392         if (account && !msg) {
393                 g_object_unref (account);
394                 *ac_out = NULL;
395         }
396         if (folder)
397                 g_object_unref (folder);
398
399         return msg;
400 }
401
402 typedef struct {
403         TnyAccount *account;
404         gchar *uri;
405         gboolean connect;
406         guint animation_timeout;
407         GtkWidget *animation;
408 } OpenMsgPerformerInfo;
409
410 #ifndef MODEST_TOOLKIT_HILDON2
411 static gboolean
412 on_show_opening_animation (gpointer userdata)
413 {
414         OpenMsgPerformerInfo *info = (OpenMsgPerformerInfo *) userdata;
415         info->animation = modest_platform_animation_banner (NULL, NULL, _("mail_me_opening"));
416         info->animation_timeout = 0;
417
418         return FALSE;
419 }
420 #endif
421
422 static gboolean
423 on_find_msg_async_destroy (gpointer userdata)
424 {
425         OpenMsgPerformerInfo *info = (OpenMsgPerformerInfo *) userdata;
426
427         if (info->animation_timeout>0) {
428                 g_source_remove (info->animation_timeout);
429                 info->animation_timeout = 0;
430         }
431
432         if (info->animation) {
433                 gtk_widget_destroy (info->animation);
434                 info->animation = NULL;
435         }
436
437         if (info->uri)
438                 g_free (info->uri);
439         
440         if (info->account)
441                 g_object_unref (info->account);
442
443         g_slice_free (OpenMsgPerformerInfo, info);
444         return FALSE;
445 }
446
447 static void     
448 find_msg_async_cb (TnyFolder *folder, 
449                    gboolean cancelled, 
450                    TnyMsg *msg, 
451                    GError *err, 
452                    gpointer user_data)
453 {
454         TnyHeader *header = NULL;
455         gchar *msg_uid = NULL;
456         ModestWindowMgr *win_mgr;
457         ModestWindow *msg_view = NULL;
458         gboolean is_draft = FALSE;
459         OpenMsgPerformerInfo *info = (OpenMsgPerformerInfo *) user_data;
460
461         if (err || cancelled) {
462                 modest_platform_run_information_dialog (NULL, _("mail_ni_ui_folder_get_msg_folder_error"), TRUE);
463                 g_idle_add (notify_error_in_dbus_callback, NULL);
464                 goto end;
465         }
466
467         header = tny_msg_get_header (msg);
468         if (!header || (tny_header_get_flags (header) & TNY_HEADER_FLAG_DELETED)) {
469                 modest_platform_run_information_dialog (NULL, _("mail_ni_ui_folder_get_msg_folder_error"), TRUE);
470                 g_idle_add (notify_error_in_dbus_callback, NULL);
471                 goto end;
472         }
473
474         msg_uid =  modest_tny_folder_get_header_unique_id (header);
475         win_mgr = modest_runtime_get_window_mgr ();
476
477         if (modest_tny_folder_is_local_folder (folder) &&
478             (modest_tny_folder_get_local_or_mmc_folder_type (folder) == TNY_FOLDER_TYPE_DRAFTS)) {
479                 is_draft = TRUE;
480         }
481
482         if (modest_window_mgr_find_registered_header (win_mgr, header, &msg_view)) {
483                 gtk_window_present (GTK_WINDOW(msg_view));
484         } else {
485                 const gchar *modest_account_name;
486                 TnyAccount *account;
487
488                 modest_window_mgr_register_header (win_mgr, header, NULL);
489
490                 account = tny_folder_get_account (folder);
491                 if (account) {
492                         modest_account_name =
493                                 modest_tny_account_get_parent_modest_account_name_for_server_account (account);
494                 } else {
495                         modest_account_name = NULL;
496                 }
497
498                 /* Drafts will be opened in the editor, and others will be opened in the viewer */
499                 if (is_draft) {
500                         gchar *modest_account_name = NULL;
501                         gchar *mailbox = NULL;
502                         gchar *from_header;
503
504                         /* we cannot edit without a valid account... */
505                         if (!modest_account_mgr_has_accounts(modest_runtime_get_account_mgr (), TRUE)) {
506                                 if (!modest_ui_actions_run_account_setup_wizard(NULL)) {
507                                         modest_window_mgr_unregister_header (win_mgr, 
508                                                                              header);
509                                         goto end;
510                                 }
511                         }
512                
513                         from_header = tny_header_dup_from (header);
514                         modest_account_name = modest_utils_get_account_name_from_recipient (from_header, &mailbox);
515                         g_free (from_header);
516                         
517                         if (modest_account_name == NULL) {
518                                 ModestAccountMgr *mgr = modest_runtime_get_account_mgr ();
519                                 modest_account_name = modest_account_mgr_get_default_account (mgr);
520                         }
521                         msg_view = modest_msg_edit_window_new (msg, modest_account_name, mailbox, TRUE);
522                         if (mailbox)
523                                 g_free (mailbox);
524                         g_free (modest_account_name);
525                 } else {
526                         TnyHeader *header;
527                         const gchar *modest_account_name;
528
529                         if (account) {
530                                 modest_account_name = 
531                                         modest_tny_account_get_parent_modest_account_name_for_server_account (account);
532                         } else {
533                                 modest_account_name = NULL;
534                         }
535
536                         header = tny_msg_get_header (msg);
537                         msg_view = modest_msg_view_window_new_for_search_result (msg, modest_account_name, NULL, msg_uid);
538                         if (! (tny_header_get_flags (header) & TNY_HEADER_FLAG_SEEN)) {
539                                 ModestMailOperation *mail_op;
540                                 
541                                 tny_header_set_flag (header, TNY_HEADER_FLAG_SEEN);
542                                 modest_platform_emit_msg_read_changed_signal (msg_uid, TRUE);
543                                 /* Sync folder, we need this to save the seen flag */
544                                 mail_op = modest_mail_operation_new (NULL);
545                                 modest_mail_operation_queue_add (modest_runtime_get_mail_operation_queue (),
546                                                                  mail_op);
547                                 modest_mail_operation_sync_folder (mail_op, folder, FALSE, NULL, NULL);
548                                 g_object_unref (mail_op);
549                         }
550                         g_object_unref (header);
551                 }
552
553                 if (msg_view != NULL) {
554                         if (!modest_window_mgr_register_window (win_mgr, msg_view, NULL)) {
555                                 gtk_widget_destroy (GTK_WIDGET (msg_view));
556                         } else {
557                                 gtk_widget_show_all (GTK_WIDGET (msg_view));
558                         }
559                 }
560         }
561
562 end:
563         if (header)
564                 g_object_unref (header);
565         if (msg_uid)
566                 g_free (msg_uid);
567         on_find_msg_async_destroy (info);
568 }
569
570
571 static void
572 on_open_message_performer (gboolean canceled,
573                            GError *err,
574                            ModestWindow *parent_window,
575                            TnyAccount *account,
576                            gpointer user_data)
577 {
578         OpenMsgPerformerInfo *info;
579         TnyFolder *folder = NULL;
580         ModestTnyAccountStore *account_store;
581         ModestTnyLocalFoldersAccount *local_folders_account;
582  
583         account_store = modest_runtime_get_account_store ();
584         local_folders_account = MODEST_TNY_LOCAL_FOLDERS_ACCOUNT (
585                 modest_tny_account_store_get_local_folders_account (account_store));
586
587         info = (OpenMsgPerformerInfo *) user_data;
588         if (canceled || err) {
589                 if (!canceled)
590                         modest_platform_run_information_dialog (NULL, _("mail_ni_ui_folder_get_msg_folder_error"), TRUE);
591                 g_idle_add (notify_error_in_dbus_callback, NULL);
592                 on_find_msg_async_destroy (info);
593                 return;
594         }
595
596         /* Get folder */
597         if (!account) {
598                 folder = modest_tny_local_folders_account_get_merged_outbox (local_folders_account);
599                 g_object_unref (local_folders_account);
600         } else if (account == TNY_ACCOUNT (local_folders_account)) {
601                 folder = tny_store_account_find_folder (TNY_STORE_ACCOUNT (account), info->uri, NULL);
602         } else {
603                 folder = NULL;
604         }
605         if (!(folder && modest_tny_folder_is_local_folder (folder) &&
606               (modest_tny_folder_get_local_or_mmc_folder_type (folder) == TNY_FOLDER_TYPE_DRAFTS))) {
607                 ModestWindowMgr *win_mgr;
608                 ModestWindow *msg_view;
609
610                 win_mgr = modest_runtime_get_window_mgr ();
611                 if (modest_window_mgr_find_registered_message_uid (win_mgr, info->uri, &msg_view)) {
612                         gtk_window_present (GTK_WINDOW(msg_view));
613                 } else {
614                         const gchar *modest_account_name;
615                         if (account) {
616                                 modest_account_name =
617                                         modest_tny_account_get_parent_modest_account_name_for_server_account (account);
618                         } else {
619                                 modest_account_name = NULL;
620                         }
621                         
622                         msg_view = modest_msg_view_window_new_from_uid (modest_account_name, NULL, info->uri);
623                         if (msg_view != NULL) {
624                                 if (!modest_window_mgr_register_window (win_mgr, msg_view, NULL)) {
625                                         gtk_widget_destroy (GTK_WIDGET (msg_view));
626                                 } else {
627                                         gtk_widget_show_all (GTK_WIDGET (msg_view));
628                                 }
629                         }
630                         if (account)
631                                 g_object_unref (account);
632
633                 }
634                 on_find_msg_async_destroy (info);
635                 return;
636         }
637
638 #ifndef MODEST_TOOLKIT_HILDON2
639         info->animation_timeout = g_timeout_add (1000, on_show_opening_animation, info);
640 #endif
641         /* Get message */
642         tny_folder_find_msg_async (folder, info->uri, find_msg_async_cb, NULL, info);
643         g_object_unref (folder);
644 }
645
646 static gboolean
647 on_idle_open_message_performer (gpointer user_data)
648 {
649         ModestWindow *top_win = NULL;
650         OpenMsgPerformerInfo *info = (OpenMsgPerformerInfo *) user_data;
651
652         top_win = modest_window_mgr_get_current_top (modest_runtime_get_window_mgr());
653
654         /* Lock before the call as we're in an idle handler */
655         gdk_threads_enter ();
656         if (info->connect) {
657                 modest_platform_connect_and_perform (top_win, TRUE,
658                                                      info->account,
659                                                      on_open_message_performer, info);
660         } else {
661                 on_open_message_performer (FALSE, NULL, top_win,
662                                            info->account, info);
663         }
664         gdk_threads_leave ();
665
666         return FALSE;
667 }
668
669 static gint 
670 on_open_message (GArray * arguments, gpointer data, osso_rpc_t * retval)
671 {
672         osso_rpc_t val;
673         gchar *uri;
674         TnyAccount *account = NULL;
675         gint osso_retval;
676         gboolean is_merge;
677
678         /* Get the arguments: */
679         val = g_array_index(arguments, osso_rpc_t, MODEST_DBUS_OPEN_MESSAGE_ARG_URI);
680         uri = g_strdup (val.value.s);
681
682         is_merge = g_str_has_prefix (uri, "merge:");
683
684         /* Get the account */
685         if (!is_merge)
686                 account = tny_account_store_find_account (TNY_ACCOUNT_STORE (modest_runtime_get_account_store ()),
687                                                           uri);
688
689         
690         if (is_merge || account) {
691                 OpenMsgPerformerInfo *info;
692                 TnyFolder *folder = NULL;
693                 ModestTnyAccountStore *account_store;
694                 ModestTnyLocalFoldersAccount *local_folders_account;
695
696                 info = g_slice_new0 (OpenMsgPerformerInfo);
697                 if (account) 
698                         info->account = g_object_ref (account);
699                 info->uri = uri;
700                 info->connect = TRUE;
701                 info->animation = NULL;
702                 info->animation_timeout = 0;
703
704                 account_store = modest_runtime_get_account_store ();
705                 local_folders_account = MODEST_TNY_LOCAL_FOLDERS_ACCOUNT 
706                         (modest_tny_account_store_get_local_folders_account (account_store));
707
708                 /* Try to get the message, if it's already downloaded
709                    we don't need to connect */
710                 if (account) {
711                         TnyDevice *device;
712                         gboolean device_online;
713
714                         device = modest_runtime_get_device ();
715                         device_online = tny_device_is_online (device);
716                         if (!device_online || TNY_ACCOUNT (local_folders_account) == account) {
717                                 folder = tny_store_account_find_folder (TNY_STORE_ACCOUNT (account), uri, NULL);
718                         } else {
719                                 folder = NULL;
720                         }
721                 } else {
722                         folder = modest_tny_local_folders_account_get_merged_outbox (local_folders_account);
723                         g_object_unref (local_folders_account);
724                         info->connect = FALSE;
725                 }
726                 if (folder) {
727                         TnyMsg *msg = tny_folder_find_msg (folder, uri, NULL);
728                         if (msg) {
729                                 info->connect = FALSE;
730                                 g_object_unref (msg);
731                         } else {
732                                 info->connect = TRUE;
733                         }
734                         g_object_unref (folder);
735                 }
736
737                 /* We need to call it into an idle to get
738                    modest_platform_connect_and_perform into the main
739                    loop */
740                 g_idle_add (on_idle_open_message_performer, info);
741                 osso_retval = OSSO_OK;
742         } else {
743                 g_free (uri);
744                 osso_retval = OSSO_ERROR; 
745                 g_idle_add (notify_error_in_dbus_callback, NULL);
746         }
747
748         if (account)
749                 g_object_unref (account);
750         return osso_retval;
751 }
752
753 static void 
754 on_remove_msgs_finished (ModestMailOperation *mail_op,
755                          gpointer user_data)
756 {       
757         TnyHeader *header;
758         ModestWindow *top_win = NULL, *msg_view = NULL;
759
760         header = (TnyHeader *) user_data;
761
762         /* Get the main window if exists */
763         top_win = modest_window_mgr_get_current_top (modest_runtime_get_window_mgr());
764         if (!top_win) {
765                 g_object_unref (header);
766                 return;
767         }
768
769         if (modest_window_mgr_find_registered_header (modest_runtime_get_window_mgr(),
770                                                       header, &msg_view)) {
771                 if (MODEST_IS_MSG_VIEW_WINDOW (msg_view))
772                         modest_ui_actions_refresh_message_window_after_delete (MODEST_MSG_VIEW_WINDOW (msg_view));
773         }       
774         g_object_unref (header);
775
776         /* Refilter the header views explicitely */
777
778         /* TODO: call modest_window_mgr_refilter_header_views */
779         /* this call will go through all the windows, get the header views and refilter them */
780 }
781
782 static gpointer
783 thread_prepare_delete_message (gpointer userdata)
784 {
785         TnyList *headers = NULL, *tmp_headers = NULL;
786         TnyFolder *folder = NULL;
787         TnyIterator *iter = NULL; 
788         TnyHeader *header = NULL, *msg_header = NULL;
789         TnyMsg *msg = NULL;
790         TnyAccount *account = NULL;
791         char *uri;
792         gchar *uid = NULL;
793         ModestMailOperation *mail_op = NULL;
794         ModestWindow *top_win = NULL;
795
796         uri = (char *) userdata;
797
798         msg = find_message_by_url (uri, &account);
799         if (account)
800                 g_object_unref (account);
801
802         if (!msg) {
803                 g_debug ("%s: Could not find message '%s'", __FUNCTION__, uri);
804                 g_idle_add (notify_error_in_dbus_callback, NULL);
805                 g_free (uri);
806                 return FALSE; 
807         }
808
809         top_win = modest_window_mgr_get_current_top (modest_runtime_get_window_mgr());
810
811         folder = tny_msg_get_folder (msg);
812         if (!folder) {
813                 g_debug ("%s: Could not find folder (uri:'%s')", __FUNCTION__, uri);
814                 g_object_unref (msg);
815                 g_idle_add (notify_error_in_dbus_callback, NULL);
816                 g_free (uri);
817                 return FALSE; 
818         }
819
820         /* Get UID */
821         msg_header = tny_msg_get_header (msg);
822         uid = tny_header_dup_uid (msg_header);
823         g_object_unref (msg);
824         g_object_unref (msg_header);
825
826         headers = tny_simple_list_new ();
827         tny_folder_get_headers (folder, headers, TRUE, NULL);
828         iter = tny_list_create_iterator (headers);
829
830         while (!tny_iterator_is_done (iter)) {
831                 gchar *cur_id = NULL;
832
833                 header = TNY_HEADER (tny_iterator_get_current (iter));
834                 if (header)
835                         cur_id = tny_header_dup_uid (header);
836                 
837                 if (cur_id && uid && g_str_equal (cur_id, uid)) {
838                         g_free (cur_id);
839                         /* g_debug ("Found corresponding header from folder"); */
840                         break;
841                 }
842                 g_free (cur_id);
843
844                 if (header) {
845                         g_object_unref (header);
846                         header = NULL;
847                 }
848                 
849                 tny_iterator_next (iter);
850         }
851         g_free (uid);
852         g_object_unref (iter);
853         g_object_unref (headers);
854
855         if (header == NULL) {
856                 if (folder)
857                         g_object_unref (folder);
858                 g_idle_add (notify_error_in_dbus_callback, NULL);                       
859                 g_free (uri);
860                 return FALSE;
861         }
862                 
863         /* This is a GDK lock because we are an idle callback and
864          * the code below is or does Gtk+ code */
865         gdk_threads_enter (); /* CHECKED */
866
867         mail_op = modest_mail_operation_new (top_win ? G_OBJECT(top_win) : NULL);
868         modest_mail_operation_queue_add (modest_runtime_get_mail_operation_queue (), mail_op);
869
870         g_signal_connect (G_OBJECT (mail_op),
871                           "operation-finished",
872                           G_CALLBACK (on_remove_msgs_finished),
873                           g_object_ref (header));
874
875         tmp_headers = tny_simple_list_new ();
876         tny_list_append (tmp_headers, (GObject *) header);
877
878         modest_mail_operation_remove_msgs (mail_op, tmp_headers, FALSE);
879
880         g_object_unref (tmp_headers);
881         g_object_unref (G_OBJECT (mail_op));
882         gdk_threads_leave (); /* CHECKED */
883         
884         /* Clean */
885         if (header)
886                 g_object_unref (header);
887         g_free (uri);
888         
889         return FALSE;
890 }
891
892 static gboolean
893 on_idle_delete_message (gpointer user_data)
894 {
895         const char *uri = NULL;
896
897         uri = (char *) user_data;
898
899         g_thread_create (thread_prepare_delete_message, g_strdup (uri), FALSE, NULL);
900
901         return FALSE;
902         
903 }
904
905
906
907
908 static gint
909 on_delete_message (GArray *arguments, gpointer data, osso_rpc_t *retval)
910 {
911         /* Get the arguments: */
912         osso_rpc_t val = g_array_index (arguments,
913                              osso_rpc_t,
914                              MODEST_DBUS_DELETE_MESSAGE_ARG_URI);
915         gchar *uri = g_strdup (val.value.s);
916         
917         /* Use g_idle to context-switch into the application's thread: */
918         g_idle_add(on_idle_delete_message, (gpointer)uri);
919         
920         return OSSO_OK;
921 }
922
923 typedef struct _SendReceivePerformerData {
924         gchar *account_id;
925         gboolean manual;
926         ModestMailOperation *mail_op;
927 } SendReceivePerformerData;
928
929 static void send_receive_performer_data_free (SendReceivePerformerData *data)
930 {
931         if (data->mail_op) {
932                 g_object_unref (data->mail_op);
933         }
934         g_free (data->account_id);
935         g_slice_free (SendReceivePerformerData, data);
936 }
937
938 static gboolean
939 on_idle_send_receive(gpointer user_data)
940 {
941         gboolean auto_update;
942         SendReceivePerformerData *data = (SendReceivePerformerData *) user_data;
943         ModestConnectedVia connect_when;
944         gboolean right_connection = FALSE;
945
946         gdk_threads_enter (); /* CHECKED */
947
948         /* Check if the autoupdate feature is on */
949         auto_update = modest_conf_get_bool (modest_runtime_get_conf (), 
950                                             MODEST_CONF_AUTO_UPDATE, NULL);
951
952         if (auto_update) {
953                 /* Do send receive. Never set the current top window
954                    as we always assume that DBus send/receive requests
955                    are not user driven */
956
957                 connect_when = modest_conf_get_int (modest_runtime_get_conf (), 
958                                                     MODEST_CONF_UPDATE_WHEN_CONNECTED_BY, NULL);
959                 /* Perform a send and receive if the user selected to connect
960                    via any mean or if the current connection method is the
961                    same as the one specified by the user */
962                 if (connect_when == MODEST_CONNECTED_VIA_ANY ||
963                     connect_when == modest_platform_get_current_connection ()) {
964                         right_connection = TRUE;
965                 }
966         } else {
967                 /* Disable auto update */
968                 modest_platform_set_update_interval (0);
969         }
970
971         if ((auto_update && right_connection) || data->manual) {
972                 if (data->account_id) {
973                         modest_ui_actions_do_send_receive (data->account_id, data->manual, FALSE, data->manual, NULL);
974                 } else {
975                         modest_ui_actions_do_send_receive_all (NULL, data->manual, FALSE, data->manual);
976                 }
977         }
978
979         modest_mail_operation_queue_remove (modest_runtime_get_mail_operation_queue (),
980                                             data->mail_op);
981
982         send_receive_performer_data_free (data);
983
984         gdk_threads_leave (); /* CHECKED */
985         
986         return FALSE;
987 }
988
989 static gint 
990 on_dbus_method_dump_send_queues (DBusConnection *con, DBusMessage *message)
991 {
992         gchar *str;
993         
994         DBusMessage *reply;
995         dbus_uint32_t serial = 0;
996
997         GSList *account_names, *cursor;
998
999         str = g_strdup("\nsend queues\n"
1000                        "===========\n");
1001
1002         cursor = account_names = modest_account_mgr_account_names
1003                 (modest_runtime_get_account_mgr(), TRUE); /* only enabled accounts */
1004
1005         while (cursor) {
1006                 TnyAccount *acc;
1007                 gchar *tmp, *accname = (gchar*)cursor->data;
1008                 
1009                 tmp = g_strdup_printf ("%s", str);
1010                 g_free (str);
1011                 str = tmp;
1012                 
1013                 /* transport */
1014                 acc = modest_tny_account_store_get_server_account (
1015                         modest_runtime_get_account_store(), accname,
1016                         TNY_ACCOUNT_TYPE_TRANSPORT);
1017                 if (TNY_IS_ACCOUNT(acc)) {
1018                         gchar *tmp = NULL, *url = tny_account_get_url_string (acc);
1019                         ModestTnySendQueue *sendqueue =
1020                                 modest_runtime_get_send_queue (TNY_TRANSPORT_ACCOUNT(acc), TRUE);
1021
1022                         if (TNY_IS_SEND_QUEUE (sendqueue)) {
1023                                 gchar *queue_str = modest_tny_send_queue_to_string (sendqueue);
1024                         
1025                                 tmp = g_strdup_printf ("%s[%s]: '%s': %s\n%s",
1026                                                        str, accname, tny_account_get_id (acc), url,
1027                                                        queue_str);
1028                                 g_free(queue_str);
1029                                 g_free (str);
1030                                 str = tmp;
1031                         }
1032                         g_free (url);
1033
1034                         g_object_unref (acc);
1035                 }
1036                 
1037                 cursor = g_slist_next (cursor);
1038         }
1039         modest_account_mgr_free_account_names (account_names);
1040                                                          
1041         g_printerr (str);
1042         
1043         reply = dbus_message_new_method_return (message);
1044         if (reply) {
1045                 dbus_message_append_args (reply,
1046                                           DBUS_TYPE_STRING, &str,
1047                                           DBUS_TYPE_INVALID);
1048                 dbus_connection_send (con, reply, &serial);
1049                 dbus_connection_flush (con);
1050                 dbus_message_unref (reply);
1051         }
1052         g_free (str);
1053
1054         /* Let modest die */
1055         g_idle_add (notify_error_in_dbus_callback, NULL);
1056
1057         return OSSO_OK;
1058 }
1059
1060
1061 static gint 
1062 on_dbus_method_dump_operation_queue (DBusConnection *con, DBusMessage *message)
1063 {
1064         gchar *str;
1065         gchar *op_queue_str;
1066         
1067         DBusMessage *reply;
1068         dbus_uint32_t serial = 0;
1069
1070         /* operations queue; */
1071         op_queue_str = modest_mail_operation_queue_to_string
1072                 (modest_runtime_get_mail_operation_queue ());
1073                 
1074         str = g_strdup_printf ("\noperation queue\n"
1075                                "===============\n"
1076                                "status: %s\n"
1077                                "%s\n",
1078                                tny_device_is_online (modest_runtime_get_device ()) ? "online" : "offline",
1079                                op_queue_str);
1080         g_free (op_queue_str);
1081         
1082         g_printerr (str);
1083         
1084         reply = dbus_message_new_method_return (message);
1085         if (reply) {
1086                 dbus_message_append_args (reply,
1087                                           DBUS_TYPE_STRING, &str,
1088                                           DBUS_TYPE_INVALID);
1089                 dbus_connection_send (con, reply, &serial);
1090                 dbus_connection_flush (con);
1091                 dbus_message_unref (reply);
1092         }       
1093         g_free (str);
1094
1095         /* Let modest die */
1096         g_idle_add (notify_error_in_dbus_callback, NULL);
1097
1098         return OSSO_OK;
1099 }
1100
1101
1102
1103 static gint 
1104 on_dbus_method_dump_accounts (DBusConnection *con, DBusMessage *message)
1105 {
1106         gchar *str;
1107         
1108         DBusMessage *reply;
1109         dbus_uint32_t serial = 0;
1110
1111         GSList *account_names, *cursor;
1112
1113         str = g_strdup ("\naccounts\n========\n");
1114
1115         cursor = account_names = modest_account_mgr_account_names
1116                 (modest_runtime_get_account_mgr(), TRUE); /* only enabled accounts */
1117
1118         while (cursor) {
1119                 TnyAccount *acc;
1120                 gchar *tmp, *accname = (gchar*)cursor->data;
1121
1122                 tmp = g_strdup_printf ("%s[%s]\n", str, accname);
1123                 g_free (str);
1124                 str = tmp;
1125                 
1126                 /* store */
1127                 acc = modest_tny_account_store_get_server_account (
1128                         modest_runtime_get_account_store(), accname,
1129                         TNY_ACCOUNT_TYPE_STORE);
1130                 if (TNY_IS_ACCOUNT(acc)) {
1131                         gchar *tmp, *url = tny_account_get_url_string (acc);
1132                         tmp = g_strdup_printf ("%sstore    : '%s': %s (refs: %d)\n",
1133                                                str, tny_account_get_id (acc), url, 
1134                                                ((GObject*)acc)->ref_count-1);
1135                         g_free (str);
1136                         str = tmp;
1137                         g_free (url);
1138                         g_object_unref (acc);
1139                 }
1140                 
1141                 /* transport */
1142                 acc = modest_tny_account_store_get_server_account (
1143                         modest_runtime_get_account_store(), accname,
1144                         TNY_ACCOUNT_TYPE_TRANSPORT);
1145                 if (TNY_IS_ACCOUNT(acc)) {
1146                         gchar *tmp, *url = tny_account_get_url_string (acc);
1147                         tmp = g_strdup_printf ("%stransport: '%s': %s (refs: %d)\n",
1148                                                str, tny_account_get_id (acc), url, 
1149                                                ((GObject*)acc)->ref_count-1);
1150                         g_free (str);
1151                         str = tmp;
1152                         g_free (url);
1153                         g_object_unref (acc);
1154                 }
1155                 
1156                 cursor = g_slist_next (cursor);
1157         }
1158         
1159         modest_account_mgr_free_account_names (account_names);
1160                                                          
1161         g_printerr (str);
1162         
1163         reply = dbus_message_new_method_return (message);
1164         if (reply) {
1165                 dbus_message_append_args (reply,
1166                                           DBUS_TYPE_STRING, &str,
1167                                           DBUS_TYPE_INVALID);
1168                 dbus_connection_send (con, reply, &serial);
1169                 dbus_connection_flush (con);
1170                 dbus_message_unref (reply);
1171         }       
1172         g_free (str);
1173
1174         /* Let modest die */
1175         g_idle_add (notify_error_in_dbus_callback, NULL);
1176
1177         return OSSO_OK;
1178 }
1179
1180 static void
1181 on_send_receive_performer(gboolean canceled, 
1182                           GError *err,
1183                           ModestWindow *parent_window,
1184                           TnyAccount *account,
1185                           gpointer user_data)
1186 {
1187         SendReceivePerformerData *data = (SendReceivePerformerData *) user_data;
1188
1189         if (err || canceled || data == NULL) {
1190                 g_idle_add (notify_error_in_dbus_callback, NULL);
1191                 if (data) {
1192                         send_receive_performer_data_free (data);
1193                 }
1194                 return;
1195         }
1196
1197         data->mail_op = modest_mail_operation_new (NULL);
1198         modest_mail_operation_queue_add (modest_runtime_get_mail_operation_queue (),
1199                                          data->mail_op);
1200         if (data->manual) {
1201                 g_idle_add (on_idle_send_receive, data);
1202         } else {
1203                 modest_heartbeat_add (on_idle_send_receive, data);
1204         }
1205 }
1206
1207
1208 static gint
1209 on_send_receive(GArray *arguments, gpointer data, osso_rpc_t * retval)
1210 {
1211         TnyDevice *device = modest_runtime_get_device ();
1212         SendReceivePerformerData *srp_data;
1213
1214         srp_data = g_slice_new0 (SendReceivePerformerData);
1215         srp_data->account_id = NULL;
1216         srp_data->manual = FALSE;
1217         srp_data->mail_op = NULL;
1218
1219         if (!tny_device_is_online (device))
1220                 modest_platform_connect_and_perform (NULL, FALSE, NULL, on_send_receive_performer, srp_data);
1221         else
1222                 on_send_receive_performer (FALSE, NULL, NULL, NULL, srp_data);
1223
1224         return OSSO_OK;
1225 }
1226
1227 static gint
1228 on_send_receive_full (GArray *arguments, gpointer data, osso_rpc_t * retval)
1229 {
1230         osso_rpc_t val;
1231         gchar *account_id;
1232         gboolean manual;
1233         TnyDevice *device;
1234         SendReceivePerformerData *srp_data;
1235
1236         val = g_array_index (arguments, osso_rpc_t, MODEST_DBUS_SEND_RECEIVE_FULL_ARG_ACCOUNT_ID);
1237         account_id = g_strdup (val.value.s);
1238         val = g_array_index (arguments, osso_rpc_t, MODEST_DBUS_SEND_RECEIVE_FULL_ARG_MANUAL);
1239         manual = val.value.b;
1240
1241         srp_data = g_slice_new0 (SendReceivePerformerData);
1242         srp_data->manual = manual;
1243         if (account_id && account_id[0] != '\0') {
1244                 srp_data->account_id = account_id;
1245         } else {
1246                 srp_data->account_id = NULL;
1247                 g_free (account_id);
1248         }
1249         srp_data->mail_op = NULL;
1250         device = modest_runtime_get_device ();
1251         if (!tny_device_is_online (device))
1252                 modest_platform_connect_and_perform (NULL, FALSE, NULL, on_send_receive_performer, srp_data);
1253         else
1254                 on_send_receive_performer (FALSE, NULL, NULL, NULL, srp_data);
1255
1256         return OSSO_OK;
1257 }
1258
1259 static gboolean
1260 on_idle_update_folder_counts (gpointer userdata)
1261 {
1262         ModestMailOperation *mail_op;
1263         gchar *account_id = (gchar *) userdata;
1264
1265         mail_op = modest_mail_operation_new (NULL);
1266         modest_mail_operation_queue_add (modest_runtime_get_mail_operation_queue (),
1267                                          mail_op);
1268         modest_mail_operation_update_folder_counts (mail_op, account_id);
1269         g_object_unref (mail_op);
1270         g_free (account_id);
1271
1272         return FALSE;
1273
1274 }
1275
1276 static gint
1277 on_update_folder_counts (GArray *arguments, gpointer data, osso_rpc_t * retval)
1278 {
1279         osso_rpc_t val;
1280         gchar *account_id;
1281
1282         val = g_array_index (arguments, osso_rpc_t, MODEST_DBUS_SEND_RECEIVE_FULL_ARG_ACCOUNT_ID);
1283         account_id = g_strdup (val.value.s);
1284
1285         if (account_id != NULL) {
1286                 g_idle_add (on_idle_update_folder_counts, g_strdup (account_id));
1287         }
1288
1289         g_free (account_id);
1290
1291         return OSSO_OK;
1292 }
1293
1294 static gint
1295 on_open_default_inbox(GArray * arguments, gpointer data, osso_rpc_t * retval)
1296 {
1297         g_idle_add(on_idle_top_application, NULL);
1298
1299         return OSSO_OK;
1300 }
1301
1302
1303 static gboolean
1304 on_idle_open_account (gpointer user_data)
1305 {
1306         ModestWindow *top;
1307         ModestWindowMgr *mgr;
1308         gchar *acc_name;
1309
1310         gdk_threads_enter ();
1311
1312         acc_name = (gchar *) user_data;
1313         mgr = modest_runtime_get_window_mgr ();
1314
1315         top = modest_window_mgr_get_current_top (mgr);
1316         if (!top)
1317                 top = modest_window_mgr_show_initial_window (mgr);
1318
1319 #ifdef MODEST_TOOLKIT_HILDON2
1320         GtkWidget *new_window;
1321         ModestProtocolType store_protocol;
1322         gboolean mailboxes_protocol;
1323
1324         store_protocol = modest_account_mgr_get_store_protocol (modest_runtime_get_account_mgr (), 
1325                                                                 acc_name);
1326         mailboxes_protocol = 
1327                 modest_protocol_registry_protocol_type_has_tag (modest_runtime_get_protocol_registry (),
1328                                                                 store_protocol,
1329                                                                 MODEST_PROTOCOL_REGISTRY_MULTI_MAILBOX_PROVIDER_PROTOCOLS);
1330
1331         if (mailboxes_protocol) {
1332                 new_window = GTK_WIDGET (modest_mailboxes_window_new (acc_name));
1333         } else {
1334                 new_window = GTK_WIDGET (modest_folder_window_new (NULL));
1335                 modest_folder_window_set_account (MODEST_FOLDER_WINDOW (new_window),
1336                                                   acc_name);
1337         }
1338
1339         if (modest_window_mgr_register_window (mgr, MODEST_WINDOW (new_window), NULL)) {
1340                 gtk_widget_show (new_window);
1341         } else {
1342                 gtk_widget_destroy (new_window);
1343                 new_window = NULL;
1344         }
1345 #else
1346         if (MODEST_IS_MAIN_WINDOW (top)) {
1347                 gchar *server_name;
1348                 GtkWidget *folder_view;
1349
1350                 folder_view = modest_main_window_get_child_widget (MODEST_MAIN_WINDOW (top),
1351                                                                    MODEST_MAIN_WINDOW_WIDGET_TYPE_FOLDER_VIEW);
1352                 server_name = modest_account_mgr_get_server_account_name (modest_runtime_get_account_mgr (), 
1353                                                                           acc_name, TNY_ACCOUNT_TYPE_STORE);
1354                 if (server_name) {
1355                         modest_folder_view_set_account_id_of_visible_server_account (MODEST_FOLDER_VIEW (folder_view),
1356                                                                                      server_name);
1357                         g_free (server_name);
1358                 }
1359         }
1360 #endif
1361
1362         gdk_threads_leave ();
1363         g_free (acc_name);
1364         return FALSE;
1365 }
1366
1367 static gint
1368 on_open_account (GArray *arguments, gpointer data, osso_rpc_t *retval)
1369 {
1370         osso_rpc_t val;
1371         gchar *account_id;
1372
1373         /* Get the arguments: */
1374         val = g_array_index(arguments, osso_rpc_t, MODEST_DBUS_OPEN_MESSAGE_ARG_URI);
1375         account_id = g_strdup (val.value.s);
1376
1377         g_idle_add (on_idle_open_account, account_id);
1378
1379         return OSSO_OK;
1380 }
1381
1382 #ifdef MODEST_TOOLKIT_HILDON2
1383 static gboolean
1384 on_idle_top_application (gpointer user_data)
1385 {
1386         HildonWindowStack *stack;
1387         GtkWidget *window;
1388
1389         /* This is a GDK lock because we are an idle callback and
1390          * the code below is or does Gtk+ code */
1391
1392         gdk_threads_enter (); /* CHECKED */
1393
1394         stack = hildon_window_stack_get_default ();
1395         window = GTK_WIDGET (hildon_window_stack_peek (stack));
1396
1397         if (window) {
1398                 gtk_window_present (GTK_WINDOW (window));
1399         } else {
1400                 ModestWindowMgr *mgr;
1401
1402                 mgr = modest_runtime_get_window_mgr ();
1403                 window = (GtkWidget *) modest_window_mgr_show_initial_window (mgr);
1404         }
1405
1406         gdk_threads_leave (); /* CHECKED */
1407
1408         return FALSE; /* Do not call this callback again. */
1409 }
1410 #else
1411 static gboolean
1412 on_idle_top_application (gpointer user_data)
1413 {
1414         ModestWindow *main_win;
1415         gboolean new_window = FALSE;
1416
1417         /* This is a GDK lock because we are an idle callback and
1418          * the code below is or does Gtk+ code */
1419
1420         gdk_threads_enter (); /* CHECKED */
1421
1422         main_win = modest_window_mgr_get_main_window (modest_runtime_get_window_mgr (),
1423                                                       FALSE);
1424
1425         if (!main_win) {
1426                 main_win = modest_window_mgr_get_main_window (modest_runtime_get_window_mgr (),
1427                                                               TRUE);
1428                 new_window = TRUE;
1429         }
1430
1431         if (main_win) {
1432                 /* If we're showing an already existing window then
1433                    reselect the INBOX */
1434                 if (!new_window) {
1435                         GtkWidget *folder_view;
1436                         folder_view = modest_main_window_get_child_widget (MODEST_MAIN_WINDOW (main_win),
1437                                                                            MODEST_MAIN_WINDOW_WIDGET_TYPE_FOLDER_VIEW);
1438                         modest_folder_view_select_first_inbox_or_local (MODEST_FOLDER_VIEW (folder_view));
1439                 }
1440         }
1441
1442         if (main_win) {
1443                 gtk_widget_show_all (GTK_WIDGET (main_win));
1444                 gtk_window_present (GTK_WINDOW (main_win));
1445         }
1446
1447         gdk_threads_leave (); /* CHECKED */
1448
1449         return FALSE; /* Do not call this callback again. */
1450 }
1451 #endif
1452
1453 static gint
1454 on_top_application(GArray * arguments, gpointer data, osso_rpc_t * retval)
1455 {
1456         /* Use g_idle to context-switch into the application's thread: */
1457         g_idle_add(on_idle_top_application, NULL);
1458
1459         return OSSO_OK;
1460 }
1461
1462 static gboolean
1463 on_idle_open_edit_accounts_dialog (gpointer user_data)
1464 {
1465         ModestWindow *top;
1466         ModestWindowMgr *mgr;
1467         gboolean closed;
1468
1469         /* This is a GDK lock because we are an idle callback and
1470          * the code below is or does Gtk+ code */
1471
1472         gdk_threads_enter (); /* CHECKED */
1473
1474         mgr = modest_runtime_get_window_mgr ();
1475         closed = modest_window_mgr_close_all_but_initial (mgr);
1476         top = modest_window_mgr_get_current_top (mgr);
1477
1478         if (closed) {
1479                 /* Show edit accounts dialog */
1480                 modest_ui_actions_on_accounts (NULL, top);
1481         } else {
1482                 gboolean has_accounts;
1483
1484                 has_accounts = modest_account_mgr_has_accounts (modest_runtime_get_account_mgr (),
1485                                                                 TRUE);
1486
1487                 /* Present the current top window */
1488                 gdk_threads_leave ();
1489                 on_idle_top_application (NULL);
1490                 gdk_threads_enter ();
1491
1492                 /* Show edit accounts dialog if we're launching the
1493                    program and there is no account (if there is at
1494                    least one account then on_idle_top_application will
1495                    show the accounts wizard */
1496                 if (!top && has_accounts) {
1497                         top = modest_window_mgr_get_current_top (mgr);
1498                         modest_ui_actions_on_accounts (NULL, top);
1499                 }
1500         }
1501
1502         gdk_threads_leave (); /* CHECKED */
1503
1504         return FALSE; /* Do not call this callback again. */
1505 }
1506
1507 static gint
1508 on_open_edit_accounts_dialog (GArray * arguments, gpointer data, osso_rpc_t * retval)
1509 {
1510         /* Use g_idle to context-switch into the application's thread: */
1511         g_idle_add (on_idle_open_edit_accounts_dialog, NULL);
1512
1513         return OSSO_OK;
1514 }
1515
1516 static gboolean 
1517 on_idle_show_memory_low (gpointer user_data)
1518 {
1519         ModestWindow *main_win = NULL;
1520
1521         gdk_threads_enter ();
1522         main_win = modest_window_mgr_get_current_top (modest_runtime_get_window_mgr ());
1523         modest_platform_run_information_dialog (GTK_WINDOW (main_win),
1524                                                 dgettext("ke-recv","memr_ib_operation_disabled"),
1525                                                 TRUE);
1526         gdk_threads_leave ();
1527
1528         return FALSE;
1529 }
1530
1531 static gboolean
1532 on_idle_present_modal (gpointer user_data)
1533 {
1534         GtkWindow *current, *transient;
1535         gdk_threads_enter ();
1536         current = (GtkWindow *) user_data;
1537         while (GTK_IS_DIALOG (current)) {
1538                 transient = gtk_window_get_transient_for (GTK_WINDOW (current));
1539                 if (transient == NULL)
1540                         break;
1541                 else
1542                         current = transient;
1543         }
1544         gtk_window_present (current);
1545         gdk_threads_leave ();
1546
1547         return FALSE;
1548 }
1549
1550 /**
1551   * This function checks if a modal dialog should be activated
1552   * instead of other UI components on a DBus request, and if yes, starts the request
1553   * @return TRUE if a modal dialog is about to be acitvated
1554   * @note This function should be used before activating any Modest UI element on DBus request
1555   */
1556 static gboolean
1557 modest_dbus_check_present_modal ()
1558 {
1559         GtkWindow *dialog;
1560
1561         /* Check if there is already a dialog or note open */
1562         dialog = modest_window_mgr_get_modal (modest_runtime_get_window_mgr());
1563         if (dialog) {
1564                 g_idle_add (on_idle_present_modal, dialog);
1565         }
1566
1567         return (NULL != dialog);
1568 }
1569
1570 /* Callback for normal D-BUS messages */
1571 gint
1572 modest_dbus_req_handler(const gchar * interface, const gchar * method,
1573                         GArray * arguments, gpointer data,
1574                         osso_rpc_t * retval)
1575 {
1576         /* Check memory low conditions */
1577         if (modest_platform_check_memory_low (NULL, FALSE)) {
1578                 g_idle_add (on_idle_show_memory_low, NULL);
1579                 goto param_error;
1580         }
1581
1582         if (g_ascii_strcasecmp (method, MODEST_DBUS_METHOD_MAIL_TO) == 0) {
1583                 if (arguments->len != MODEST_DBUS_MAIL_TO_ARGS_COUNT)
1584                         goto param_error;
1585                 return modest_dbus_check_present_modal () ? OSSO_OK : on_mail_to (arguments, data, retval);
1586         } else if (g_ascii_strcasecmp (method, MODEST_DBUS_METHOD_OPEN_MESSAGE) == 0) {
1587                 if (arguments->len != MODEST_DBUS_OPEN_MESSAGE_ARGS_COUNT)
1588                         goto param_error;
1589                 return modest_dbus_check_present_modal () ? OSSO_OK : on_open_message (arguments, data, retval);
1590         } else if (g_ascii_strcasecmp (method, MODEST_DBUS_METHOD_OPEN_ACCOUNT) == 0) {
1591                 if (arguments->len != MODEST_DBUS_OPEN_ACCOUNT_ARGS_COUNT)
1592                         goto param_error;
1593                 return modest_dbus_check_present_modal () ? OSSO_OK : on_open_account (arguments, data, retval);
1594         } else if (g_ascii_strcasecmp (method, MODEST_DBUS_METHOD_SEND_RECEIVE) == 0) {
1595                 if (arguments->len != 0)
1596                         goto param_error;
1597                 return modest_dbus_check_present_modal () ? OSSO_OK : on_send_receive (arguments, data, retval);
1598         } else if (g_ascii_strcasecmp (method, MODEST_DBUS_METHOD_SEND_RECEIVE_FULL) == 0) {
1599                 if (arguments->len != MODEST_DBUS_SEND_RECEIVE_FULL_ARGS_COUNT)
1600                         goto param_error;
1601                 return modest_dbus_check_present_modal () ? OSSO_OK : on_send_receive_full (arguments, data, retval);
1602         } else if (g_ascii_strcasecmp (method, MODEST_DBUS_METHOD_UPDATE_FOLDER_COUNTS) == 0) {
1603                 if (arguments->len != MODEST_DBUS_UPDATE_FOLDER_COUNTS_ARGS_COUNT)
1604                         goto param_error;
1605                 return on_update_folder_counts (arguments, data, retval);
1606         } else if (g_ascii_strcasecmp (method, MODEST_DBUS_METHOD_COMPOSE_MAIL) == 0) {
1607                 if (arguments->len != MODEST_DBUS_COMPOSE_MAIL_ARGS_COUNT)
1608                         goto param_error;
1609                 return modest_dbus_check_present_modal () ? OSSO_OK : on_compose_mail (arguments, data, retval);
1610         } else if (g_ascii_strcasecmp (method, MODEST_DBUS_METHOD_DELETE_MESSAGE) == 0) {
1611                 if (arguments->len != MODEST_DBUS_DELETE_MESSAGE_ARGS_COUNT)
1612                         goto param_error;
1613                 return modest_dbus_check_present_modal () ? OSSO_OK : on_delete_message (arguments,data, retval);
1614         } else if (g_ascii_strcasecmp (method, MODEST_DBUS_METHOD_OPEN_DEFAULT_INBOX) == 0) {
1615                 if (arguments->len != 0)
1616                         goto param_error;
1617                 return modest_dbus_check_present_modal () ? OSSO_OK : on_open_default_inbox (arguments, data, retval);
1618         } else if (g_ascii_strcasecmp (method, MODEST_DBUS_METHOD_TOP_APPLICATION) == 0) {
1619                 if (arguments->len != 0)
1620                         goto param_error;
1621                 return modest_dbus_check_present_modal () ? OSSO_OK : on_top_application (arguments, data, retval);
1622         } else if (g_ascii_strcasecmp (method, MODEST_DBUS_METHOD_OPEN_EDIT_ACCOUNTS_DIALOG) == 0) {
1623                 if (arguments->len != 0)
1624                         goto param_error;
1625                 return modest_dbus_check_present_modal () ? OSSO_OK : on_open_edit_accounts_dialog (arguments, data, retval);
1626         } else {
1627                 /* We need to return INVALID here so
1628                  * libosso will return DBUS_HANDLER_RESULT_NOT_YET_HANDLED,
1629                  * so that our modest_dbus_req_filter will then be tried instead.
1630                  * */
1631                 return OSSO_INVALID;
1632         }
1633  param_error:
1634         /* Notify error in D-Bus method */
1635         g_idle_add (notify_error_in_dbus_callback, NULL);
1636         return OSSO_ERROR;
1637 }
1638
1639 /* A complex D-Bus type (like a struct),
1640  * used to return various information about a search hit.
1641  */
1642 #define SEARCH_HIT_DBUS_TYPE \
1643         DBUS_STRUCT_BEGIN_CHAR_AS_STRING \
1644         DBUS_TYPE_STRING_AS_STRING /* msgid */ \
1645         DBUS_TYPE_STRING_AS_STRING /* subject */ \
1646         DBUS_TYPE_STRING_AS_STRING /* folder */ \
1647         DBUS_TYPE_STRING_AS_STRING /* sender */ \
1648         DBUS_TYPE_UINT64_AS_STRING /* msize */ \
1649         DBUS_TYPE_BOOLEAN_AS_STRING /* has_attachment */ \
1650         DBUS_TYPE_BOOLEAN_AS_STRING /* is_unread */ \
1651         DBUS_TYPE_INT64_AS_STRING /* timestamp */ \
1652         DBUS_STRUCT_END_CHAR_AS_STRING
1653
1654 #define ACCOUNT_HIT_DBUS_TYPE \
1655         DBUS_STRUCT_BEGIN_CHAR_AS_STRING \
1656         DBUS_TYPE_INT64_AS_STRING /* timestamp */ \
1657         DBUS_TYPE_STRING_AS_STRING /* subject */ \
1658         DBUS_STRUCT_END_CHAR_AS_STRING
1659
1660
1661 #define ACCOUNTS_HIT_DBUS_TYPE \
1662         DBUS_STRUCT_BEGIN_CHAR_AS_STRING \
1663         DBUS_TYPE_STRING_AS_STRING \
1664         DBUS_TYPE_STRING_AS_STRING \
1665         DBUS_TYPE_STRING_AS_STRING \
1666         DBUS_TYPE_INT64_AS_STRING \
1667         DBUS_TYPE_ARRAY_AS_STRING \
1668         ACCOUNT_HIT_DBUS_TYPE \
1669         DBUS_STRUCT_END_CHAR_AS_STRING
1670
1671 static DBusMessage *
1672 search_result_to_message (DBusMessage *reply,
1673                            GList       *hits)
1674 {
1675         DBusMessageIter iter;
1676         DBusMessageIter array_iter;
1677         GList          *hit_iter;
1678
1679         dbus_message_iter_init_append (reply, &iter); 
1680         dbus_message_iter_open_container (&iter,
1681                                           DBUS_TYPE_ARRAY,
1682                                           SEARCH_HIT_DBUS_TYPE,
1683                                           &array_iter); 
1684
1685         for (hit_iter = hits; hit_iter; hit_iter = hit_iter->next) {
1686                 DBusMessageIter  struct_iter;
1687                 ModestSearchResultHit *hit;
1688                 char            *msg_url;
1689                 const char      *subject;
1690                 const char      *folder;
1691                 const char      *sender;
1692                 guint64          size;
1693                 gboolean         has_attachment;
1694                 gboolean         is_unread;
1695                 gint64           ts;
1696
1697                 hit = (ModestSearchResultHit *) hit_iter->data;
1698
1699                 msg_url = hit->msgid;
1700                 subject = hit->subject;
1701                 folder  = hit->folder;
1702                 sender  = hit->sender;
1703                 size           = hit->msize;
1704                 has_attachment = hit->has_attachment;
1705                 is_unread      = hit->is_unread;
1706                 ts             = hit->timestamp;
1707
1708                 g_debug ("DEBUG: %s: Adding hit: %s", __FUNCTION__, msg_url);   
1709                 
1710                 dbus_message_iter_open_container (&array_iter,
1711                                                   DBUS_TYPE_STRUCT,
1712                                                   NULL,
1713                                                   &struct_iter);
1714
1715                 dbus_message_iter_append_basic (&struct_iter,
1716                                                 DBUS_TYPE_STRING,
1717                                                 &msg_url);
1718
1719                 dbus_message_iter_append_basic (&struct_iter,
1720                                                 DBUS_TYPE_STRING,
1721                                                 &subject); 
1722
1723                 dbus_message_iter_append_basic (&struct_iter,
1724                                                 DBUS_TYPE_STRING,
1725                                                 &folder);
1726
1727                 dbus_message_iter_append_basic (&struct_iter,
1728                                                 DBUS_TYPE_STRING,
1729                                                 &sender);
1730
1731                 dbus_message_iter_append_basic (&struct_iter,
1732                                                 DBUS_TYPE_UINT64,
1733                                                 &size);
1734
1735                 dbus_message_iter_append_basic (&struct_iter,
1736                                                 DBUS_TYPE_BOOLEAN,
1737                                                 &has_attachment);
1738
1739                 dbus_message_iter_append_basic (&struct_iter,
1740                                                 DBUS_TYPE_BOOLEAN,
1741                                                 &is_unread);
1742                 
1743                 dbus_message_iter_append_basic (&struct_iter,
1744                                                 DBUS_TYPE_INT64,
1745                                                 &ts);
1746
1747                 dbus_message_iter_close_container (&array_iter,
1748                                                    &struct_iter); 
1749
1750                 g_free (hit->msgid);
1751                 g_free (hit->subject);
1752                 g_free (hit->folder);
1753                 g_free (hit->sender);
1754
1755                 g_slice_free (ModestSearchResultHit, hit);
1756         }
1757
1758         dbus_message_iter_close_container (&iter, &array_iter);
1759
1760         return reply;
1761 }
1762
1763 typedef struct
1764 {
1765         DBusConnection *con;
1766         DBusMessage *message;
1767         ModestSearch *search;
1768 } SearchHelper;
1769
1770 static void
1771 search_all_cb (GList *hits, gpointer user_data)
1772 {
1773         DBusMessage  *reply;
1774         SearchHelper *helper = (SearchHelper *) user_data;
1775
1776         reply = dbus_message_new_method_return (helper->message);
1777
1778         if (reply) {
1779                 dbus_uint32_t serial = 0;
1780                 
1781                 search_result_to_message (reply, hits);
1782
1783                 dbus_connection_send (helper->con, reply, &serial);
1784                 dbus_connection_flush (helper->con);
1785                 dbus_message_unref (reply);
1786         }
1787
1788         /* Free the helper */
1789         dbus_message_unref (helper->message);
1790         modest_search_free (helper->search);
1791         g_slice_free (ModestSearch, helper->search);
1792         g_slice_free (SearchHelper, helper);
1793 }
1794
1795 static void
1796 on_dbus_method_search (DBusConnection *con, DBusMessage *message)
1797 {
1798         ModestDBusSearchFlags dbus_flags;
1799         dbus_bool_t  res;
1800         dbus_int64_t sd_v;
1801         dbus_int64_t ed_v;
1802         dbus_int32_t flags_v;
1803         dbus_uint32_t size_v;
1804         const char *folder;
1805         const char *query;
1806         time_t start_date;
1807         time_t end_date;
1808         ModestSearch *search;
1809         DBusError error;
1810
1811         dbus_error_init (&error);
1812
1813         sd_v = ed_v = 0;
1814         flags_v = 0;
1815
1816         res = dbus_message_get_args (message,
1817                                      &error,
1818                                      DBUS_TYPE_STRING, &query,
1819                                      DBUS_TYPE_STRING, &folder, /* e.g. "INBOX/drafts": TODO: Use both an ID and a display name. */
1820                                      DBUS_TYPE_INT64, &sd_v,
1821                                      DBUS_TYPE_INT64, &ed_v,
1822                                      DBUS_TYPE_INT32, &flags_v,
1823                                      DBUS_TYPE_UINT32, &size_v,
1824                                      DBUS_TYPE_INVALID);
1825
1826         dbus_flags = (ModestDBusSearchFlags) flags_v;
1827         start_date = (time_t) sd_v;
1828         end_date = (time_t) ed_v;
1829
1830         search = g_slice_new0 (ModestSearch);
1831         
1832         if (folder && g_str_has_prefix (folder, "MAND:")) {
1833                 search->folder = g_strdup (folder + strlen ("MAND:"));
1834         } else if (folder && g_str_has_prefix (folder, "USER:")) {
1835                 search->folder = g_strdup (folder + strlen ("USER:"));
1836         } else if (folder && g_str_has_prefix (folder, "MY:")) {
1837                 search->folder = g_strdup (folder + strlen ("MY:"));
1838         } else {
1839                 search->folder = g_strdup (folder);
1840         }
1841
1842    /* Remember the text to search for: */
1843 #ifdef MODEST_HAVE_OGS
1844         search->query  = g_strdup (query);
1845 #endif
1846
1847         /* Other criteria: */
1848         search->start_date = start_date;
1849         search->end_date  = end_date;
1850         search->flags = 0;
1851
1852         /* Text to serach for in various parts of the message: */
1853         if (dbus_flags & MODEST_DBUS_SEARCH_SUBJECT) {
1854                 search->flags |= MODEST_SEARCH_SUBJECT;
1855                 search->subject = g_strdup (query);
1856         }
1857
1858         if (dbus_flags & MODEST_DBUS_SEARCH_SENDER) {
1859                 search->flags |=  MODEST_SEARCH_SENDER;
1860                 search->from = g_strdup (query);
1861         }
1862
1863         if (dbus_flags & MODEST_DBUS_SEARCH_RECIPIENT) {
1864                 search->flags |= MODEST_SEARCH_RECIPIENT; 
1865                 search->recipient = g_strdup (query);
1866         }
1867
1868         if (dbus_flags & MODEST_DBUS_SEARCH_BODY) {
1869                 search->flags |=  MODEST_SEARCH_BODY; 
1870                 search->body = g_strdup (query);
1871         }
1872
1873         if (sd_v > 0) {
1874                 search->flags |= MODEST_SEARCH_AFTER;
1875                 search->start_date = start_date;
1876         }
1877
1878         if (ed_v > 0) {
1879                 search->flags |= MODEST_SEARCH_BEFORE;
1880                 search->end_date = end_date;
1881         }
1882
1883         if (size_v > 0) {
1884                 search->flags |= MODEST_SEARCH_SIZE;
1885                 search->minsize = size_v;
1886         }
1887
1888 #ifdef MODEST_HAVE_OGS
1889         search->flags |= MODEST_SEARCH_USE_OGS;
1890         g_debug ("%s: Starting search for %s", __FUNCTION__, search->query);
1891 #endif
1892
1893         SearchHelper *helper = g_slice_new (SearchHelper);
1894         helper->search = search;
1895         dbus_message_ref (message);
1896         helper->message = message;
1897         helper->con = con;
1898
1899         /* Search asynchronously */
1900         modest_search_all_accounts (search, search_all_cb, helper);
1901 }
1902
1903 static gint
1904 headers_cmp (TnyHeader *a, TnyHeader *b)
1905 {
1906         time_t date_a, date_b;
1907         date_a = tny_header_get_date_received (a);
1908         date_b = tny_header_get_date_received (b);
1909
1910         return date_a - date_b;
1911 }
1912
1913 /**
1914   * The helper structure for handling GetUnreadMessages DBus request
1915   */
1916 typedef struct {
1917         TnyList *accounts_list;
1918         TnyList *inboxes_list;
1919         gint unread_msgs_count;
1920         DBusConnection *con;
1921         DBusMessage *message;
1922         GList *account_hits_list;
1923         ModestMailOperation *mail_op;
1924         guint folder_requests_total; /**< Total get-folder requests number for multi-mailbox accounts */
1925         guint folder_requests_done; /**< Done get-folder requests number for multi-mailbox accounts */
1926 } GetUnreadMessagesHelper;
1927
1928 typedef struct {
1929         gchar *account_id;
1930         gchar *account_name;
1931         gchar *store_protocol;
1932         gchar *mailbox_id;
1933         gint unread_count;
1934         GList *header_list;
1935 } AccountHits;
1936
1937 static void return_results (GetUnreadMessagesHelper *helper)
1938 {
1939         DBusMessage *reply;
1940
1941         reply = dbus_message_new_method_return (helper->message);
1942         if (reply) {
1943                 dbus_uint32_t serial = 0;
1944                 GList *node;
1945                 DBusMessageIter iter;
1946                 DBusMessageIter array_iter;
1947
1948                 dbus_message_iter_init_append (reply, &iter);
1949                 dbus_message_iter_open_container (&iter,
1950                                                   DBUS_TYPE_ARRAY,
1951                                                   ACCOUNTS_HIT_DBUS_TYPE,
1952                                                   &array_iter);
1953                 for (node = helper->account_hits_list; node != NULL; node = g_list_next (node)) {
1954                         AccountHits *ah = (AccountHits *) node->data;
1955                         const char *account_id;
1956                         const char *account_name;
1957                         const char *store_protocol;
1958                         gint64 unread_count;
1959                         DBusMessageIter ah_struct_iter;
1960                         DBusMessageIter sh_array_iter;
1961                         GList *result_node;
1962
1963                         dbus_message_iter_open_container (&array_iter,
1964                                                           DBUS_TYPE_STRUCT,
1965                                                           NULL,
1966                                                           &ah_struct_iter);
1967                         account_id = ah->account_id;
1968                         account_name = ah->account_name;
1969                         store_protocol = ah->store_protocol;
1970                         unread_count = ah->unread_count;
1971                         dbus_message_iter_append_basic (&ah_struct_iter,
1972                                                         DBUS_TYPE_STRING,
1973                                                         &account_id);
1974                         dbus_message_iter_append_basic (&ah_struct_iter,
1975                                                         DBUS_TYPE_STRING,
1976                                                         &account_name);
1977                         dbus_message_iter_append_basic (&ah_struct_iter,
1978                                                         DBUS_TYPE_STRING,
1979                                                         &store_protocol);
1980                         dbus_message_iter_append_basic (&ah_struct_iter,
1981                                                         DBUS_TYPE_INT64,
1982                                                         &unread_count);
1983
1984                         dbus_message_iter_open_container (&ah_struct_iter,
1985                                                           DBUS_TYPE_ARRAY,
1986                                                           ACCOUNT_HIT_DBUS_TYPE,
1987                                                           &sh_array_iter);
1988                         for (result_node = ah->header_list; result_node != NULL; result_node = g_list_next (result_node)) {
1989                                 TnyHeader *header = (TnyHeader *) result_node->data;
1990                                 DBusMessageIter sh_struct_iter;
1991                                 gint64 ts = tny_header_get_date_received (header);
1992                                 gchar *subject = tny_header_dup_subject (header);
1993
1994                                 dbus_message_iter_open_container (&sh_array_iter,
1995                                                                   DBUS_TYPE_STRUCT,
1996                                                                   NULL,
1997                                                                   &sh_struct_iter);
1998                                 dbus_message_iter_append_basic (&sh_struct_iter,
1999                                                                 DBUS_TYPE_INT64,
2000                                                                 &ts);
2001                                 dbus_message_iter_append_basic (&sh_struct_iter,
2002                                                                 DBUS_TYPE_STRING,
2003                                                                 (const gchar **) &subject); 
2004
2005                                 dbus_message_iter_close_container (&sh_array_iter,
2006                                                            &sh_struct_iter); 
2007                                 g_object_unref (header);
2008                         }
2009                         dbus_message_iter_close_container (&ah_struct_iter,
2010                                                            &sh_array_iter); 
2011
2012                         dbus_message_iter_close_container (&array_iter,
2013                                                            &ah_struct_iter); 
2014                         g_free (ah->account_id);
2015                         g_free (ah->account_name);
2016                         g_free (ah->store_protocol);
2017                         g_list_free (ah->header_list);
2018                 }
2019
2020                 dbus_message_iter_close_container (&iter,
2021                                                    &array_iter); 
2022                 dbus_connection_send (helper->con, reply, &serial);
2023                 dbus_connection_flush (helper->con);
2024                 dbus_message_unref (reply);
2025
2026         }
2027         g_list_free (helper->account_hits_list);
2028         dbus_message_unref (helper->message);
2029         g_object_unref (helper->accounts_list);
2030         modest_mail_operation_queue_remove (modest_runtime_get_mail_operation_queue (),
2031                                             helper->mail_op);
2032         g_object_unref (helper->mail_op);
2033         g_slice_free (GetUnreadMessagesHelper, helper);
2034 }
2035
2036 static void get_unread_messages_get_account (GetUnreadMessagesHelper *helper);
2037 static void get_unread_messages_get_headers (GetUnreadMessagesHelper *helper);
2038
2039
2040 static void get_unread_messages_get_headers_cb (TnyFolder *self,
2041                                                 gboolean cancelled, 
2042                                                 TnyList *headers,
2043                                                 GError *err, 
2044                                                 GetUnreadMessagesHelper *helper)
2045 {
2046         TnyIterator *acc_iterator;
2047         TnyAccount *account;
2048         TnyIterator *headers_iterator;
2049         GList *result_list = NULL;
2050         gint members_count = 0;
2051         AccountHits *account_hits;
2052         const gchar *folder_id;
2053         const gchar *bar;
2054         ModestProtocolType store_protocol_type;
2055         ModestProtocol *store_protocol;
2056         gint unread_count;
2057         ModestProtocolRegistry *registry;
2058
2059         acc_iterator = tny_list_create_iterator (helper->accounts_list);
2060         account = TNY_ACCOUNT (tny_iterator_get_current (acc_iterator));
2061
2062         headers_iterator = tny_list_create_iterator (headers);
2063         unread_count = 0;
2064         while (!tny_iterator_is_done (headers_iterator)) {
2065                 TnyHeader *header;
2066                 TnyHeaderFlags flags;
2067
2068                 header = TNY_HEADER (tny_iterator_get_current (headers_iterator));
2069                 flags = tny_header_get_flags (header);
2070                 if (!(flags & TNY_HEADER_FLAG_SEEN)) {
2071                         unread_count++;
2072                         result_list = g_list_insert_sorted (result_list, g_object_ref (header), (GCompareFunc) headers_cmp);
2073                         if (members_count == helper->unread_msgs_count) {
2074                                 g_object_unref (result_list->data);
2075                                 result_list = g_list_delete_link (result_list, result_list);
2076                         } else {
2077                                 members_count++;
2078                         }
2079                 }
2080
2081                 g_object_unref (header);
2082                 tny_iterator_next (headers_iterator);
2083         }
2084         g_object_unref (headers_iterator);
2085
2086         registry = modest_runtime_get_protocol_registry ();
2087         store_protocol_type = modest_tny_account_get_protocol_type (account);
2088
2089         /* Get the number of unread messages for plug-in based accounts */
2090         if (modest_protocol_registry_protocol_type_is_provider (registry, store_protocol_type)) {
2091                 unread_count = tny_folder_get_unread_count (self);
2092         }
2093
2094         account_hits = g_slice_new (AccountHits);
2095         account_hits->account_id = g_strdup (modest_tny_account_get_parent_modest_account_name_for_server_account (account));
2096         account_hits->account_name = g_strdup (tny_account_get_name (account));
2097         store_protocol = modest_protocol_registry_get_protocol_by_type (registry, store_protocol_type);
2098         account_hits->store_protocol = g_strdup (modest_protocol_get_name (store_protocol));
2099         account_hits->header_list = result_list;
2100         account_hits->mailbox_id = NULL;
2101         account_hits->unread_count = unread_count;
2102
2103         folder_id = tny_folder_get_id (self);
2104         bar = g_strstr_len (folder_id, -1, "/");
2105         if (bar) {
2106                 gchar *prefix;
2107                 prefix = g_strndup (folder_id, bar - folder_id);
2108                 if (g_strstr_len (prefix, -1, "@")) {
2109                         account_hits->mailbox_id = g_strdup (prefix);
2110                 }
2111                 g_free (prefix);
2112         }
2113
2114         helper->account_hits_list = g_list_prepend (helper->account_hits_list, account_hits);
2115
2116         get_unread_messages_get_headers (helper);
2117
2118 }
2119
2120 static void
2121 get_unread_messages_get_headers (GetUnreadMessagesHelper *helper)
2122 {
2123         TnyIterator *iterator;
2124
2125         iterator = tny_list_create_iterator (helper->inboxes_list);
2126         if (tny_iterator_is_done (iterator)) {
2127                 TnyIterator *accounts_iter;
2128                 TnyAccount *account;
2129                 g_object_unref (helper->inboxes_list);
2130                 helper->inboxes_list = NULL;
2131
2132                 accounts_iter = tny_list_create_iterator (helper->accounts_list);
2133                 account = TNY_ACCOUNT (tny_iterator_get_current (accounts_iter));
2134                 g_object_unref (accounts_iter);
2135
2136                 tny_list_remove (helper->accounts_list, (GObject *) account);
2137                 g_object_unref (account);
2138                 get_unread_messages_get_account (helper);
2139         } else {
2140                 TnyFolder *folder;
2141
2142                 folder = TNY_FOLDER (tny_iterator_get_current (iterator));
2143                 if (folder) {
2144                         TnyList *headers_list;
2145
2146                         headers_list = TNY_LIST (tny_simple_list_new ());
2147                         tny_folder_get_headers_async (folder, headers_list, FALSE, (TnyGetHeadersCallback) get_unread_messages_get_headers_cb, NULL, helper);
2148                         g_object_unref (headers_list);
2149                         tny_list_remove (helper->inboxes_list, G_OBJECT (folder));
2150                         g_object_unref (folder);
2151                 }
2152         }
2153         g_object_unref (iterator);
2154 }
2155
2156 static void get_account_folders_cb (TnyFolderStore *self, gboolean cancelled, TnyList *list, GError *err, gpointer user_data)
2157 {
2158         GetUnreadMessagesHelper *helper = (GetUnreadMessagesHelper *) user_data;
2159         TnyIterator *iterator;
2160
2161         iterator = tny_list_create_iterator (list);
2162         while (!tny_iterator_is_done (iterator)) {
2163                 TnyFolder *folder;
2164
2165                 folder = TNY_FOLDER (tny_iterator_get_current (iterator));
2166                 if (tny_folder_get_folder_type (folder) == TNY_FOLDER_TYPE_INBOX) {
2167                         tny_list_prepend (helper->inboxes_list, G_OBJECT (folder));
2168                         g_object_unref (folder);
2169                         break;
2170                 }
2171                 g_object_unref (folder);
2172                 tny_iterator_next (iterator);
2173         }
2174         g_object_unref (iterator);
2175         
2176         get_unread_messages_get_headers (helper);
2177 }
2178
2179 static void get_multi_mailbox_account_folders_cb (TnyFolderStore *self, gboolean cancelled, TnyList *list, GError *err, gpointer user_data)
2180 {
2181         GetUnreadMessagesHelper *helper = (GetUnreadMessagesHelper *) user_data;
2182         TnyIterator *iterator;
2183
2184         /* another request has been finished */
2185         helper->folder_requests_done += 1;
2186
2187         /* analize the folders we got */
2188         iterator = tny_list_create_iterator (list);
2189         while (!tny_iterator_is_done (iterator)) {
2190                 TnyFolder *folder;
2191
2192                 folder = TNY_FOLDER (tny_iterator_get_current (iterator));
2193                 if (tny_folder_get_folder_type (folder) == TNY_FOLDER_TYPE_INBOX) {
2194                         tny_list_prepend (helper->inboxes_list, G_OBJECT (folder));
2195                 }
2196
2197                 /* Try to check if we have inbox sub-folders in this folder */
2198                 if (TNY_IS_FOLDER_STORE (folder)) {
2199                         TnyFolderStore *folder_store;
2200
2201                         folder_store = TNY_FOLDER_STORE (folder);
2202                         if (folder_store) {
2203                                 TnyList *folders_list;
2204
2205                                 helper->folder_requests_total += 1;
2206                                 folders_list = tny_simple_list_new ();
2207                                 tny_folder_store_get_folders_async (folder_store, folders_list,
2208                                         NULL, FALSE, get_multi_mailbox_account_folders_cb, NULL, helper);
2209                                 g_object_unref (folders_list);
2210                         }
2211                 }
2212                 g_object_unref (folder);
2213                 tny_iterator_next (iterator);
2214         }
2215         g_object_unref (iterator);
2216
2217         /* Check if we have handled all the inbox folders for multi-mailbox accounts */
2218         if (helper->folder_requests_done == helper->folder_requests_total) {
2219                 TnyIterator *inboxes_it;
2220                 TnyIterator *accounts_it;
2221                 TnyAccount *account;
2222                 guint unread_messages;
2223                 AccountHits* account_hits;
2224                 ModestProtocol *store_protocol;
2225                 ModestProtocolType store_protocol_type;
2226
2227                 /* Store the number of unread messages for the handled account */
2228                 unread_messages = 0;
2229                 accounts_it = tny_list_create_iterator (helper->accounts_list);
2230                 account = TNY_ACCOUNT (tny_iterator_get_current (accounts_it));
2231                 g_object_unref (accounts_it);
2232                 inboxes_it = tny_list_create_iterator (helper->inboxes_list);
2233                 while (!tny_iterator_is_done (inboxes_it)) {
2234                         TnyFolder *folder;
2235
2236                         folder = TNY_FOLDER (tny_iterator_get_current (inboxes_it));
2237                         if (folder) {
2238                                 unread_messages += tny_folder_get_unread_count (folder);
2239                         }
2240                         tny_iterator_next (inboxes_it);
2241                 }
2242                 g_object_unref (inboxes_it);
2243                 g_object_unref (helper->inboxes_list);
2244                 helper->inboxes_list = NULL;
2245                 account_hits = g_slice_new (AccountHits);
2246                 account_hits->account_id = g_strdup (
2247                         modest_tny_account_get_parent_modest_account_name_for_server_account (account));
2248                 account_hits->account_name = g_strdup (tny_account_get_name (account));
2249                 store_protocol_type = modest_tny_account_get_protocol_type (account);
2250                 store_protocol = modest_protocol_registry_get_protocol_by_type (
2251                         modest_runtime_get_protocol_registry (), store_protocol_type);
2252                 account_hits->store_protocol = g_strdup (modest_protocol_get_name (store_protocol));
2253                 account_hits->mailbox_id = NULL;
2254                 account_hits->header_list = NULL;
2255                 account_hits->unread_count = unread_messages;
2256                 helper->account_hits_list = g_list_prepend (helper->account_hits_list, account_hits);
2257
2258                 /* remove the handled account from the accounts_list */
2259                 tny_list_remove (helper->accounts_list, G_OBJECT (account));
2260                 g_object_unref (account);
2261
2262                 get_unread_messages_get_account (helper);
2263         }
2264 }
2265
2266 static void
2267 get_unread_messages_get_account (GetUnreadMessagesHelper *helper)
2268 {
2269         TnyIterator *iterator;
2270
2271         /* Search through all accounts */
2272         iterator = tny_list_create_iterator (helper->accounts_list);
2273         if (tny_iterator_is_done (iterator)) {
2274                 /* all results, then finish */
2275                 return_results (helper);
2276         } else {
2277                 TnyAccount *account;
2278                 TnyList *folders_list;
2279                 ModestProtocolType protocol_type;
2280
2281                 account = TNY_ACCOUNT (tny_iterator_get_current (iterator));
2282                 protocol_type = modest_tny_account_get_protocol_type (account);
2283
2284                 folders_list = tny_simple_list_new ();
2285                 helper->inboxes_list =  tny_simple_list_new ();
2286                 if (MODEST_PROTOCOL_REGISTRY_TYPE_INVALID != protocol_type &&
2287                         modest_protocol_registry_protocol_type_has_tag (modest_runtime_get_protocol_registry (),
2288                                 protocol_type, MODEST_PROTOCOL_REGISTRY_MULTI_MAILBOX_PROVIDER_PROTOCOLS)) {
2289                         /* For multi-mailbox protocols we only can get the number of unread messages,
2290                            we will not even try to get their email headers */
2291                         helper->folder_requests_done = 0;
2292                         helper->folder_requests_total = 1;
2293                         tny_folder_store_get_folders_async (TNY_FOLDER_STORE (account),
2294                                 folders_list, NULL, FALSE, get_multi_mailbox_account_folders_cb, NULL, helper);
2295                 }
2296                 else {
2297                         /* For non-multi-mailbox protocols we will get their email headers */
2298                         tny_folder_store_get_folders_async (TNY_FOLDER_STORE (account),
2299                                 folders_list, NULL, FALSE, get_account_folders_cb, NULL, helper);
2300                 }
2301                 g_object_unref (folders_list);
2302                 g_object_unref (account);
2303
2304         }
2305         g_object_unref (iterator);
2306 }
2307
2308 static gboolean
2309 on_idle_get_unread_messages (GetUnreadMessagesHelper *helper)
2310 {
2311         ModestTnyAccountStore *astore;
2312         astore = modest_runtime_get_account_store ();
2313
2314         tny_account_store_get_accounts (TNY_ACCOUNT_STORE (astore),
2315                                         helper->accounts_list,
2316                                         TNY_ACCOUNT_STORE_STORE_ACCOUNTS);
2317
2318         get_unread_messages_get_account (helper);
2319
2320         return FALSE;
2321 }
2322
2323 static void
2324 on_dbus_method_get_unread_messages (DBusConnection *con, DBusMessage *message)
2325 {
2326         dbus_bool_t  res;
2327         dbus_int64_t unread_msgs_count_v;
2328         DBusError error;
2329         GetUnreadMessagesHelper *helper;
2330
2331         dbus_error_init (&error);
2332
2333         res = dbus_message_get_args (message,
2334                                      &error,
2335                                      DBUS_TYPE_INT32, &unread_msgs_count_v,
2336                                      DBUS_TYPE_INVALID);
2337
2338         helper = g_slice_new (GetUnreadMessagesHelper);
2339         helper->unread_msgs_count = unread_msgs_count_v;
2340         dbus_message_ref (message);
2341         helper->message = message;
2342         helper->con = con;
2343         helper->account_hits_list = NULL;
2344         helper->inboxes_list = NULL;
2345         helper->accounts_list = TNY_LIST (tny_simple_list_new ());
2346         helper->mail_op = modest_mail_operation_new (NULL);
2347         modest_mail_operation_queue_add (modest_runtime_get_mail_operation_queue (),
2348                                          helper->mail_op);
2349
2350         g_idle_add ((GSourceFunc) on_idle_get_unread_messages, helper);
2351 }
2352
2353
2354 /* A complex D-Bus type (like a struct),
2355  * used to return various information about a folder.
2356  */
2357 #define GET_FOLDERS_RESULT_DBUS_TYPE \
2358         DBUS_STRUCT_BEGIN_CHAR_AS_STRING \
2359         DBUS_TYPE_STRING_AS_STRING /* Folder Name */ \
2360         DBUS_TYPE_STRING_AS_STRING /* Folder URI */ \
2361         DBUS_STRUCT_END_CHAR_AS_STRING
2362
2363 static DBusMessage *
2364 get_folders_result_to_message (DBusMessage *reply,
2365                            GList *folder_ids)
2366 {
2367         DBusMessageIter iter;   
2368         dbus_message_iter_init_append (reply, &iter); 
2369         
2370         DBusMessageIter array_iter;
2371         dbus_message_iter_open_container (&iter,
2372                                           DBUS_TYPE_ARRAY,
2373                                           GET_FOLDERS_RESULT_DBUS_TYPE,
2374                                           &array_iter); 
2375
2376         GList *list_iter = folder_ids;
2377         for (list_iter = folder_ids; list_iter; list_iter = list_iter->next) {
2378                 
2379                 const gchar *folder_name = (const gchar*)list_iter->data;
2380                 if (folder_name) {
2381                         /* g_debug ("DEBUG: %s: Adding folder: %s", __FUNCTION__, folder_name); */
2382                         
2383                         DBusMessageIter struct_iter;
2384                         dbus_message_iter_open_container (&array_iter,
2385                                                           DBUS_TYPE_STRUCT,
2386                                                           NULL,
2387                                                           &struct_iter);
2388         
2389                         /* name: */
2390                         dbus_message_iter_append_basic (&struct_iter,
2391                                                         DBUS_TYPE_STRING,
2392                                                         &folder_name); /* The string will be copied. */
2393                                                         
2394                         /* URI: This is maybe not needed by osso-global-search: */
2395                         const gchar *folder_uri = "TODO:unimplemented";
2396                         dbus_message_iter_append_basic (&struct_iter,
2397                                                         DBUS_TYPE_STRING,
2398                                                         &folder_uri); /* The string will be copied. */
2399         
2400                         dbus_message_iter_close_container (&array_iter,
2401                                                            &struct_iter); 
2402                 }
2403         }
2404
2405         dbus_message_iter_close_container (&iter, &array_iter);
2406
2407         return reply;
2408 }
2409
2410 static void
2411 add_single_folder_to_list (TnyFolder *folder, GList** list)
2412 {
2413         if (!folder)
2414                 return;
2415                 
2416         if (TNY_IS_MERGE_FOLDER (folder)) {
2417                 const gchar * folder_name;
2418                 /* Ignore these because their IDs ares
2419                  * a) not always unique or sensible.
2420                  * b) not human-readable, and currently need a human-readable 
2421                  *    ID here, because the osso-email-interface API does not allow 
2422                  *    us to return both an ID and a display name.
2423                  * 
2424                  * This is actually the merged outbox folder.
2425                  * We could hack our D-Bus API to understand "outbox" as the merged outboxes, 
2426                  * but that seems unwise. murrayc.
2427                  */
2428                 folder_name = tny_folder_get_name (folder);
2429                 if (folder_name && !strcmp (folder_name, "Outbox")) {
2430                         *list = g_list_append(*list, g_strdup ("MAND:outbox"));
2431                 }
2432                 return; 
2433         }
2434                 
2435         /* Add this folder to the list: */
2436         /*
2437         const gchar * folder_name = tny_folder_get_name (folder);
2438         if (folder_name)
2439                 *list = g_list_append(*list, g_strdup (folder_name));
2440         else {
2441         */
2442                 /* osso-global-search only uses one string,
2443                  * so ID is the only thing that could possibly identify a folder.
2444                  * TODO: osso-global search should probably be changed to 
2445                  * take an ID and a Name.
2446                  */
2447         const gchar * id =  tny_folder_get_id (folder);
2448         if (id && strlen(id)) {
2449                 const gchar *prefix = NULL;
2450                 TnyFolderType folder_type;
2451                         
2452                 /* dbus global search api expects a prefix identifying the type of
2453                  * folder here. Mandatory folders should have MAND: prefix, and
2454                  * other user created folders should have USER: prefix
2455                  */
2456                 folder_type = modest_tny_folder_guess_folder_type (folder);
2457                 switch (folder_type) {
2458                 case TNY_FOLDER_TYPE_INBOX:
2459                         prefix = "MY:";
2460                         break;
2461                 case TNY_FOLDER_TYPE_OUTBOX:
2462                 case TNY_FOLDER_TYPE_DRAFTS:
2463                 case TNY_FOLDER_TYPE_SENT:
2464                 case TNY_FOLDER_TYPE_ARCHIVE:
2465                         prefix = "MAND:";
2466                         break;
2467                 case TNY_FOLDER_TYPE_INVALID:
2468                         g_warning ("%s: BUG: TNY_FOLDER_TYPE_INVALID", __FUNCTION__);
2469                         return; /* don't add it */
2470                 default:
2471                         prefix = "USER:";
2472                         
2473                 }
2474                 
2475
2476                 *list = g_list_append(*list, g_strdup_printf ("%s%s", prefix, id));
2477         }
2478 }
2479
2480 static void
2481 add_folders_to_list (TnyFolderStore *folder_store, GList** list)
2482 {
2483         if (!folder_store)
2484                 return;
2485         
2486         /* Add this folder to the list: */
2487         if (TNY_IS_FOLDER (folder_store)) {
2488                 add_single_folder_to_list (TNY_FOLDER (folder_store), list);
2489         }       
2490                 
2491         /* Recurse into child folders: */
2492                 
2493         /* Get the folders list: */
2494         /*
2495         TnyFolderStoreQuery *query = tny_folder_store_query_new ();
2496         tny_folder_store_query_add_item (query, NULL, 
2497                 TNY_FOLDER_STORE_QUERY_OPTION_SUBSCRIBED);
2498         */
2499         TnyList *all_folders = tny_simple_list_new ();
2500         tny_folder_store_get_folders (folder_store,
2501                                       all_folders,
2502                                       NULL /* query */,
2503                                       FALSE,
2504                                       NULL /* error */);
2505
2506         TnyIterator *iter = tny_list_create_iterator (all_folders);
2507         while (!tny_iterator_is_done (iter)) {
2508                 
2509                 /* Do not recurse, because the osso-global-search UI specification 
2510                  * does not seem to want the sub-folders, though that spec seems to 
2511                  * be generally unsuitable for Modest.
2512                  */
2513                 TnyFolder *folder = TNY_FOLDER (tny_iterator_get_current (iter));
2514                 if (folder) {
2515                         add_single_folder_to_list (TNY_FOLDER (folder), list);
2516                          
2517                         #if 0
2518                         if (TNY_IS_FOLDER_STORE (folder))
2519                                 add_folders_to_list (TNY_FOLDER_STORE (folder), list);
2520                         else {
2521                                 add_single_folder_to_list (TNY_FOLDER (folder), list);
2522                         }
2523                         #endif
2524                         
2525                         /* tny_iterator_get_current() gave us a reference. */
2526                         g_object_unref (folder);
2527                 }
2528                 
2529                 tny_iterator_next (iter);
2530         }
2531         g_object_unref (G_OBJECT (iter));
2532 }
2533
2534
2535 /* return >1 for a special folder, 0 for a user-folder */
2536 static gint
2537 get_rank (const gchar *folder)
2538 {
2539         if (strcmp (folder, "INBOX") == 0)
2540                 return 1;
2541         if (strcmp (folder, modest_local_folder_info_get_type_name(TNY_FOLDER_TYPE_SENT)) == 0)
2542                 return 2;
2543         if (strcmp (folder, modest_local_folder_info_get_type_name(TNY_FOLDER_TYPE_DRAFTS)) == 0)
2544                 return 3;
2545         if (strcmp (folder, modest_local_folder_info_get_type_name(TNY_FOLDER_TYPE_OUTBOX)) == 0)
2546                 return 4;
2547         return 0;
2548 }
2549
2550 static gint
2551 folder_name_compare_func (const gchar* folder1, const gchar* folder2)
2552 {
2553         gint r1 = get_rank (folder1);
2554         gint r2 = get_rank (folder2);
2555
2556         if (r1 > 0 && r2 > 0)
2557                 return r1 - r2;
2558         if (r1 > 0 && r2 == 0)
2559                 return -1;
2560         if (r1 == 0 && r2 > 0)
2561                 return 1;
2562         else
2563                 return  modest_text_utils_utf8_strcmp (folder1, folder2, TRUE);
2564 }
2565
2566 /* FIXME: */
2567 /*   - we're still missing the outbox */
2568 /*   - we need to take care of localization (urgh) */
2569 /*   - what about 'All mail folders'? */
2570 static void
2571 on_dbus_method_get_folders (DBusConnection *con, DBusMessage *message)
2572 {
2573         DBusMessage  *reply = NULL;
2574         ModestAccountMgr *account_mgr = NULL;
2575         gchar *account_name = NULL;
2576         GList *folder_names = NULL;     
2577         TnyAccount *account_local = NULL;
2578         TnyAccount *account_mmc = NULL;
2579         
2580         /* Get the TnyStoreAccount so we can get the folders: */
2581         account_mgr = modest_runtime_get_account_mgr();
2582         account_name = modest_account_mgr_get_default_account (account_mgr);
2583         if (!account_name) {
2584                 g_printerr ("modest: no account found\n");
2585         }
2586         
2587         if (account_name) {
2588                 TnyAccount *account = NULL;
2589                 if (account_mgr) {
2590                         account = modest_tny_account_store_get_server_account (
2591                                 modest_runtime_get_account_store(), account_name, 
2592                                 TNY_ACCOUNT_TYPE_STORE);
2593                 }
2594                 
2595                 if (!account) {
2596                         g_printerr ("modest: failed to get tny account folder'%s'\n", account_name);
2597                 } 
2598                 
2599                 printf("DEBUG: %s: Getting folders for account name=%s\n", __FUNCTION__, account_name);
2600                 g_free (account_name);
2601                 account_name = NULL;
2602                 
2603                 add_folders_to_list (TNY_FOLDER_STORE (account), &folder_names);
2604         
2605                 g_object_unref (account);
2606                 account = NULL;
2607         }
2608         
2609         /* Also add the folders from the local folders account,
2610          * because they are (currently) used with all accounts:
2611          * TODO: This is not working. It seems to get only the Merged Folder (with an ID of "" (not NULL)).
2612          */
2613         account_local = 
2614                 modest_tny_account_store_get_local_folders_account (modest_runtime_get_account_store());
2615         add_folders_to_list (TNY_FOLDER_STORE (account_local), &folder_names);
2616
2617         g_object_unref (account_local);
2618         account_local = NULL;
2619
2620         /* Obtain the mmc account */
2621         account_mmc = 
2622                 modest_tny_account_store_get_mmc_folders_account (modest_runtime_get_account_store());
2623         if (account_mmc) {
2624                 add_folders_to_list (TNY_FOLDER_STORE (account_mmc), &folder_names);
2625                 g_object_unref (account_mmc);
2626                 account_mmc = NULL;
2627         }
2628
2629         /* specs require us to sort the folder names, although
2630          * this is really not the place to do that...
2631          */
2632         folder_names = g_list_sort (folder_names,
2633                                     (GCompareFunc)folder_name_compare_func);
2634
2635         /* Put the result in a DBus reply: */
2636         reply = dbus_message_new_method_return (message);
2637
2638         get_folders_result_to_message (reply, folder_names);
2639
2640         if (reply == NULL) {
2641                 g_warning ("%s: Could not create reply.", __FUNCTION__);
2642         }
2643
2644         if (reply) {
2645                 dbus_uint32_t serial = 0;
2646                 dbus_connection_send (con, reply, &serial);
2647         dbus_connection_flush (con);
2648         dbus_message_unref (reply);
2649         }
2650
2651         g_list_foreach (folder_names, (GFunc)g_free, NULL);
2652         g_list_free (folder_names);
2653 }
2654
2655
2656 static void
2657 reply_empty_results (DBusConnection *con, DBusMessage *msg)
2658 {
2659         DBusMessage *reply = dbus_message_new_method_return (msg);
2660         if (reply) {
2661                 dbus_uint32_t serial = 0;
2662                 /* we simply return an empty list, otherwise
2663                    global-search gets confused */
2664                 search_result_to_message (reply, NULL);
2665
2666                 dbus_connection_send (con, reply, &serial);
2667                 dbus_connection_flush (con);
2668                 dbus_message_unref (reply);
2669         } else
2670                 g_warning ("%s: failed to send reply",
2671                         __FUNCTION__);
2672 }
2673
2674
2675 /** This D-Bus handler is used when the main osso-rpc 
2676  * D-Bus handler has not handled something.
2677  * We use this for D-Bus methods that need to use more complex types 
2678  * than osso-rpc supports.
2679  */
2680 DBusHandlerResult
2681 modest_dbus_req_filter (DBusConnection *con,
2682                         DBusMessage    *message,
2683                         void           *user_data)
2684 {
2685         gboolean handled = FALSE;
2686
2687         if (dbus_message_is_method_call (message,
2688                                          MODEST_DBUS_IFACE,
2689                                          MODEST_DBUS_METHOD_SEARCH)) {
2690                 
2691         /* don't try to search when there not enough mem */
2692                 if (modest_platform_check_memory_low (NULL, TRUE)) {
2693                         g_warning ("%s: not enough memory for searching",
2694                                    __FUNCTION__);
2695                         reply_empty_results (con, message);
2696                         handled = TRUE;
2697
2698                 } else {
2699                         on_dbus_method_search (con, message);
2700                         handled = TRUE;
2701                 }
2702                                 
2703         } else if (dbus_message_is_method_call (message,
2704                                          MODEST_DBUS_IFACE,
2705                                          MODEST_DBUS_METHOD_GET_UNREAD_MESSAGES)) {
2706                 
2707         /* don't try to get unread messages when there not enough mem */
2708                 if (modest_platform_check_memory_low (NULL, TRUE)) {
2709                         g_warning ("%s: not enough memory for searching",
2710                                    __FUNCTION__);
2711                         reply_empty_results (con, message);
2712                         handled = TRUE;
2713
2714                 } else {
2715                         on_dbus_method_get_unread_messages (con, message);
2716                         handled = TRUE;
2717                 }
2718                                 
2719         } else if (dbus_message_is_method_call (message,
2720                                                 MODEST_DBUS_IFACE,
2721                                                 MODEST_DBUS_METHOD_GET_FOLDERS)) {
2722                 on_dbus_method_get_folders (con, message);
2723                 handled = TRUE;                         
2724         } else if (dbus_message_is_method_call (message,
2725                                                 MODEST_DBUS_IFACE,
2726                                                 MODEST_DBUS_METHOD_DUMP_OPERATION_QUEUE)) {
2727                 on_dbus_method_dump_operation_queue (con, message);
2728                 handled = TRUE;
2729         } else if (dbus_message_is_method_call (message,
2730                                                 MODEST_DBUS_IFACE,
2731                                                 MODEST_DBUS_METHOD_DUMP_ACCOUNTS)) {
2732                 on_dbus_method_dump_accounts (con, message);
2733                 handled = TRUE;
2734         } else if (dbus_message_is_method_call (message,
2735                                                 MODEST_DBUS_IFACE,
2736                                                 MODEST_DBUS_METHOD_DUMP_SEND_QUEUES)) {
2737                 on_dbus_method_dump_send_queues (con, message);
2738                 handled = TRUE;
2739         } else {
2740                 /* Note that this mentions methods that were already handled in modest_dbus_req_handler(). */
2741                 /* 
2742                 g_debug ("  debug: %s: Unexpected (maybe already handled) D-Bus method:\n   Interface=%s, Member=%s\n", 
2743                         __FUNCTION__, dbus_message_get_interface (message),
2744                         dbus_message_get_member(message));
2745                 */
2746         }
2747         
2748         return (handled ? 
2749                 DBUS_HANDLER_RESULT_HANDLED :
2750                 DBUS_HANDLER_RESULT_NOT_YET_HANDLED);
2751 }
2752
2753 static gboolean
2754 notify_error_in_dbus_callback (gpointer user_data)
2755 {
2756         ModestMailOperation *mail_op;
2757         ModestMailOperationQueue *mail_op_queue;
2758
2759         mail_op = modest_mail_operation_new (NULL);
2760         mail_op_queue = modest_runtime_get_mail_operation_queue ();
2761
2762         /* Issues a noop operation in order to force the queue to emit
2763            the "queue-empty" signal to allow modest to quit */
2764         modest_mail_operation_queue_add (mail_op_queue, mail_op);
2765         modest_mail_operation_noop (mail_op);
2766         g_object_unref (mail_op);
2767
2768         return FALSE;
2769 }
2770
2771 gboolean
2772 modest_dbus_emit_account_created_signal (DBusConnection *con, 
2773                                          const gchar *account_id)
2774 {
2775         DBusMessage *signal;
2776         dbus_bool_t result;
2777
2778         signal = dbus_message_new_signal (MODEST_DBUS_OBJECT, MODEST_DBUS_IFACE,
2779                                           MODEST_DBUS_SIGNAL_ACCOUNT_CREATED);
2780
2781         if (signal == NULL)
2782                 return FALSE;
2783
2784         if (!dbus_message_append_args  (signal,
2785                                         DBUS_TYPE_STRING, &account_id,
2786                                         DBUS_TYPE_INVALID)) {
2787                 dbus_message_unref (signal);
2788                 return FALSE;
2789         }
2790
2791         result = dbus_connection_send (con, signal, NULL);
2792
2793         dbus_message_unref (signal);
2794
2795         return result?TRUE:FALSE;
2796 }
2797
2798 gboolean
2799 modest_dbus_emit_account_removed_signal (DBusConnection *con,
2800                                          const gchar *account_id)
2801 {
2802         DBusMessage *signal;
2803         dbus_bool_t result;
2804
2805         signal = dbus_message_new_signal (MODEST_DBUS_OBJECT, MODEST_DBUS_IFACE,
2806                                           MODEST_DBUS_SIGNAL_ACCOUNT_REMOVED);
2807
2808         if (signal == NULL)
2809                 return FALSE;
2810
2811         if (!dbus_message_append_args  (signal,
2812                                         DBUS_TYPE_STRING, &account_id,
2813                                         DBUS_TYPE_INVALID)) {
2814                 dbus_message_unref (signal);
2815                 return FALSE;
2816         }
2817
2818         result = dbus_connection_send (con, signal, NULL);
2819
2820         dbus_message_unref (signal);
2821
2822         return result?TRUE:FALSE;
2823 }
2824
2825 gboolean
2826 modest_dbus_emit_folder_updated_signal (DBusConnection *con, 
2827                                         const gchar *account_id,
2828                                         const gchar *folder_path)
2829 {
2830         DBusMessage *signal;
2831         dbus_bool_t result;
2832
2833         signal = dbus_message_new_signal (MODEST_DBUS_OBJECT, MODEST_DBUS_IFACE,
2834                                           MODEST_DBUS_SIGNAL_FOLDER_UPDATED);
2835
2836         if (signal == NULL)
2837                 return FALSE;
2838
2839         if (!dbus_message_append_args  (signal,
2840                                         DBUS_TYPE_STRING, &account_id,
2841                                         DBUS_TYPE_STRING, &folder_path,
2842                                         DBUS_TYPE_INVALID)) {
2843                 dbus_message_unref (signal);
2844                 return FALSE;
2845         }
2846
2847         result = dbus_connection_send (con, signal, NULL);
2848
2849         dbus_message_unref (signal);
2850
2851         return result?TRUE:FALSE;
2852 }
2853
2854 gboolean
2855 modest_dbus_emit_msg_read_changed_signal (DBusConnection *con,
2856                                           const gchar *uid,
2857                                           gboolean is_read)
2858 {
2859         DBusMessage *signal;
2860         dbus_bool_t result;
2861
2862         signal = dbus_message_new_signal (MODEST_DBUS_OBJECT, MODEST_DBUS_IFACE,
2863                                           MODEST_DBUS_SIGNAL_MSG_READ_CHANGED);
2864
2865         if (signal == NULL)
2866                 return FALSE;
2867
2868         if (!dbus_message_append_args  (signal,
2869                                         DBUS_TYPE_STRING, &uid,
2870                                         DBUS_TYPE_BOOLEAN, &is_read,
2871                                         DBUS_TYPE_INVALID)) {
2872                 dbus_message_unref (signal);
2873                 return FALSE;
2874         }
2875
2876         result = dbus_connection_send (con, signal, NULL);
2877
2878         dbus_message_unref (signal);
2879
2880         return result?TRUE:FALSE;
2881 }