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