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