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