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