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