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