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