Merged fix for 87744 from trunk, using revision 5566.
[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 gpointer
726 thread_prepare_delete_message (gpointer userdata)
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         char *uri;
735         gchar *uid = NULL;
736         ModestMailOperation *mail_op = NULL;
737         ModestWindow *main_win = NULL;
738
739         uri = (char *) userdata;
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                 g_free (uri);
749                 return FALSE; 
750         }
751         
752         main_win = modest_window_mgr_get_main_window (modest_runtime_get_window_mgr(),
753                                                       FALSE); /* don't create */
754         
755         folder = tny_msg_get_folder (msg);
756         if (!folder) {
757                 g_warning ("%s: Could not find folder (uri:'%s')", __FUNCTION__, uri);
758                 g_object_unref (msg);
759                 g_idle_add (notify_error_in_dbus_callback, NULL);
760                 g_free (uri);
761                 return FALSE; 
762         }
763
764         /* Get UID */
765         msg_header = tny_msg_get_header (msg);
766         uid = tny_header_dup_uid (msg_header);
767         g_object_unref (msg);
768         g_object_unref (msg_header);
769
770         headers = tny_simple_list_new ();
771         tny_folder_get_headers (folder, headers, TRUE, NULL);
772         iter = tny_list_create_iterator (headers);
773
774         while (!tny_iterator_is_done (iter)) {
775                 gchar *cur_id = NULL;
776
777                 header = TNY_HEADER (tny_iterator_get_current (iter));
778                 if (header)
779                         cur_id = tny_header_dup_uid (header);
780                 
781                 if (cur_id && uid && g_str_equal (cur_id, uid)) {
782                         g_free (cur_id);
783                         /* g_debug ("Found corresponding header from folder"); */
784                         break;
785                 }
786                 g_free (cur_id);
787
788                 if (header) {
789                         g_object_unref (header);
790                         header = NULL;
791                 }
792                 
793                 tny_iterator_next (iter);
794         }
795         g_free (uid);
796         g_object_unref (iter);
797         g_object_unref (headers);
798
799         if (header == NULL) {
800                 if (folder)
801                         g_object_unref (folder);
802                 g_idle_add (notify_error_in_dbus_callback, NULL);                       
803                 g_free (uri);
804                 return FALSE;
805         }
806                 
807         /* This is a GDK lock because we are an idle callback and
808          * the code below is or does Gtk+ code */
809         gdk_threads_enter (); /* CHECKED */
810
811         mail_op = modest_mail_operation_new (main_win ? G_OBJECT(main_win) : NULL);
812         modest_mail_operation_queue_add (modest_runtime_get_mail_operation_queue (), mail_op);
813
814         g_signal_connect (G_OBJECT (mail_op),
815                           "operation-finished",
816                           G_CALLBACK (on_remove_msgs_finished),
817                           g_object_ref (header));
818
819         tmp_headers = tny_simple_list_new ();
820         tny_list_append (tmp_headers, (GObject *) header);
821
822         modest_mail_operation_remove_msgs (mail_op, tmp_headers, FALSE);
823
824         g_object_unref (tmp_headers);
825         g_object_unref (G_OBJECT (mail_op));
826         gdk_threads_leave (); /* CHECKED */
827         
828         /* Clean */
829         if (header)
830                 g_object_unref (header);
831         g_free (uri);
832         
833         return FALSE;
834 }
835
836 static gboolean
837 on_idle_delete_message (gpointer user_data)
838 {
839         const char *uri = NULL;
840
841         uri = (char *) user_data;
842
843         g_thread_create (thread_prepare_delete_message, g_strdup (uri), FALSE, NULL);
844
845         return FALSE;
846         
847 }
848
849
850
851
852 static gint
853 on_delete_message (GArray *arguments, gpointer data, osso_rpc_t *retval)
854 {
855         /* Get the arguments: */
856         osso_rpc_t val = g_array_index (arguments,
857                              osso_rpc_t,
858                              MODEST_DBUS_DELETE_MESSAGE_ARG_URI);
859         gchar *uri = g_strdup (val.value.s);
860         
861         /* Use g_idle to context-switch into the application's thread: */
862         g_idle_add(on_idle_delete_message, (gpointer)uri);
863         
864         return OSSO_OK;
865 }
866
867 static gboolean
868 on_idle_send_receive(gpointer user_data)
869 {
870         gboolean auto_update;
871         ModestWindow *main_win = NULL;
872
873         main_win =
874                 modest_window_mgr_get_main_window (modest_runtime_get_window_mgr (),
875                                                    FALSE); /* don't create */
876
877         gdk_threads_enter (); /* CHECKED */
878
879         /* Check if the autoupdate feature is on */
880         auto_update = modest_conf_get_bool (modest_runtime_get_conf (), 
881                                             MODEST_CONF_AUTO_UPDATE, NULL);
882
883         if (auto_update)
884                 /* Do send receive */
885                 modest_ui_actions_do_send_receive_all (main_win, FALSE, FALSE, FALSE);
886         else
887                 /* Disable auto update */
888                 modest_platform_set_update_interval (0);
889
890         gdk_threads_leave (); /* CHECKED */
891         
892         return FALSE;
893 }
894
895
896
897 static gint 
898 on_dbus_method_dump_send_queues (DBusConnection *con, DBusMessage *message)
899 {
900         gchar *str;
901         
902         DBusMessage *reply;
903         dbus_uint32_t serial = 0;
904
905         GSList *account_names, *cursor;
906
907         str = g_strdup("\nsend queues\n"
908                        "===========\n");
909
910         cursor = account_names = modest_account_mgr_account_names
911                 (modest_runtime_get_account_mgr(), TRUE); /* only enabled accounts */
912
913         while (cursor) {
914                 TnyAccount *acc;
915                 gchar *tmp, *accname = (gchar*)cursor->data;
916                 
917                 tmp = g_strdup_printf ("%s", str);
918                 g_free (str);
919                 str = tmp;
920                 
921                 /* transport */
922                 acc = modest_tny_account_store_get_server_account (
923                         modest_runtime_get_account_store(), accname,
924                         TNY_ACCOUNT_TYPE_TRANSPORT);
925                 if (TNY_IS_ACCOUNT(acc)) {
926                         gchar *tmp = NULL, *url = tny_account_get_url_string (acc);
927                         ModestTnySendQueue *sendqueue =
928                                 modest_runtime_get_send_queue (TNY_TRANSPORT_ACCOUNT(acc), TRUE);
929
930                         if (TNY_IS_SEND_QUEUE (sendqueue)) {
931                                 gchar *queue_str = modest_tny_send_queue_to_string (sendqueue);
932                         
933                                 tmp = g_strdup_printf ("%s[%s]: '%s': %s\n%s",
934                                                        str, accname, tny_account_get_id (acc), url,
935                                                        queue_str);
936                                 g_free(queue_str);
937                                 g_free (str);
938                                 str = tmp;
939                         }
940                         g_free (url);
941
942                         g_object_unref (acc);
943                 }
944                 
945                 cursor = g_slist_next (cursor);
946         }
947         modest_account_mgr_free_account_names (account_names);
948                                                          
949         g_printerr (str);
950         
951         reply = dbus_message_new_method_return (message);
952         if (reply) {
953                 dbus_message_append_args (reply,
954                                           DBUS_TYPE_STRING, &str,
955                                           DBUS_TYPE_INVALID);
956                 dbus_connection_send (con, reply, &serial);
957                 dbus_connection_flush (con);
958                 dbus_message_unref (reply);
959         }
960         g_free (str);
961
962         /* Let modest die */
963         g_idle_add (notify_error_in_dbus_callback, NULL);
964
965         return OSSO_OK;
966 }
967
968
969 static gint 
970 on_dbus_method_dump_operation_queue (DBusConnection *con, DBusMessage *message)
971 {
972         gchar *str;
973         gchar *op_queue_str;
974         
975         DBusMessage *reply;
976         dbus_uint32_t serial = 0;
977
978         /* operations queue; */
979         op_queue_str = modest_mail_operation_queue_to_string
980                 (modest_runtime_get_mail_operation_queue ());
981                 
982         str = g_strdup_printf ("\noperation queue\n"
983                                "===============\n"
984                                "status: %s\n"
985                                "%s\n",
986                                tny_device_is_online (modest_runtime_get_device ()) ? "online" : "offline",
987                                op_queue_str);
988         g_free (op_queue_str);
989         
990         g_printerr (str);
991         
992         reply = dbus_message_new_method_return (message);
993         if (reply) {
994                 dbus_message_append_args (reply,
995                                           DBUS_TYPE_STRING, &str,
996                                           DBUS_TYPE_INVALID);
997                 dbus_connection_send (con, reply, &serial);
998                 dbus_connection_flush (con);
999                 dbus_message_unref (reply);
1000         }       
1001         g_free (str);
1002
1003         /* Let modest die */
1004         g_idle_add (notify_error_in_dbus_callback, NULL);
1005
1006         return OSSO_OK;
1007 }
1008
1009
1010
1011 static gint 
1012 on_dbus_method_dump_accounts (DBusConnection *con, DBusMessage *message)
1013 {
1014         gchar *str;
1015         
1016         DBusMessage *reply;
1017         dbus_uint32_t serial = 0;
1018
1019         GSList *account_names, *cursor;
1020
1021         str = g_strdup ("\naccounts\n========\n");
1022
1023         cursor = account_names = modest_account_mgr_account_names
1024                 (modest_runtime_get_account_mgr(), TRUE); /* only enabled accounts */
1025
1026         while (cursor) {
1027                 TnyAccount *acc;
1028                 gchar *tmp, *accname = (gchar*)cursor->data;
1029
1030                 tmp = g_strdup_printf ("%s[%s]\n", str, accname);
1031                 g_free (str);
1032                 str = tmp;
1033                 
1034                 /* store */
1035                 acc = modest_tny_account_store_get_server_account (
1036                         modest_runtime_get_account_store(), accname,
1037                         TNY_ACCOUNT_TYPE_STORE);
1038                 if (TNY_IS_ACCOUNT(acc)) {
1039                         gchar *tmp, *url = tny_account_get_url_string (acc);
1040                         tmp = g_strdup_printf ("%sstore    : '%s': %s (refs: %d)\n",
1041                                                str, tny_account_get_id (acc), url, 
1042                                                ((GObject*)acc)->ref_count-1);
1043                         g_free (str);
1044                         str = tmp;
1045                         g_free (url);
1046                         g_object_unref (acc);
1047                 }
1048                 
1049                 /* transport */
1050                 acc = modest_tny_account_store_get_server_account (
1051                         modest_runtime_get_account_store(), accname,
1052                         TNY_ACCOUNT_TYPE_TRANSPORT);
1053                 if (TNY_IS_ACCOUNT(acc)) {
1054                         gchar *tmp, *url = tny_account_get_url_string (acc);
1055                         tmp = g_strdup_printf ("%stransport: '%s': %s (refs: %d)\n",
1056                                                str, tny_account_get_id (acc), url, 
1057                                                ((GObject*)acc)->ref_count-1);
1058                         g_free (str);
1059                         str = tmp;
1060                         g_free (url);
1061                         g_object_unref (acc);
1062                 }
1063                 
1064                 cursor = g_slist_next (cursor);
1065         }
1066         
1067         modest_account_mgr_free_account_names (account_names);
1068                                                          
1069         g_printerr (str);
1070         
1071         reply = dbus_message_new_method_return (message);
1072         if (reply) {
1073                 dbus_message_append_args (reply,
1074                                           DBUS_TYPE_STRING, &str,
1075                                           DBUS_TYPE_INVALID);
1076                 dbus_connection_send (con, reply, &serial);
1077                 dbus_connection_flush (con);
1078                 dbus_message_unref (reply);
1079         }       
1080         g_free (str);
1081
1082         /* Let modest die */
1083         g_idle_add (notify_error_in_dbus_callback, NULL);
1084
1085         return OSSO_OK;
1086 }
1087
1088 static void
1089 on_send_receive_performer(gboolean canceled, 
1090                           GError *err,
1091                           GtkWindow *parent_window,
1092                           TnyAccount *account,
1093                           gpointer user_data)
1094 {
1095         ModestConnectedVia connect_when;
1096
1097         if (err || canceled) {
1098                 g_idle_add (notify_error_in_dbus_callback, NULL);
1099                 return;
1100         }
1101
1102         connect_when = modest_conf_get_int (modest_runtime_get_conf (), 
1103                                             MODEST_CONF_UPDATE_WHEN_CONNECTED_BY, NULL);
1104         
1105         /* Perform a send and receive if the user selected to connect
1106            via any mean or if the current connection method is the
1107            same as the one specified by the user */
1108         if (connect_when == MODEST_CONNECTED_VIA_ANY ||
1109             connect_when == modest_platform_get_current_connection ()) {
1110                 g_idle_add (on_idle_send_receive, NULL);
1111         } else {
1112                 /* We need this to allow modest to finish */
1113                 g_idle_add (notify_error_in_dbus_callback, NULL);
1114         }
1115 }
1116
1117
1118 static gint 
1119 on_send_receive(GArray *arguments, gpointer data, osso_rpc_t * retval)
1120 {       
1121         TnyDevice *device = modest_runtime_get_device ();
1122
1123         if (!tny_device_is_online (device))
1124                 modest_platform_connect_and_perform (NULL, FALSE, NULL, on_send_receive_performer, NULL);
1125         else
1126                 on_send_receive_performer (FALSE, NULL, NULL, NULL, NULL);
1127         
1128         return OSSO_OK;
1129 }
1130
1131 static gboolean
1132 on_idle_open_default_inbox(gpointer user_data)
1133 {
1134         ModestWindow *main_win;
1135         GtkWidget *folder_view;
1136         
1137         if (!check_and_offer_account_creation ()) /* this has it's only lock already */
1138                 return FALSE;
1139
1140         /* This is a GDK lock because we are an idle callback and
1141          * the code below is or does Gtk+ code */
1142         gdk_threads_enter (); /* CHECKED */
1143
1144         main_win = modest_window_mgr_get_main_window (modest_runtime_get_window_mgr (),
1145                                                       TRUE); /* create if non-existent */
1146         if (!main_win) {
1147                 g_warning ("%s: BUG: no main window", __FUNCTION__);
1148                 gdk_threads_leave (); /* CHECKED */
1149                 return FALSE; /* don't call me again */
1150         }
1151                 
1152         /* Get the folder view */
1153         folder_view = modest_main_window_get_child_widget (MODEST_MAIN_WINDOW (main_win),
1154                                                            MODEST_MAIN_WINDOW_WIDGET_TYPE_FOLDER_VIEW);
1155         modest_folder_view_select_first_inbox_or_local (MODEST_FOLDER_VIEW (folder_view));
1156         
1157         gdk_threads_leave (); /* CHECKED */
1158         
1159         /* This D-Bus method is obviously meant to result in the UI being visible,
1160          * so show it, by calling this idle handler directly: */
1161         on_idle_top_application(user_data);
1162         
1163         return FALSE; /* Do not call this callback again. */
1164 }
1165
1166 static gint 
1167 on_open_default_inbox(GArray * arguments, gpointer data, osso_rpc_t * retval)
1168 {
1169         /* Use g_idle to context-switch into the application's thread: */
1170         g_idle_add(on_idle_open_default_inbox, NULL);
1171         
1172         return OSSO_OK;
1173 }
1174
1175
1176 static gboolean 
1177 on_idle_top_application (gpointer user_data)
1178 {
1179         ModestWindow *main_win;
1180         
1181         /* This is a GDK lock because we are an idle callback and
1182          * the code below is or does Gtk+ code */
1183
1184         gdk_threads_enter (); /* CHECKED */
1185         
1186         main_win = modest_window_mgr_get_main_window (modest_runtime_get_window_mgr (),
1187                                                       TRUE); /* create if non-existent */
1188         if (main_win) {
1189                 /* Ideally, we would just use gtk_widget_show(), 
1190                  * but this widget is not coded correctly to support that: */
1191                 gtk_widget_show_all (GTK_WIDGET (main_win));
1192                 gtk_window_present (GTK_WINDOW (main_win));
1193         } else
1194                 g_warning ("%s: BUG: no main window", __FUNCTION__);
1195
1196         gdk_threads_leave (); /* CHECKED */
1197         
1198         return FALSE; /* Do not call this callback again. */
1199 }
1200
1201 static gint 
1202 on_top_application(GArray * arguments, gpointer data, osso_rpc_t * retval)
1203 {
1204         /* Use g_idle to context-switch into the application's thread: */
1205         g_idle_add(on_idle_top_application, NULL);
1206         
1207         return OSSO_OK;
1208 }
1209
1210 static gboolean 
1211 on_idle_show_memory_low (gpointer user_data)
1212 {
1213         ModestWindow *main_win = NULL;
1214
1215         gdk_threads_enter ();
1216         main_win = modest_window_mgr_get_main_window (modest_runtime_get_window_mgr (), FALSE);
1217         modest_platform_run_information_dialog (GTK_WINDOW (main_win),
1218                                                 dgettext("ke-recv","memr_ib_operation_disabled"),
1219                                                 TRUE);
1220         gdk_threads_leave ();
1221         
1222         return FALSE;
1223 }
1224                       
1225 /* Callback for normal D-BUS messages */
1226 gint 
1227 modest_dbus_req_handler(const gchar * interface, const gchar * method,
1228                         GArray * arguments, gpointer data,
1229                         osso_rpc_t * retval)
1230 {
1231         /* Check memory low conditions */
1232         if (modest_platform_check_memory_low (NULL, FALSE)) {
1233                 g_idle_add (on_idle_show_memory_low, NULL);
1234                 goto param_error;
1235         }
1236
1237         if (g_ascii_strcasecmp (method, MODEST_DBUS_METHOD_MAIL_TO) == 0) {
1238                 if (arguments->len != MODEST_DBUS_MAIL_TO_ARGS_COUNT)
1239                         goto param_error;
1240                 return on_mail_to (arguments, data, retval);            
1241         } else if (g_ascii_strcasecmp (method, MODEST_DBUS_METHOD_OPEN_MESSAGE) == 0) {
1242                 if (arguments->len != MODEST_DBUS_OPEN_MESSAGE_ARGS_COUNT)
1243                         goto param_error;
1244                 return on_open_message (arguments, data, retval);
1245         } else if (g_ascii_strcasecmp (method, MODEST_DBUS_METHOD_SEND_RECEIVE) == 0) {
1246                 if (arguments->len != 0)
1247                         goto param_error;
1248                 return on_send_receive (arguments, data, retval);
1249         } else if (g_ascii_strcasecmp (method, MODEST_DBUS_METHOD_COMPOSE_MAIL) == 0) {
1250                 if (arguments->len != MODEST_DBUS_COMPOSE_MAIL_ARGS_COUNT)
1251                         goto param_error;
1252                 return on_compose_mail (arguments, data, retval);
1253         } else if (g_ascii_strcasecmp (method, MODEST_DBUS_METHOD_DELETE_MESSAGE) == 0) {
1254                 if (arguments->len != MODEST_DBUS_DELETE_MESSAGE_ARGS_COUNT)
1255                         goto param_error;
1256                 return on_delete_message (arguments,data, retval);
1257         } else if (g_ascii_strcasecmp (method, MODEST_DBUS_METHOD_OPEN_DEFAULT_INBOX) == 0) {
1258                 if (arguments->len != 0)
1259                         goto param_error;
1260                 return on_open_default_inbox (arguments, data, retval);
1261         } else if (g_ascii_strcasecmp (method, MODEST_DBUS_METHOD_TOP_APPLICATION) == 0) {
1262                 if (arguments->len != 0)
1263                         goto param_error;
1264                 return on_top_application (arguments, data, retval); 
1265         } else { 
1266                 /* We need to return INVALID here so
1267                  * libosso will return DBUS_HANDLER_RESULT_NOT_YET_HANDLED,
1268                  * so that our modest_dbus_req_filter will then be tried instead.
1269                  * */
1270                 return OSSO_INVALID;
1271         }
1272  param_error:
1273         /* Notify error in D-Bus method */
1274         g_idle_add (notify_error_in_dbus_callback, NULL);
1275         return OSSO_ERROR;
1276 }
1277                                          
1278 /* A complex D-Bus type (like a struct),
1279  * used to return various information about a search hit.
1280  */
1281 #define SEARCH_HIT_DBUS_TYPE \
1282         DBUS_STRUCT_BEGIN_CHAR_AS_STRING \
1283         DBUS_TYPE_STRING_AS_STRING /* msgid */ \
1284         DBUS_TYPE_STRING_AS_STRING /* subject */ \
1285         DBUS_TYPE_STRING_AS_STRING /* folder */ \
1286         DBUS_TYPE_STRING_AS_STRING /* sender */ \
1287         DBUS_TYPE_UINT64_AS_STRING /* msize */ \
1288         DBUS_TYPE_BOOLEAN_AS_STRING /* has_attachment */ \
1289         DBUS_TYPE_BOOLEAN_AS_STRING /* is_unread */ \
1290         DBUS_TYPE_INT64_AS_STRING /* timestamp */ \
1291         DBUS_STRUCT_END_CHAR_AS_STRING
1292
1293 static DBusMessage *
1294 search_result_to_message (DBusMessage *reply,
1295                            GList       *hits)
1296 {
1297         DBusMessageIter iter;
1298         DBusMessageIter array_iter;
1299         GList          *hit_iter;
1300
1301         dbus_message_iter_init_append (reply, &iter); 
1302         dbus_message_iter_open_container (&iter,
1303                                           DBUS_TYPE_ARRAY,
1304                                           SEARCH_HIT_DBUS_TYPE,
1305                                           &array_iter); 
1306
1307         for (hit_iter = hits; hit_iter; hit_iter = hit_iter->next) {
1308                 DBusMessageIter  struct_iter;
1309                 ModestSearchResultHit *hit;
1310                 char            *msg_url;
1311                 const char      *subject;
1312                 const char      *folder;
1313                 const char      *sender;
1314                 guint64          size;
1315                 gboolean         has_attachment;
1316                 gboolean         is_unread;
1317                 gint64           ts;
1318
1319                 hit = (ModestSearchResultHit *) hit_iter->data;
1320
1321                 msg_url = hit->msgid;
1322                 subject = hit->subject;
1323                 folder  = hit->folder;
1324                 sender  = hit->sender;
1325                 size           = hit->msize;
1326                 has_attachment = hit->has_attachment;
1327                 is_unread      = hit->is_unread;
1328                 ts             = hit->timestamp;
1329
1330                 g_debug ("DEBUG: %s: Adding hit: %s", __FUNCTION__, msg_url);   
1331                 
1332                 dbus_message_iter_open_container (&array_iter,
1333                                                   DBUS_TYPE_STRUCT,
1334                                                   NULL,
1335                                                   &struct_iter);
1336
1337                 dbus_message_iter_append_basic (&struct_iter,
1338                                                 DBUS_TYPE_STRING,
1339                                                 &msg_url);
1340
1341                 dbus_message_iter_append_basic (&struct_iter,
1342                                                 DBUS_TYPE_STRING,
1343                                                 &subject); 
1344
1345                 dbus_message_iter_append_basic (&struct_iter,
1346                                                 DBUS_TYPE_STRING,
1347                                                 &folder);
1348
1349                 dbus_message_iter_append_basic (&struct_iter,
1350                                                 DBUS_TYPE_STRING,
1351                                                 &sender);
1352
1353                 dbus_message_iter_append_basic (&struct_iter,
1354                                                 DBUS_TYPE_UINT64,
1355                                                 &size);
1356
1357                 dbus_message_iter_append_basic (&struct_iter,
1358                                                 DBUS_TYPE_BOOLEAN,
1359                                                 &has_attachment);
1360
1361                 dbus_message_iter_append_basic (&struct_iter,
1362                                                 DBUS_TYPE_BOOLEAN,
1363                                                 &is_unread);
1364                 
1365                 dbus_message_iter_append_basic (&struct_iter,
1366                                                 DBUS_TYPE_INT64,
1367                                                 &ts);
1368
1369                 dbus_message_iter_close_container (&array_iter,
1370                                                    &struct_iter); 
1371
1372                 g_free (hit->msgid);
1373                 g_free (hit->subject);
1374                 g_free (hit->folder);
1375                 g_free (hit->sender);
1376
1377                 g_slice_free (ModestSearchResultHit, hit);
1378         }
1379
1380         dbus_message_iter_close_container (&iter, &array_iter);
1381
1382         return reply;
1383 }
1384
1385 typedef struct
1386 {
1387         DBusConnection *con;
1388         DBusMessage *message;
1389         ModestSearch *search;
1390 } SearchHelper;
1391
1392 static void
1393 search_all_cb (GList *hits, gpointer user_data)
1394 {
1395         DBusMessage  *reply;
1396         SearchHelper *helper = (SearchHelper *) user_data;
1397
1398         reply = dbus_message_new_method_return (helper->message);
1399
1400         if (reply) {
1401                 dbus_uint32_t serial = 0;
1402                 
1403                 search_result_to_message (reply, hits);
1404
1405                 dbus_connection_send (helper->con, reply, &serial);
1406                 dbus_connection_flush (helper->con);
1407                 dbus_message_unref (reply);
1408         }
1409
1410         /* Free the helper */
1411         dbus_message_unref (helper->message);
1412         modest_search_free (helper->search);
1413         g_slice_free (ModestSearch, helper->search);
1414         g_slice_free (SearchHelper, helper);
1415 }
1416
1417 static void
1418 on_dbus_method_search (DBusConnection *con, DBusMessage *message)
1419 {
1420         ModestDBusSearchFlags dbus_flags;
1421         dbus_bool_t  res;
1422         dbus_int64_t sd_v;
1423         dbus_int64_t ed_v;
1424         dbus_int32_t flags_v;
1425         dbus_uint32_t size_v;
1426         const char *folder;
1427         const char *query;
1428         time_t start_date;
1429         time_t end_date;
1430         ModestSearch *search;
1431         DBusError error;
1432
1433         dbus_error_init (&error);
1434
1435         sd_v = ed_v = 0;
1436         flags_v = 0;
1437
1438         res = dbus_message_get_args (message,
1439                                      &error,
1440                                      DBUS_TYPE_STRING, &query,
1441                                      DBUS_TYPE_STRING, &folder, /* e.g. "INBOX/drafts": TODO: Use both an ID and a display name. */
1442                                      DBUS_TYPE_INT64, &sd_v,
1443                                      DBUS_TYPE_INT64, &ed_v,
1444                                      DBUS_TYPE_INT32, &flags_v,
1445                                      DBUS_TYPE_UINT32, &size_v,
1446                                      DBUS_TYPE_INVALID);
1447
1448         dbus_flags = (ModestDBusSearchFlags) flags_v;
1449         start_date = (time_t) sd_v;
1450         end_date = (time_t) ed_v;
1451
1452         search = g_slice_new0 (ModestSearch);
1453         
1454         if (folder && g_str_has_prefix (folder, "MAND:")) {
1455                 search->folder = g_strdup (folder + strlen ("MAND:"));
1456         } else if (folder && g_str_has_prefix (folder, "USER:")) {
1457                 search->folder = g_strdup (folder + strlen ("USER:"));
1458         } else if (folder && g_str_has_prefix (folder, "MY:")) {
1459                 search->folder = g_strdup (folder + strlen ("MY:"));
1460         } else {
1461                 search->folder = g_strdup (folder);
1462         }
1463
1464    /* Remember the text to search for: */
1465 #ifdef MODEST_HAVE_OGS
1466         search->query  = g_strdup (query);
1467 #endif
1468
1469         /* Other criteria: */
1470         search->start_date = start_date;
1471         search->end_date  = end_date;
1472         search->flags = 0;
1473
1474         /* Text to serach for in various parts of the message: */
1475         if (dbus_flags & MODEST_DBUS_SEARCH_SUBJECT) {
1476                 search->flags |= MODEST_SEARCH_SUBJECT;
1477                 search->subject = g_strdup (query);
1478         }
1479
1480         if (dbus_flags & MODEST_DBUS_SEARCH_SENDER) {
1481                 search->flags |=  MODEST_SEARCH_SENDER;
1482                 search->from = g_strdup (query);
1483         }
1484
1485         if (dbus_flags & MODEST_DBUS_SEARCH_RECIPIENT) {
1486                 search->flags |= MODEST_SEARCH_RECIPIENT; 
1487                 search->recipient = g_strdup (query);
1488         }
1489
1490         if (dbus_flags & MODEST_DBUS_SEARCH_BODY) {
1491                 search->flags |=  MODEST_SEARCH_BODY; 
1492                 search->body = g_strdup (query);
1493         }
1494
1495         if (sd_v > 0) {
1496                 search->flags |= MODEST_SEARCH_BEFORE;
1497                 search->start_date = start_date;
1498         }
1499
1500         if (ed_v > 0) {
1501                 search->flags |= MODEST_SEARCH_AFTER;
1502                 search->end_date = end_date;
1503         }
1504
1505         if (size_v > 0) {
1506                 search->flags |= MODEST_SEARCH_SIZE;
1507                 search->minsize = size_v;
1508         }
1509
1510 #ifdef MODEST_HAVE_OGS
1511         search->flags |= MODEST_SEARCH_USE_OGS;
1512         g_debug ("%s: Starting search for %s", __FUNCTION__, search->query);
1513 #endif
1514
1515         SearchHelper *helper = g_slice_new (SearchHelper);
1516         helper->search = search;
1517         dbus_message_ref (message);
1518         helper->message = message;
1519         helper->con = con;
1520
1521         /* Search asynchronously */
1522         modest_search_all_accounts (search, search_all_cb, helper);
1523 }
1524
1525
1526 /* A complex D-Bus type (like a struct),
1527  * used to return various information about a folder.
1528  */
1529 #define GET_FOLDERS_RESULT_DBUS_TYPE \
1530         DBUS_STRUCT_BEGIN_CHAR_AS_STRING \
1531         DBUS_TYPE_STRING_AS_STRING /* Folder Name */ \
1532         DBUS_TYPE_STRING_AS_STRING /* Folder URI */ \
1533         DBUS_STRUCT_END_CHAR_AS_STRING
1534
1535 static DBusMessage *
1536 get_folders_result_to_message (DBusMessage *reply,
1537                            GList *folder_ids)
1538 {
1539         DBusMessageIter iter;   
1540         dbus_message_iter_init_append (reply, &iter); 
1541         
1542         DBusMessageIter array_iter;
1543         dbus_message_iter_open_container (&iter,
1544                                           DBUS_TYPE_ARRAY,
1545                                           GET_FOLDERS_RESULT_DBUS_TYPE,
1546                                           &array_iter); 
1547
1548         GList *list_iter = folder_ids;
1549         for (list_iter = folder_ids; list_iter; list_iter = list_iter->next) {
1550                 
1551                 const gchar *folder_name = (const gchar*)list_iter->data;
1552                 if (folder_name) {
1553                         /* g_debug ("DEBUG: %s: Adding folder: %s", __FUNCTION__, folder_name); */
1554                         
1555                         DBusMessageIter struct_iter;
1556                         dbus_message_iter_open_container (&array_iter,
1557                                                           DBUS_TYPE_STRUCT,
1558                                                           NULL,
1559                                                           &struct_iter);
1560         
1561                         /* name: */
1562                         dbus_message_iter_append_basic (&struct_iter,
1563                                                         DBUS_TYPE_STRING,
1564                                                         &folder_name); /* The string will be copied. */
1565                                                         
1566                         /* URI: This is maybe not needed by osso-global-search: */
1567                         const gchar *folder_uri = "TODO:unimplemented";
1568                         dbus_message_iter_append_basic (&struct_iter,
1569                                                         DBUS_TYPE_STRING,
1570                                                         &folder_uri); /* The string will be copied. */
1571         
1572                         dbus_message_iter_close_container (&array_iter,
1573                                                            &struct_iter); 
1574                 }
1575         }
1576
1577         dbus_message_iter_close_container (&iter, &array_iter);
1578
1579         return reply;
1580 }
1581
1582 static void
1583 add_single_folder_to_list (TnyFolder *folder, GList** list)
1584 {
1585         if (!folder)
1586                 return;
1587                 
1588         if (TNY_IS_MERGE_FOLDER (folder)) {
1589                 const gchar * folder_name;
1590                 /* Ignore these because their IDs ares
1591                  * a) not always unique or sensible.
1592                  * b) not human-readable, and currently need a human-readable 
1593                  *    ID here, because the osso-email-interface API does not allow 
1594                  *    us to return both an ID and a display name.
1595                  * 
1596                  * This is actually the merged outbox folder.
1597                  * We could hack our D-Bus API to understand "outbox" as the merged outboxes, 
1598                  * but that seems unwise. murrayc.
1599                  */
1600                 folder_name = tny_folder_get_name (folder);
1601                 if (folder_name && !strcmp (folder_name, "Outbox")) {
1602                         *list = g_list_append(*list, g_strdup ("MAND:outbox"));
1603                 }
1604                 return; 
1605         }
1606                 
1607         /* Add this folder to the list: */
1608         /*
1609         const gchar * folder_name = tny_folder_get_name (folder);
1610         if (folder_name)
1611                 *list = g_list_append(*list, g_strdup (folder_name));
1612         else {
1613         */
1614                 /* osso-global-search only uses one string,
1615                  * so ID is the only thing that could possibly identify a folder.
1616                  * TODO: osso-global search should probably be changed to 
1617                  * take an ID and a Name.
1618                  */
1619         const gchar * id =  tny_folder_get_id (folder);
1620         if (id && strlen(id)) {
1621                 const gchar *prefix = NULL;
1622                 TnyFolderType folder_type;
1623                         
1624                 /* dbus global search api expects a prefix identifying the type of
1625                  * folder here. Mandatory folders should have MAND: prefix, and
1626                  * other user created folders should have USER: prefix
1627                  */
1628                 folder_type = modest_tny_folder_guess_folder_type (folder);
1629                 switch (folder_type) {
1630                 case TNY_FOLDER_TYPE_INBOX:
1631                         prefix = "MY:";
1632                         break;
1633                 case TNY_FOLDER_TYPE_OUTBOX:
1634                 case TNY_FOLDER_TYPE_DRAFTS:
1635                 case TNY_FOLDER_TYPE_SENT:
1636                 case TNY_FOLDER_TYPE_ARCHIVE:
1637                         prefix = "MAND:";
1638                         break;
1639                 case TNY_FOLDER_TYPE_INVALID:
1640                         g_warning ("%s: BUG: TNY_FOLDER_TYPE_INVALID", __FUNCTION__);
1641                         return; /* don't add it */
1642                 default:
1643                         prefix = "USER:";
1644                         
1645                 }
1646                 
1647
1648                 *list = g_list_append(*list, g_strdup_printf ("%s%s", prefix, id));
1649         }
1650 }
1651
1652 static void
1653 add_folders_to_list (TnyFolderStore *folder_store, GList** list)
1654 {
1655         if (!folder_store)
1656                 return;
1657         
1658         /* Add this folder to the list: */
1659         if (TNY_IS_FOLDER (folder_store)) {
1660                 add_single_folder_to_list (TNY_FOLDER (folder_store), list);
1661         }       
1662                 
1663         /* Recurse into child folders: */
1664                 
1665         /* Get the folders list: */
1666         /*
1667         TnyFolderStoreQuery *query = tny_folder_store_query_new ();
1668         tny_folder_store_query_add_item (query, NULL, 
1669                 TNY_FOLDER_STORE_QUERY_OPTION_SUBSCRIBED);
1670         */
1671         TnyList *all_folders = tny_simple_list_new ();
1672         tny_folder_store_get_folders (folder_store,
1673                                       all_folders,
1674                                       NULL /* query */,
1675                                       NULL /* error */);
1676
1677         TnyIterator *iter = tny_list_create_iterator (all_folders);
1678         while (!tny_iterator_is_done (iter)) {
1679                 
1680                 /* Do not recurse, because the osso-global-search UI specification 
1681                  * does not seem to want the sub-folders, though that spec seems to 
1682                  * be generally unsuitable for Modest.
1683                  */
1684                 TnyFolder *folder = TNY_FOLDER (tny_iterator_get_current (iter));
1685                 if (folder) {
1686                         add_single_folder_to_list (TNY_FOLDER (folder), list);
1687                          
1688                         #if 0
1689                         if (TNY_IS_FOLDER_STORE (folder))
1690                                 add_folders_to_list (TNY_FOLDER_STORE (folder), list);
1691                         else {
1692                                 add_single_folder_to_list (TNY_FOLDER (folder), list);
1693                         }
1694                         #endif
1695                         
1696                         /* tny_iterator_get_current() gave us a reference. */
1697                         g_object_unref (folder);
1698                 }
1699                 
1700                 tny_iterator_next (iter);
1701         }
1702         g_object_unref (G_OBJECT (iter));
1703 }
1704
1705
1706 /* return >1 for a special folder, 0 for a user-folder */
1707 static gint
1708 get_rank (const gchar *folder)
1709 {
1710         if (strcmp (folder, "INBOX") == 0)
1711                 return 1;
1712         if (strcmp (folder, modest_local_folder_info_get_type_name(TNY_FOLDER_TYPE_SENT)) == 0)
1713                 return 2;
1714         if (strcmp (folder, modest_local_folder_info_get_type_name(TNY_FOLDER_TYPE_DRAFTS)) == 0)
1715                 return 3;
1716         if (strcmp (folder, modest_local_folder_info_get_type_name(TNY_FOLDER_TYPE_OUTBOX)) == 0)
1717                 return 4;
1718         return 0;
1719 }
1720
1721 static gint
1722 folder_name_compare_func (const gchar* folder1, const gchar* folder2)
1723 {
1724         gint r1 = get_rank (folder1);
1725         gint r2 = get_rank (folder2);
1726
1727         if (r1 > 0 && r2 > 0)
1728                 return r1 - r2;
1729         if (r1 > 0 && r2 == 0)
1730                 return -1;
1731         if (r1 == 0 && r2 > 0)
1732                 return 1;
1733         else
1734                 return  modest_text_utils_utf8_strcmp (folder1, folder2, TRUE);
1735 }
1736
1737 /* FIXME: */
1738 /*   - we're still missing the outbox */
1739 /*   - we need to take care of localization (urgh) */
1740 /*   - what about 'All mail folders'? */
1741 static void
1742 on_dbus_method_get_folders (DBusConnection *con, DBusMessage *message)
1743 {
1744         DBusMessage  *reply = NULL;
1745         ModestAccountMgr *account_mgr = NULL;
1746         gchar *account_name = NULL;
1747         GList *folder_names = NULL;     
1748         TnyAccount *account_local = NULL;
1749         TnyAccount *account_mmc = NULL;
1750         
1751         /* Get the TnyStoreAccount so we can get the folders: */
1752         account_mgr = modest_runtime_get_account_mgr();
1753         account_name = modest_account_mgr_get_default_account (account_mgr);
1754         if (!account_name) {
1755                 g_printerr ("modest: no account found\n");
1756         }
1757         
1758         if (account_name) {
1759                 TnyAccount *account = NULL;
1760                 if (account_mgr) {
1761                         account = modest_tny_account_store_get_server_account (
1762                                 modest_runtime_get_account_store(), account_name, 
1763                                 TNY_ACCOUNT_TYPE_STORE);
1764                 }
1765                 
1766                 if (!account) {
1767                         g_printerr ("modest: failed to get tny account folder'%s'\n", account_name);
1768                 } 
1769                 
1770                 printf("DEBUG: %s: Getting folders for account name=%s\n", __FUNCTION__, account_name);
1771                 g_free (account_name);
1772                 account_name = NULL;
1773                 
1774                 add_folders_to_list (TNY_FOLDER_STORE (account), &folder_names);
1775         
1776                 g_object_unref (account);
1777                 account = NULL;
1778         }
1779         
1780         /* Also add the folders from the local folders account,
1781          * because they are (currently) used with all accounts:
1782          * TODO: This is not working. It seems to get only the Merged Folder (with an ID of "" (not NULL)).
1783          */
1784         account_local = 
1785                 modest_tny_account_store_get_local_folders_account (modest_runtime_get_account_store());
1786         add_folders_to_list (TNY_FOLDER_STORE (account_local), &folder_names);
1787
1788         g_object_unref (account_local);
1789         account_local = NULL;
1790
1791         /* Obtain the mmc account */
1792         account_mmc = 
1793                 modest_tny_account_store_get_mmc_folders_account (modest_runtime_get_account_store());
1794         if (account_mmc) {
1795                 add_folders_to_list (TNY_FOLDER_STORE (account_mmc), &folder_names);
1796                 g_object_unref (account_mmc);
1797                 account_mmc = NULL;
1798         }
1799
1800         /* specs require us to sort the folder names, although
1801          * this is really not the place to do that...
1802          */
1803         folder_names = g_list_sort (folder_names,
1804                                     (GCompareFunc)folder_name_compare_func);
1805
1806         /* Put the result in a DBus reply: */
1807         reply = dbus_message_new_method_return (message);
1808
1809         get_folders_result_to_message (reply, folder_names);
1810
1811         if (reply == NULL) {
1812                 g_warning ("%s: Could not create reply.", __FUNCTION__);
1813         }
1814
1815         if (reply) {
1816                 dbus_uint32_t serial = 0;
1817                 dbus_connection_send (con, reply, &serial);
1818         dbus_connection_flush (con);
1819         dbus_message_unref (reply);
1820         }
1821
1822         g_list_foreach (folder_names, (GFunc)g_free, NULL);
1823         g_list_free (folder_names);
1824 }
1825
1826
1827 static void
1828 reply_empty_results (DBusConnection *con, DBusMessage *msg)
1829 {
1830         DBusMessage *reply = dbus_message_new_method_return (msg);
1831         if (reply) {
1832                 dbus_uint32_t serial = 0;
1833                 /* we simply return an empty list, otherwise
1834                    global-search gets confused */
1835                 search_result_to_message (reply, NULL);
1836
1837                 dbus_connection_send (con, reply, &serial);
1838                 dbus_connection_flush (con);
1839                 dbus_message_unref (reply);
1840         } else
1841                 g_warning ("%s: failed to send reply",
1842                         __FUNCTION__);
1843 }
1844
1845
1846 /** This D-Bus handler is used when the main osso-rpc 
1847  * D-Bus handler has not handled something.
1848  * We use this for D-Bus methods that need to use more complex types 
1849  * than osso-rpc supports.
1850  */
1851 DBusHandlerResult
1852 modest_dbus_req_filter (DBusConnection *con,
1853                         DBusMessage    *message,
1854                         void           *user_data)
1855 {
1856         gboolean handled = FALSE;
1857
1858         if (dbus_message_is_method_call (message,
1859                                          MODEST_DBUS_IFACE,
1860                                          MODEST_DBUS_METHOD_SEARCH)) {
1861                 
1862         /* don't try to search when there not enough mem */
1863                 if (modest_platform_check_memory_low (NULL, TRUE)) {
1864                         g_warning ("%s: not enough memory for searching",
1865                                    __FUNCTION__);
1866                         reply_empty_results (con, message);
1867                         handled = TRUE;
1868
1869                 } else {
1870                         on_dbus_method_search (con, message);
1871                         handled = TRUE;
1872                 }
1873                                 
1874         } else if (dbus_message_is_method_call (message,
1875                                                 MODEST_DBUS_IFACE,
1876                                                 MODEST_DBUS_METHOD_GET_FOLDERS)) {
1877                 on_dbus_method_get_folders (con, message);
1878                 handled = TRUE;                         
1879         } else if (dbus_message_is_method_call (message,
1880                                                 MODEST_DBUS_IFACE,
1881                                                 MODEST_DBUS_METHOD_DUMP_OPERATION_QUEUE)) {
1882                 on_dbus_method_dump_operation_queue (con, message);
1883                 handled = TRUE;
1884         } else if (dbus_message_is_method_call (message,
1885                                                 MODEST_DBUS_IFACE,
1886                                                 MODEST_DBUS_METHOD_DUMP_ACCOUNTS)) {
1887                 on_dbus_method_dump_accounts (con, message);
1888                 handled = TRUE;
1889         } else if (dbus_message_is_method_call (message,
1890                                                 MODEST_DBUS_IFACE,
1891                                                 MODEST_DBUS_METHOD_DUMP_SEND_QUEUES)) {
1892                 on_dbus_method_dump_send_queues (con, message);
1893                 handled = TRUE;
1894         } else {
1895                 /* Note that this mentions methods that were already handled in modest_dbus_req_handler(). */
1896                 /* 
1897                 g_debug ("  debug: %s: Unexpected (maybe already handled) D-Bus method:\n   Interface=%s, Member=%s\n", 
1898                         __FUNCTION__, dbus_message_get_interface (message),
1899                         dbus_message_get_member(message));
1900                 */
1901         }
1902         
1903         return (handled ? 
1904                 DBUS_HANDLER_RESULT_HANDLED :
1905                 DBUS_HANDLER_RESULT_NOT_YET_HANDLED);
1906 }
1907
1908 static gboolean
1909 notify_error_in_dbus_callback (gpointer user_data)
1910 {
1911         ModestMailOperation *mail_op;
1912         ModestMailOperationQueue *mail_op_queue;
1913
1914         mail_op = modest_mail_operation_new (NULL);
1915         mail_op_queue = modest_runtime_get_mail_operation_queue ();
1916
1917         /* Issues a noop operation in order to force the queue to emit
1918            the "queue-empty" signal to allow modest to quit */
1919         modest_mail_operation_queue_add (mail_op_queue, mail_op);
1920         modest_mail_operation_noop (mail_op);
1921         g_object_unref (mail_op);
1922
1923         return FALSE;
1924 }
1925
1926 static gboolean
1927 notify_msg_not_found_in_idle (gpointer user_data)
1928 {
1929         modest_platform_run_information_dialog (NULL, _("mail_ni_ui_folder_get_msg_folder_error"), FALSE);
1930
1931         g_idle_add (notify_error_in_dbus_callback, NULL);
1932
1933         return FALSE;
1934 }