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