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