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