9589b58c258b2c12d126228051b43307432b73f7
[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 <libmodest-dbus-client/libmodest-dbus-client.h>
42 #include <libgnomevfs/gnome-vfs-utils.h>
43 #include <stdio.h>
44 #include <string.h>
45 #include <glib/gstdio.h>
46 #ifdef MODEST_HAVE_HILDON0_WIDGETS
47 #include <libgnomevfs/gnome-vfs-mime-utils.h>
48 #else
49 #include <libgnomevfs/gnome-vfs-mime.h>
50 #endif
51 #include <tny-fs-stream.h>
52
53 #include <tny-list.h>
54 #include <tny-iterator.h>
55 #include <tny-simple-list.h>
56 #include <tny-merge-folder.h>
57
58 #include <modest-text-utils.h>
59
60 typedef struct 
61 {
62         gchar *to;
63         gchar *cc;
64         gchar *bcc;
65         gchar *subject;
66         gchar *body;
67         gchar *attachments;
68 } ComposeMailIdleData;
69
70
71 static gboolean notify_error_in_dbus_callback (gpointer user_data);
72 static gboolean on_idle_compose_mail(gpointer user_data);
73 static gboolean on_idle_top_application (gpointer user_data);
74
75 /** uri_unescape:
76  * @uri An escaped URI. URIs should always be escaped.
77  * @len The length of the @uri string, or -1 if the string is null terminated.
78  * 
79  * Decode a URI, or URI fragment, as per RFC 1738.
80  * http://www.ietf.org/rfc/rfc1738.txt
81  * 
82  * Return value: An unescaped string. This should be freed with g_free().
83  */
84 static gchar* 
85 uri_unescape(const gchar* uri, size_t len)
86 {
87         if (!uri)
88                 return NULL;
89                 
90         if (len == -1)
91                 len = strlen (uri);
92         
93         /* Allocate an extra string so we can be sure that it is null-terminated,
94          * so we can use gnome_vfs_unescape_string().
95          * This is not efficient. */
96         gchar * escaped_nullterminated = g_strndup (uri, len);
97         gchar *result = gnome_vfs_unescape_string (escaped_nullterminated, NULL);
98         g_free (escaped_nullterminated);
99         
100         return result;
101 }
102
103 /** uri_parse_mailto:
104  * @mailto A mailto URI, with the mailto: prefix.
105  * @list_items_and_values: A pointer to a list that should be filled with item namesand value strings, 
106  * with each name item being followed by a value item. This list should be freed with g_slist_free) after 
107  * all the string items have been freed. This parameter may be NULL.
108  * Parse a mailto URI as per RFC2368.
109  * http://www.ietf.org/rfc/rfc2368.txt
110  * 
111  * Return value: The to address, unescaped. This should be freed with g_free().
112  */
113 static gchar* 
114 uri_parse_mailto (const gchar* mailto, GSList** list_items_and_values)
115 {
116         /* The URL must begin with mailto: */
117         if (strncmp (mailto, "mailto:", 7) != 0) {
118                 return NULL;
119         }
120         const gchar* start_to = mailto + 7;
121
122         /* Look for ?, or the end of the string, marking the end of the to address: */
123         const size_t len_to = strcspn (start_to, "?");
124         gchar* result_to = uri_unescape (start_to, len_to);
125         printf("debug: result_to=%s\n", result_to);
126
127         if (list_items_and_values == NULL) {
128                 return result_to;
129         }
130
131         /* Get any other items: */
132         const size_t len_mailto = strlen (start_to);
133         const gchar* p = start_to + len_to + 1; /* parsed so far. */
134         const gchar* end = start_to + len_mailto;
135         while (p < end) {
136                 const gchar *name, *value, *name_start, *name_end, *value_start, *value_end;
137                 name_start = p;
138                 name_end = strchr (name_start, '='); /* Separator between name and value */
139                 if (name_end == NULL) {
140                         g_debug ("Malformed URI: %s\n", mailto);
141                         return result_to;
142                 }
143                 value_start = name_end + 1;
144                 value_end = strchr (value_start, '&'); /* Separator between value and next parameter */
145
146                 name = g_strndup(name_start, name_end - name_start);
147                 if (value_end != NULL) {
148                         value = uri_unescape(value_start, value_end - value_start);
149                         p = value_end + 1;
150                 } else {
151                         value = uri_unescape(value_start, -1);
152                         p = end;
153                 }
154                 *list_items_and_values = g_slist_append (*list_items_and_values, (gpointer) name);
155                 *list_items_and_values = g_slist_append (*list_items_and_values, (gpointer) value);
156         }
157         
158         return result_to;
159 }
160
161 static gboolean
162 check_and_offer_account_creation()
163 {
164         gboolean result = TRUE;
165         
166         /* This is called from idle handlers, so lock gdk: */
167         gdk_threads_enter ();
168         
169         if (!modest_account_mgr_has_accounts(modest_runtime_get_account_mgr(), TRUE)) {
170                 const gboolean created = modest_ui_actions_run_account_setup_wizard (NULL);
171                 if (!created) {
172                         g_debug ("modest: %s: no account exists even after offering, "
173                                  "or account setup was already underway.\n", __FUNCTION__);
174                         result = FALSE;
175                 }
176         }
177         
178         gdk_threads_leave ();
179         
180         return result;
181 }
182
183 static gboolean
184 on_idle_mail_to(gpointer user_data)
185 {
186         gchar *uri = (gchar*)user_data;
187         GSList *list_names_and_values = NULL;
188         gchar *to = NULL;
189         const gchar *cc = NULL;
190         const gchar *bcc = NULL;
191         const gchar *subject = NULL;
192         const gchar *body = NULL;
193
194         if (!check_and_offer_account_creation ()) {
195                 g_idle_add (notify_error_in_dbus_callback, NULL);
196                 goto cleanup;
197         }
198
199         /* Get the relevant items from the list: */
200         to = uri_parse_mailto (uri, &list_names_and_values);
201         GSList *list = list_names_and_values;
202         while (list) {
203                 GSList *list_value = g_slist_next (list);
204                 const gchar * name = (const gchar*)list->data;
205                 const gchar * value = (const gchar*)list_value->data;
206
207                 if (strcmp (name, "cc") == 0) {
208                         cc = value;
209                 } else if (strcmp (name, "bcc") == 0) {
210                         bcc = value;
211                 } else if (strcmp (name, "subject") == 0) {
212                         subject = value;
213                 } else if (strcmp (name, "body") == 0) {
214                         body = value;
215                 }
216
217                 list = g_slist_next (list_value);
218         }
219
220         gdk_threads_enter (); /* CHECKED */
221         modest_ui_actions_compose_msg(NULL, to, cc, bcc, subject, body, NULL);
222         gdk_threads_leave (); /* CHECKED */
223
224 cleanup:
225         /* Free the to: and the list, as required by uri_parse_mailto() */
226         g_free(to);
227         g_slist_foreach (list_names_and_values, (GFunc)g_free, NULL);
228         g_slist_free (list_names_and_values);
229
230         g_free(uri);
231
232         return FALSE; /* Do not call this callback again. */
233 }
234
235 static gint 
236 on_mail_to(GArray * arguments, gpointer data, osso_rpc_t * retval)
237 {
238         osso_rpc_t val;
239         gchar *uri;
240
241         /* Get arguments */
242         val = g_array_index(arguments, osso_rpc_t, MODEST_DBUS_MAIL_TO_ARG_URI);
243         uri = g_strdup (val.value.s);
244         
245         g_idle_add(on_idle_mail_to, (gpointer)uri);
246         
247         /* Note that we cannot report failures during sending, 
248          * because that would be asynchronous. */
249         return OSSO_OK;
250 }
251
252
253 static gboolean
254 on_idle_compose_mail(gpointer user_data)
255 {
256         GSList *attachments = NULL;
257         ComposeMailIdleData *idle_data = (ComposeMailIdleData*)user_data;
258
259         if (!check_and_offer_account_creation ()) {
260                 g_idle_add (notify_error_in_dbus_callback, NULL);
261                 goto cleanup;
262         }
263
264         /* it seems Sketch at least sends a leading ',' -- take that into account,
265          * ie strip that ,*/
266         if (idle_data->attachments && idle_data->attachments[0]==',') {
267                 gchar *tmp = g_strdup (idle_data->attachments + 1);
268                 g_free(idle_data->attachments);
269                 idle_data->attachments = tmp;
270         }
271         if (idle_data->attachments != NULL) {
272                 gchar **list = g_strsplit(idle_data->attachments, ",", 0);
273                 gint i = 0;
274                 for (i=0; list[i] != NULL; i++) {
275                         attachments = g_slist_append(attachments, g_strdup(list[i]));
276                 }
277                 g_strfreev(list);
278         }
279         gdk_threads_enter (); /* CHECKED */
280         modest_ui_actions_compose_msg(NULL, idle_data->to, idle_data->cc,
281                                       idle_data->bcc, idle_data->subject,
282                                       idle_data->body, attachments);
283         gdk_threads_leave (); /* CHECKED */
284 cleanup:
285         g_slist_foreach(attachments, (GFunc)g_free, NULL);
286         g_slist_free(attachments);
287         g_free (idle_data->to);
288         g_free (idle_data->cc);
289         g_free (idle_data->bcc);
290         g_free (idle_data->subject);
291         g_free (idle_data->body);
292         g_free (idle_data->attachments);
293         g_free(idle_data);
294
295         return FALSE; /* Do not call this callback again. */
296 }
297
298 static gint 
299 on_compose_mail(GArray * arguments, gpointer data, osso_rpc_t * retval)
300 {
301         ComposeMailIdleData *idle_data;
302         osso_rpc_t val;
303         
304         idle_data = g_new0(ComposeMailIdleData, 1); /* Freed in the idle callback. */
305         
306         /* Get the arguments: */
307         val = g_array_index(arguments, osso_rpc_t, MODEST_DBUS_COMPOSE_MAIL_ARG_TO);
308         idle_data->to = g_strdup (val.value.s);
309         
310         val = g_array_index(arguments, osso_rpc_t, MODEST_DBUS_COMPOSE_MAIL_ARG_CC);
311         idle_data->cc = g_strdup (val.value.s);
312         
313         val = g_array_index(arguments, osso_rpc_t, MODEST_DBUS_COMPOSE_MAIL_ARG_BCC);
314         idle_data->bcc = g_strdup (val.value.s);
315         
316         val = g_array_index(arguments, osso_rpc_t, MODEST_DBUS_COMPOSE_MAIL_ARG_SUBJECT);
317         idle_data->subject = g_strdup (val.value.s);
318         
319         val = g_array_index(arguments, osso_rpc_t, MODEST_DBUS_COMPOSE_MAIL_ARG_BODY);
320         idle_data->body = g_strdup (val.value.s);
321         
322         val = g_array_index(arguments, osso_rpc_t, MODEST_DBUS_COMPOSE_MAIL_ARG_ATTACHMENTS);
323         idle_data->attachments = g_strdup (val.value.s);
324
325         /* Use g_idle to context-switch into the application's thread: */
326         g_idle_add(on_idle_compose_mail, (gpointer)idle_data);
327         
328         return OSSO_OK;
329 }
330
331 static TnyMsg *
332 find_message_by_url (const char *uri,  TnyAccount **ac_out)
333 {
334         ModestTnyAccountStore *astore;
335         TnyAccount            *account;
336         TnyFolder             *folder;
337         TnyMsg                *msg;
338         GError *err = NULL;
339         account = NULL;
340         msg = NULL;
341         folder = NULL;
342
343         astore = modest_runtime_get_account_store ();
344         
345         if (astore == NULL) {
346                 return NULL;
347         }
348
349         if (uri && g_str_has_prefix (uri, "merge://")) {
350                 /* we assume we're talking about outbox folder, as this 
351                  * is the only merge folder we work with in modest */
352                 return modest_tny_account_store_find_msg_in_outboxes (astore, uri, ac_out);
353         }
354         
355         /* TODO: When tinymail is built with the extra DBC assertion checks, 
356          * this will crash for local folders (such as drafts),
357          * because tny_folder_get_url_string() (in add_hit())
358          * returns mail:/home/murrayc/yaddayadda 
359          * instead of mail://localhost/home/murrayc/yaddayadd,
360          * but I'm not sure where that folder URI is built. murrayc.
361          */
362         account = tny_account_store_find_account (TNY_ACCOUNT_STORE (astore),
363                                                   uri);
364         
365         if (account == NULL) {
366                 g_debug ("%s: tny_account_store_find_account() failed for\n  uri=%s\n", 
367                         __FUNCTION__, uri);
368                 return NULL;
369         }
370
371         MODEST_DEBUG_BLOCK (g_debug ("%s: Found account.\n", __FUNCTION__););
372
373         if ( ! TNY_IS_STORE_ACCOUNT (account)) {
374                 goto out;
375         }
376
377         MODEST_DEBUG_BLOCK (g_debug ("%s: Account is store account.\n", __FUNCTION__););
378         *ac_out = account;
379
380         folder = tny_store_account_find_folder (TNY_STORE_ACCOUNT (account),
381                                                 uri,
382                                                 &err);
383
384         if (folder == NULL) {
385                 g_debug ("%s: tny_store_account_find_folder() failed for\n  account=%s, uri=%s.\n", __FUNCTION__, 
386                         tny_account_get_id (TNY_ACCOUNT(account)), uri);
387                 goto out;
388         }
389         
390         MODEST_DEBUG_BLOCK (g_debug ("%s: Found folder. (%s)\n",  __FUNCTION__, uri););
391         
392         msg = tny_folder_find_msg (folder, uri, &err);
393         
394         if (!msg)
395                 MODEST_DEBUG_BLOCK (
396                                     g_debug ("%s: tny_folder_find_msg() failed for "\
397                                              "folder %s\n  with error=%s.\n",
398                                              __FUNCTION__, tny_folder_get_id (folder), 
399                                              err->message);
400                                     );
401
402 out:
403         if (err)
404                 g_error_free (err);
405
406         if (account && !msg) {
407                 g_object_unref (account);
408                 *ac_out = NULL;
409         }
410
411         if (folder)
412                 g_object_unref (folder);
413
414         return msg;
415 }
416
417 static gboolean
418 on_idle_open_message (gpointer user_data)
419 {
420         TnyMsg       *msg = NULL;
421         TnyAccount   *account = NULL;
422         TnyHeader    *header = NULL; 
423         const char   *msg_uid = NULL;
424         char         *uri = NULL;
425         ModestWindowMgr *win_mgr = NULL;
426         TnyFolder    *folder = NULL;
427         gboolean is_draft = FALSE;
428         gboolean already_opened = FALSE;
429         ModestWindow *msg_view = NULL;
430
431         uri = (char *) user_data;
432
433         msg = find_message_by_url (uri, &account);
434         g_free (uri);
435
436         if (msg == NULL) {
437                 g_warning ("modest:  %s: message not found.", __FUNCTION__);
438                 g_idle_add (notify_error_in_dbus_callback, NULL);
439                 return FALSE;
440         }
441         
442         folder = tny_msg_get_folder (msg);
443         
444         /* Drafts will be opened in the editor, instead of the viewer, as per the UI spec: */
445         /* FIXME: same should happen for Outbox; not enabling that, as the handling
446          * of edited messages is not clear in that case */
447         if (folder && modest_tny_folder_is_local_folder (folder) &&
448                 (modest_tny_folder_get_local_or_mmc_folder_type (folder) == TNY_FOLDER_TYPE_DRAFTS)) {
449                 is_draft = TRUE;
450         }
451
452         header = tny_msg_get_header (msg);
453         
454         /* TODO:  The modest_tny_folder_get_header_unique_id() documentation warns against 
455          * using it with tny_msg_get_header(), and there is a 
456          * " camel_folder_get_full_name: assertion `CAMEL_IS_FOLDER (folder)' failed" runtime warning,
457          * but it seems to work.
458          */     
459         msg_uid =  modest_tny_folder_get_header_unique_id(header); 
460         
461         win_mgr = modest_runtime_get_window_mgr ();
462
463         /* This is a GDK lock because we are an idle callback and
464          * the code below is or does Gtk+ code */
465
466         gdk_threads_enter (); /* CHECKED */
467
468         if (modest_window_mgr_find_registered_header (win_mgr, header, &msg_view)) {
469                 if (msg_view) {
470                         g_debug ("modest: %s: A window for this message is open already: type=%s", 
471                         __FUNCTION__, G_OBJECT_TYPE_NAME (msg_view));
472                 }
473                 
474                 if (!msg_view)
475                         g_debug ("modest_window_mgr_find_registered_header(): Returned TRUE, but msg_view is NULL");
476                 else if (!MODEST_IS_MSG_VIEW_WINDOW (msg_view) && !MODEST_IS_MSG_EDIT_WINDOW (msg_view))
477                         g_debug ("  DEBUG: But the window is not a msg view or edit window.");
478                 else {
479                         gtk_window_present (GTK_WINDOW(msg_view));
480                         already_opened = TRUE;
481                 }
482         }
483         
484         if (!already_opened) {
485                 const gchar *modest_account_name;
486
487                 /* g_debug ("creating new window for this msg"); */
488                 modest_window_mgr_register_header (win_mgr, header, NULL);
489                 
490                 modest_account_name = 
491                         modest_tny_account_get_parent_modest_account_name_for_server_account (account);
492                         
493                 /* Drafts will be opened in the editor, and others will be opened in the viewer, 
494                  * as per the UI spec: */
495                 if (is_draft) {
496                         /* TODO: Maybe the msg_uid should be registered for edit windows too,
497                          * so we can open the same window again next time: */
498                         msg_view = modest_msg_edit_window_new (msg, modest_account_name, TRUE);
499                 } else {
500                         msg_view = modest_msg_view_window_new_for_search_result (msg, modest_account_name,
501                                                        msg_uid);
502                 }               
503                 modest_window_mgr_register_window (win_mgr, msg_view);
504                 gtk_widget_show_all (GTK_WIDGET (msg_view));
505         }
506
507         gdk_threads_leave (); /* CHECKED */
508
509         g_object_unref (header);
510         g_object_unref (account);
511         g_object_unref (folder);
512
513         return FALSE; /* Do not call this callback again. */
514 }
515
516 static gint 
517 on_open_message (GArray * arguments, gpointer data, osso_rpc_t * retval)
518 {
519         osso_rpc_t val;
520         gchar *uri;
521
522         /* Get the arguments: */
523         val = g_array_index(arguments, osso_rpc_t, MODEST_DBUS_OPEN_MESSAGE_ARG_URI);
524         uri = g_strdup (val.value.s);
525         
526         /* Use g_idle to context-switch into the application's thread */
527         g_idle_add(on_idle_open_message, (gpointer)uri);
528         
529         return OSSO_OK;
530 }
531
532 static gboolean
533 on_idle_delete_message (gpointer user_data)
534 {
535         TnyList *headers = NULL;
536         TnyFolder *folder = NULL;
537         TnyIterator *iter = NULL; 
538         TnyHeader *header = NULL, *msg_header = NULL;
539         TnyMsg *msg = NULL;
540         TnyAccount *account = NULL;
541         const char *uri = NULL, *uid = NULL;
542         gint res = 0;
543         ModestMailOperation *mail_op = NULL;
544         ModestWindow *main_win = NULL, *msg_view = NULL;
545
546         uri = (char *) user_data;
547         
548         msg = find_message_by_url (uri, &account);
549
550         if (!msg) {
551                 g_warning ("%s: Could not find message '%s'", __FUNCTION__, uri);
552                 g_idle_add (notify_error_in_dbus_callback, NULL);
553                 return OSSO_ERROR; 
554         }
555         
556         main_win = modest_window_mgr_get_main_window (modest_runtime_get_window_mgr(),
557                                                       FALSE); /* don't create */
558         
559         msg_header = tny_msg_get_header (msg);
560         uid = tny_header_get_uid (msg_header);
561         folder = tny_msg_get_folder (msg);
562
563         if (!folder) {
564                 g_warning ("%s: Could not find folder (uri:'%s')", __FUNCTION__, uri);
565                 g_object_unref (msg);
566                 g_idle_add (notify_error_in_dbus_callback, NULL);
567                 return OSSO_ERROR; 
568         }
569
570         headers = tny_simple_list_new ();
571         tny_folder_get_headers (folder, headers, TRUE, NULL);
572         iter = tny_list_create_iterator (headers);
573         header = NULL;
574
575         while (!tny_iterator_is_done (iter)) {
576                 const char *cur_id = NULL;
577
578                 header = TNY_HEADER (tny_iterator_get_current (iter));
579                 if (header)
580                         cur_id = tny_header_get_uid (header);
581                 
582                 if (cur_id && uid && g_str_equal (cur_id, uid)) {
583                         /* g_debug ("Found corresponding header from folder"); */
584                         break;
585                 }
586
587                 if (header) {
588                         g_object_unref (header);
589                         header = NULL;
590                 }
591                 
592                 tny_iterator_next (iter);
593         }
594
595         g_object_unref (iter);
596         iter = NULL;
597         g_object_unref (headers);
598         headers = NULL;
599         
600         g_object_unref (msg_header);
601         msg_header = NULL;
602         g_object_unref (msg);
603         msg = NULL;
604
605         if (header == NULL) {
606                 if (folder)
607                         g_object_unref (folder);
608                 g_idle_add (notify_error_in_dbus_callback, NULL);                       
609                 return OSSO_ERROR;
610         }
611                 
612         res = OSSO_OK;
613
614         /* This is a GDK lock because we are an idle callback and
615          * the code below is or does Gtk+ code */
616         gdk_threads_enter (); /* CHECKED */
617
618         mail_op = modest_mail_operation_new (main_win ? G_OBJECT(main_win) : NULL);
619         modest_mail_operation_queue_add (modest_runtime_get_mail_operation_queue (), mail_op);
620         modest_mail_operation_remove_msg (mail_op, header, FALSE);
621         g_object_unref (G_OBJECT (mail_op));
622         
623         if (main_win) { /* no need if there's no window */ 
624                 if (modest_window_mgr_find_registered_header (modest_runtime_get_window_mgr(),
625                                                               header, &msg_view)) {
626                         if (MODEST_IS_MSG_VIEW_WINDOW (msg_view))
627                                 modest_ui_actions_refresh_message_window_after_delete (MODEST_MSG_VIEW_WINDOW (msg_view));
628                 }
629         }
630         gdk_threads_leave (); /* CHECKED */
631         
632         if (header)
633                 g_object_unref (header);
634         
635         if (folder) {
636                 /* Trick: do a poke status in order to speed up the signaling
637                    of observers.
638                    A delete via the menu does this, in do_headers_action(), 
639                    though I don't know why.
640                  */
641                 tny_folder_poke_status (folder);
642         
643                 g_object_unref (folder);
644         }
645         
646         if (account)
647                 g_object_unref (account);
648                 
649         /* Refilter the header view explicitly, to make sure that 
650          * deleted emails are really removed from view. 
651          * (They are not really deleted until contact is made with the server, 
652          * so they would appear with a strike-through until then):
653          */
654         if (main_win) { /* only needed when there's a mainwindow / UI */
655
656                 /* This is a GDK lock because we are an idle callback and
657                  * the code below is or does Gtk+ code */
658                 gdk_threads_enter (); /* CHECKED */
659                 ModestHeaderView *header_view = (ModestHeaderView *)
660                         modest_main_window_get_child_widget (MODEST_MAIN_WINDOW(main_win),
661                                                              MODEST_MAIN_WINDOW_WIDGET_TYPE_HEADER_VIEW);
662                 if (header_view && MODEST_IS_HEADER_VIEW (header_view))
663                         modest_header_view_refilter (header_view);
664                 gdk_threads_leave ();
665         }
666         
667         return res;
668 }
669
670
671
672
673 static gint
674 on_delete_message (GArray *arguments, gpointer data, osso_rpc_t *retval)
675 {
676         /* Get the arguments: */
677         osso_rpc_t val = g_array_index (arguments,
678                              osso_rpc_t,
679                              MODEST_DBUS_DELETE_MESSAGE_ARG_URI);
680         gchar *uri = g_strdup (val.value.s);
681         
682         /* Use g_idle to context-switch into the application's thread: */
683         g_idle_add(on_idle_delete_message, (gpointer)uri);
684         
685         return OSSO_OK;
686 }
687
688 static gboolean
689 on_idle_send_receive(gpointer user_data)
690 {
691         ModestWindow *main_win =
692                 modest_window_mgr_get_main_window (modest_runtime_get_window_mgr (),
693                                                    FALSE); /* don't create */
694
695         /* Send & receive all */
696         gdk_threads_enter (); /* CHECKED */
697         modest_ui_actions_do_send_receive_all (main_win);
698         gdk_threads_leave (); /* CHECKED */
699         
700         return FALSE;
701 }
702
703 static gint 
704 on_send_receive(GArray *arguments, gpointer data, osso_rpc_t * retval)
705 {       
706         /* Use g_idle to context-switch into the application's thread: */
707         g_idle_add(on_idle_send_receive, NULL);
708         
709         return OSSO_OK;
710 }
711
712 static gboolean
713 on_idle_open_default_inbox(gpointer user_data)
714 {
715         ModestWindow *main_win;
716         GtkWidget *folder_view;
717         
718         if (!check_and_offer_account_creation ()) /* this has it's only lock already */
719                 return FALSE;
720
721         /* This is a GDK lock because we are an idle callback and
722          * the code below is or does Gtk+ code */
723         gdk_threads_enter (); /* CHECKED */
724
725         main_win = modest_window_mgr_get_main_window (modest_runtime_get_window_mgr (),
726                                                       TRUE); /* create if non-existent */
727         if (!main_win) {
728                 g_warning ("%s: BUG: no main window", __FUNCTION__);
729                 gdk_threads_leave (); /* CHECKED */
730                 return FALSE; /* don't call me again */
731         }
732                 
733         /* Get the folder view */
734         folder_view = modest_main_window_get_child_widget (MODEST_MAIN_WINDOW (main_win),
735                                                            MODEST_MAIN_WINDOW_WIDGET_TYPE_FOLDER_VIEW);
736         modest_folder_view_select_first_inbox_or_local (MODEST_FOLDER_VIEW (folder_view));
737         
738         gdk_threads_leave (); /* CHECKED */
739         
740         /* This D-Bus method is obviously meant to result in the UI being visible,
741          * so show it, by calling this idle handler directly: */
742         on_idle_top_application(user_data);
743         
744         return FALSE; /* Do not call this callback again. */
745 }
746
747 static gint 
748 on_open_default_inbox(GArray * arguments, gpointer data, osso_rpc_t * retval)
749 {
750         /* Use g_idle to context-switch into the application's thread: */
751         g_idle_add(on_idle_open_default_inbox, NULL);
752         
753         return OSSO_OK;
754 }
755
756
757 static gboolean 
758 on_idle_top_application (gpointer user_data)
759 {
760         ModestWindow *main_win;
761         
762         /* This is a GDK lock because we are an idle callback and
763          * the code below is or does Gtk+ code */
764
765         gdk_threads_enter (); /* CHECKED */
766         
767         main_win = modest_window_mgr_get_main_window (modest_runtime_get_window_mgr (),
768                                                       TRUE); /* create if non-existent */
769         if (main_win) {
770                 /* Ideally, we would just use gtk_widget_show(), 
771                  * but this widget is not coded correctly to support that: */
772                 gtk_widget_show_all (GTK_WIDGET (main_win));
773                 gtk_window_present (GTK_WINDOW (main_win));
774         } else
775                 g_warning ("%s: BUG: no main window", __FUNCTION__);
776
777         gdk_threads_leave (); /* CHECKED */
778         
779         return FALSE; /* Do not call this callback again. */
780 }
781
782 static gint 
783 on_top_application(GArray * arguments, gpointer data, osso_rpc_t * retval)
784 {
785         /* Use g_idle to context-switch into the application's thread: */
786         g_idle_add(on_idle_top_application, NULL);
787         
788         return OSSO_OK;
789 }
790                       
791 /* Callback for normal D-BUS messages */
792 gint 
793 modest_dbus_req_handler(const gchar * interface, const gchar * method,
794                         GArray * arguments, gpointer data,
795                         osso_rpc_t * retval)
796 {
797         if (g_ascii_strcasecmp (method, MODEST_DBUS_METHOD_MAIL_TO) == 0) {
798                 if (arguments->len != MODEST_DBUS_MAIL_TO_ARGS_COUNT)
799                         goto param_error;
800                 return on_mail_to (arguments, data, retval);            
801         } else if (g_ascii_strcasecmp (method, MODEST_DBUS_METHOD_OPEN_MESSAGE) == 0) {
802                 if (arguments->len != MODEST_DBUS_OPEN_MESSAGE_ARGS_COUNT)
803                         goto param_error;
804                 return on_open_message (arguments, data, retval);
805         } else if (g_ascii_strcasecmp (method, MODEST_DBUS_METHOD_SEND_RECEIVE) == 0) {
806                 if (arguments->len != 0)
807                         goto param_error;
808                 return on_send_receive (arguments, data, retval);
809         } else if (g_ascii_strcasecmp (method, MODEST_DBUS_METHOD_COMPOSE_MAIL) == 0) {
810                 if (arguments->len != MODEST_DBUS_COMPOSE_MAIL_ARGS_COUNT)
811                         goto param_error;
812                 return on_compose_mail (arguments, data, retval);
813         } else if (g_ascii_strcasecmp (method, MODEST_DBUS_METHOD_DELETE_MESSAGE) == 0) {
814                 if (arguments->len != MODEST_DBUS_DELETE_MESSAGE_ARGS_COUNT)
815                         goto param_error;
816                 return on_delete_message (arguments,data, retval);
817         } else if (g_ascii_strcasecmp (method, MODEST_DBUS_METHOD_OPEN_DEFAULT_INBOX) == 0) {
818                 if (arguments->len != 0)
819                         goto param_error;
820                 return on_open_default_inbox (arguments, data, retval);
821         } else if (g_ascii_strcasecmp (method, MODEST_DBUS_METHOD_TOP_APPLICATION) == 0) {
822                 if (arguments->len != 0)
823                         goto param_error;
824                 return on_top_application (arguments, data, retval);
825         } else { 
826                 /* We need to return INVALID here so
827                  * libosso will return DBUS_HANDLER_RESULT_NOT_YET_HANDLED,
828                  * so that our modest_dbus_req_filter will then be tried instead.
829                  * */
830                 return OSSO_INVALID;
831         }
832  param_error:
833         /* Notify error in D-Bus method */
834         g_idle_add (notify_error_in_dbus_callback, NULL);
835         return OSSO_ERROR;
836 }
837                                          
838 /* A complex D-Bus type (like a struct),
839  * used to return various information about a search hit.
840  */
841 #define SEARCH_HIT_DBUS_TYPE \
842         DBUS_STRUCT_BEGIN_CHAR_AS_STRING \
843         DBUS_TYPE_STRING_AS_STRING /* msgid */ \
844         DBUS_TYPE_STRING_AS_STRING /* subject */ \
845         DBUS_TYPE_STRING_AS_STRING /* folder */ \
846         DBUS_TYPE_STRING_AS_STRING /* sender */ \
847         DBUS_TYPE_UINT64_AS_STRING /* msize */ \
848         DBUS_TYPE_BOOLEAN_AS_STRING /* has_attachment */ \
849         DBUS_TYPE_BOOLEAN_AS_STRING /* is_unread */ \
850         DBUS_TYPE_INT64_AS_STRING /* timestamp */ \
851         DBUS_STRUCT_END_CHAR_AS_STRING
852
853 static DBusMessage *
854 search_result_to_message (DBusMessage *reply,
855                            GList       *hits)
856 {
857         DBusMessageIter iter;
858         DBusMessageIter array_iter;
859         GList          *hit_iter;
860
861         dbus_message_iter_init_append (reply, &iter); 
862         dbus_message_iter_open_container (&iter,
863                                           DBUS_TYPE_ARRAY,
864                                           SEARCH_HIT_DBUS_TYPE,
865                                           &array_iter); 
866
867         for (hit_iter = hits; hit_iter; hit_iter = hit_iter->next) {
868                 DBusMessageIter  struct_iter;
869                 ModestSearchHit *hit;
870                 char            *msg_url;
871                 const char      *subject;
872                 const char      *folder;
873                 const char      *sender;
874                 guint64          size;
875                 gboolean         has_attachment;
876                 gboolean         is_unread;
877                 gint64           ts;
878
879                 hit = (ModestSearchHit *) hit_iter->data;
880
881                 msg_url = hit->msgid;
882                 subject = hit->subject;
883                 folder  = hit->folder;
884                 sender  = hit->sender;
885                 size           = hit->msize;
886                 has_attachment = hit->has_attachment;
887                 is_unread      = hit->is_unread;
888                 ts             = hit->timestamp;
889
890                 g_debug ("DEBUG: %s: Adding hit: %s", __FUNCTION__, msg_url);   
891                 
892                 dbus_message_iter_open_container (&array_iter,
893                                                   DBUS_TYPE_STRUCT,
894                                                   NULL,
895                                                   &struct_iter);
896
897                 dbus_message_iter_append_basic (&struct_iter,
898                                                 DBUS_TYPE_STRING,
899                                                 &msg_url);
900
901                 dbus_message_iter_append_basic (&struct_iter,
902                                                 DBUS_TYPE_STRING,
903                                                 &subject); 
904
905                 dbus_message_iter_append_basic (&struct_iter,
906                                                 DBUS_TYPE_STRING,
907                                                 &folder);
908
909                 dbus_message_iter_append_basic (&struct_iter,
910                                                 DBUS_TYPE_STRING,
911                                                 &sender);
912
913                 dbus_message_iter_append_basic (&struct_iter,
914                                                 DBUS_TYPE_UINT64,
915                                                 &size);
916
917                 dbus_message_iter_append_basic (&struct_iter,
918                                                 DBUS_TYPE_BOOLEAN,
919                                                 &has_attachment);
920
921                 dbus_message_iter_append_basic (&struct_iter,
922                                                 DBUS_TYPE_BOOLEAN,
923                                                 &is_unread);
924                 
925                 dbus_message_iter_append_basic (&struct_iter,
926                                                 DBUS_TYPE_INT64,
927                                                 &ts);
928
929                 dbus_message_iter_close_container (&array_iter,
930                                                    &struct_iter); 
931
932                 g_free (hit->msgid);
933                 g_free (hit->subject);
934                 g_free (hit->folder);
935                 g_free (hit->sender);
936
937                 g_slice_free (ModestSearchHit, hit);
938         }
939
940         dbus_message_iter_close_container (&iter, &array_iter);
941
942         return reply;
943 }
944
945
946 static void
947 on_dbus_method_search (DBusConnection *con, DBusMessage *message)
948 {
949         ModestDBusSearchFlags dbus_flags;
950         DBusMessage  *reply = NULL;
951         dbus_bool_t  res;
952         dbus_int64_t sd_v;
953         dbus_int64_t ed_v;
954         dbus_int32_t flags_v;
955         dbus_uint32_t size_v;
956         const char *folder;
957         const char *query;
958         time_t start_date;
959         time_t end_date;
960         GList *hits;
961
962         DBusError error;
963         dbus_error_init (&error);
964
965         sd_v = ed_v = 0;
966         flags_v = 0;
967
968         res = dbus_message_get_args (message,
969                                      &error,
970                                      DBUS_TYPE_STRING, &query,
971                                      DBUS_TYPE_STRING, &folder, /* e.g. "INBOX/drafts": TODO: Use both an ID and a display name. */
972                                      DBUS_TYPE_INT64, &sd_v,
973                                      DBUS_TYPE_INT64, &ed_v,
974                                      DBUS_TYPE_INT32, &flags_v,
975                                      DBUS_TYPE_UINT32, &size_v,
976                                      DBUS_TYPE_INVALID);
977
978         dbus_flags = (ModestDBusSearchFlags) flags_v;
979         start_date = (time_t) sd_v;
980         end_date = (time_t) ed_v;
981
982         ModestSearch search;
983         memset (&search, 0, sizeof (search));
984         
985         /* Remember what folder we are searching in:
986          *
987          * Note that we don't copy the strings, 
988          * because this struct will only be used for the lifetime of this function.
989          */
990         if (folder && g_str_has_prefix (folder, "MAND:")) {
991                 search.folder = folder + strlen ("MAND:");
992         } else if (folder && g_str_has_prefix (folder, "USER:")) {
993                 search.folder = folder + strlen ("USER:");
994         } else if (folder && g_str_has_prefix (folder, "MY:")) {
995                 search.folder = folder + strlen ("MY:");
996         } else {
997                 search.folder = folder;
998         }
999
1000    /* Remember the text to search for: */
1001 #ifdef MODEST_HAVE_OGS
1002         search.query  = query;
1003 #endif
1004
1005         /* Other criteria: */
1006         search.start_date = start_date;
1007         search.end_date  = end_date;
1008         search.flags  = 0;
1009
1010         /* Text to serach for in various parts of the message: */
1011         if (dbus_flags & MODEST_DBUS_SEARCH_SUBJECT) {
1012                 search.flags |= MODEST_SEARCH_SUBJECT;
1013                 search.subject = query;
1014         }
1015
1016         if (dbus_flags & MODEST_DBUS_SEARCH_SENDER) {
1017                 search.flags |=  MODEST_SEARCH_SENDER;
1018                 search.from = query;
1019         }
1020
1021         if (dbus_flags & MODEST_DBUS_SEARCH_RECIPIENT) {
1022                 search.flags |= MODEST_SEARCH_RECIPIENT; 
1023                 search.recipient = query;
1024         }
1025
1026         if (dbus_flags & MODEST_DBUS_SEARCH_BODY) {
1027                 search.flags |=  MODEST_SEARCH_BODY; 
1028                 search.body = query;
1029         }
1030
1031         if (sd_v > 0) {
1032                 search.flags |= MODEST_SEARCH_BEFORE;
1033                 search.start_date = start_date;
1034         }
1035
1036         if (ed_v > 0) {
1037                 search.flags |= MODEST_SEARCH_AFTER;
1038                 search.end_date = end_date;
1039         }
1040
1041         if (size_v > 0) {
1042                 search.flags |= MODEST_SEARCH_SIZE;
1043                 search.minsize = size_v;
1044         }
1045
1046 #ifdef MODEST_HAVE_OGS
1047         search.flags |= MODEST_SEARCH_USE_OGS;
1048         g_debug ("%s: Starting search for %s", __FUNCTION__, search.query);
1049 #endif
1050
1051         /* Note that this currently gets folders and messages from the servers, 
1052          * which can take a long time. libmodest_dbus_client_search() can timeout, 
1053          * reporting no results, if this takes a long time: */
1054         hits = modest_search_all_accounts (&search);
1055
1056         reply = dbus_message_new_method_return (message);
1057
1058         search_result_to_message (reply, hits);
1059
1060         if (reply == NULL) {
1061                 g_warning ("%s: Could not create reply.", __FUNCTION__);
1062         }
1063
1064         if (reply) {
1065                 dbus_uint32_t serial = 0;
1066                 dbus_connection_send (con, reply, &serial);
1067         dbus_connection_flush (con);
1068         dbus_message_unref (reply);
1069         }
1070
1071         g_list_free (hits);
1072 }
1073
1074
1075 /* A complex D-Bus type (like a struct),
1076  * used to return various information about a folder.
1077  */
1078 #define GET_FOLDERS_RESULT_DBUS_TYPE \
1079         DBUS_STRUCT_BEGIN_CHAR_AS_STRING \
1080         DBUS_TYPE_STRING_AS_STRING /* Folder Name */ \
1081         DBUS_TYPE_STRING_AS_STRING /* Folder URI */ \
1082         DBUS_STRUCT_END_CHAR_AS_STRING
1083
1084 static DBusMessage *
1085 get_folders_result_to_message (DBusMessage *reply,
1086                            GList *folder_ids)
1087 {
1088         DBusMessageIter iter;   
1089         dbus_message_iter_init_append (reply, &iter); 
1090         
1091         DBusMessageIter array_iter;
1092         dbus_message_iter_open_container (&iter,
1093                                           DBUS_TYPE_ARRAY,
1094                                           GET_FOLDERS_RESULT_DBUS_TYPE,
1095                                           &array_iter); 
1096
1097         GList *list_iter = folder_ids;
1098         for (list_iter = folder_ids; list_iter; list_iter = list_iter->next) {
1099                 
1100                 const gchar *folder_name = (const gchar*)list_iter->data;
1101                 if (folder_name) {
1102                         /* g_debug ("DEBUG: %s: Adding folder: %s", __FUNCTION__, folder_name); */
1103                         
1104                         DBusMessageIter struct_iter;
1105                         dbus_message_iter_open_container (&array_iter,
1106                                                           DBUS_TYPE_STRUCT,
1107                                                           NULL,
1108                                                           &struct_iter);
1109         
1110                         /* name: */
1111                         dbus_message_iter_append_basic (&struct_iter,
1112                                                         DBUS_TYPE_STRING,
1113                                                         &folder_name); /* The string will be copied. */
1114                                                         
1115                         /* URI: This is maybe not needed by osso-global-search: */
1116                         const gchar *folder_uri = "TODO:unimplemented";
1117                         dbus_message_iter_append_basic (&struct_iter,
1118                                                         DBUS_TYPE_STRING,
1119                                                         &folder_uri); /* The string will be copied. */
1120         
1121                         dbus_message_iter_close_container (&array_iter,
1122                                                            &struct_iter); 
1123                 }
1124         }
1125
1126         dbus_message_iter_close_container (&iter, &array_iter);
1127
1128         return reply;
1129 }
1130
1131 static void
1132 add_single_folder_to_list (TnyFolder *folder, GList** list)
1133 {
1134         if (!folder)
1135                 return;
1136                 
1137         if (TNY_IS_MERGE_FOLDER (folder)) {
1138                 const gchar * folder_name;
1139                 /* Ignore these because their IDs ares
1140                  * a) not always unique or sensible.
1141                  * b) not human-readable, and currently need a human-readable 
1142                  *    ID here, because the osso-email-interface API does not allow 
1143                  *    us to return both an ID and a display name.
1144                  * 
1145                  * This is actually the merged outbox folder.
1146                  * We could hack our D-Bus API to understand "outbox" as the merged outboxes, 
1147                  * but that seems unwise. murrayc.
1148                  */
1149                 folder_name = tny_folder_get_name (folder);
1150                 if (folder_name && !strcmp (folder_name, "Outbox")) {
1151                         *list = g_list_append(*list, g_strdup ("MAND:outbox"));
1152                 }
1153                 return; 
1154         }
1155                 
1156         /* Add this folder to the list: */
1157         /*
1158         const gchar * folder_name = tny_folder_get_name (folder);
1159         if (folder_name)
1160                 *list = g_list_append(*list, g_strdup (folder_name));
1161         else {
1162         */
1163                 /* osso-global-search only uses one string,
1164                  * so ID is the only thing that could possibly identify a folder.
1165                  * TODO: osso-global search should probably be changed to 
1166                  * take an ID and a Name.
1167                  */
1168         const gchar * id =  tny_folder_get_id (folder);
1169         if (id && strlen(id)) {
1170                 const gchar *prefix = NULL;
1171                 TnyFolderType folder_type;
1172                         
1173                 /* dbus global search api expects a prefix identifying the type of
1174                  * folder here. Mandatory folders should have MAND: prefix, and
1175                  * other user created folders should have USER: prefix
1176                  */
1177                 folder_type = modest_tny_folder_guess_folder_type (folder);
1178                 switch (folder_type) {
1179                 case TNY_FOLDER_TYPE_INBOX:
1180                         prefix = "MY:";
1181                         break;
1182                 case TNY_FOLDER_TYPE_OUTBOX:
1183                 case TNY_FOLDER_TYPE_DRAFTS:
1184                 case TNY_FOLDER_TYPE_SENT:
1185                 case TNY_FOLDER_TYPE_ARCHIVE:
1186                         prefix = "MAND:";
1187                         break;
1188                 case TNY_FOLDER_TYPE_INVALID:
1189                         g_warning ("%s: BUG: TNY_FOLDER_TYPE_INVALID", __FUNCTION__);
1190                         return; /* don't add it */
1191                 default:
1192                         prefix = "USER:";
1193                         
1194                 }
1195                 
1196
1197                 *list = g_list_append(*list, g_strdup_printf ("%s%s", prefix, id));
1198         }
1199 }
1200
1201 static void
1202 add_folders_to_list (TnyFolderStore *folder_store, GList** list)
1203 {
1204         if (!folder_store)
1205                 return;
1206         
1207         /* Add this folder to the list: */
1208         if (TNY_IS_FOLDER (folder_store)) {
1209                 add_single_folder_to_list (TNY_FOLDER (folder_store), list);
1210         }       
1211                 
1212         /* Recurse into child folders: */
1213                 
1214         /* Get the folders list: */
1215         /*
1216         TnyFolderStoreQuery *query = tny_folder_store_query_new ();
1217         tny_folder_store_query_add_item (query, NULL, 
1218                 TNY_FOLDER_STORE_QUERY_OPTION_SUBSCRIBED);
1219         */
1220         TnyList *all_folders = tny_simple_list_new ();
1221         tny_folder_store_get_folders (folder_store,
1222                                       all_folders,
1223                                       NULL /* query */,
1224                                       NULL /* error */);
1225
1226         TnyIterator *iter = tny_list_create_iterator (all_folders);
1227         while (!tny_iterator_is_done (iter)) {
1228                 
1229                 /* Do not recurse, because the osso-global-search UI specification 
1230                  * does not seem to want the sub-folders, though that spec seems to 
1231                  * be generally unsuitable for Modest.
1232                  */
1233                 TnyFolder *folder = TNY_FOLDER (tny_iterator_get_current (iter));
1234                 if (folder) {
1235                         add_single_folder_to_list (TNY_FOLDER (folder), list);
1236                          
1237                         #if 0
1238                         if (TNY_IS_FOLDER_STORE (folder))
1239                                 add_folders_to_list (TNY_FOLDER_STORE (folder), list);
1240                         else {
1241                                 add_single_folder_to_list (TNY_FOLDER (folder), list);
1242                         }
1243                         #endif
1244                         
1245                         /* tny_iterator_get_current() gave us a reference. */
1246                         g_object_unref (folder);
1247                 }
1248                 
1249                 tny_iterator_next (iter);
1250         }
1251         g_object_unref (G_OBJECT (iter));
1252 }
1253
1254
1255 /* return >1 for a special folder, 0 for a user-folder */
1256 static gint
1257 get_rank (const gchar *folder)
1258 {
1259         if (strcmp (folder, "INBOX") == 0)
1260                 return 1;
1261         if (strcmp (folder, modest_local_folder_info_get_type_name(TNY_FOLDER_TYPE_SENT)) == 0)
1262                 return 2;
1263         if (strcmp (folder, modest_local_folder_info_get_type_name(TNY_FOLDER_TYPE_DRAFTS)) == 0)
1264                 return 3;
1265         if (strcmp (folder, modest_local_folder_info_get_type_name(TNY_FOLDER_TYPE_OUTBOX)) == 0)
1266                 return 4;
1267         return 0;
1268 }
1269
1270 static gint
1271 folder_name_compare_func (const gchar* folder1, const gchar* folder2)
1272 {
1273         gint r1 = get_rank (folder1);
1274         gint r2 = get_rank (folder2);
1275
1276         if (r1 > 0 && r2 > 0)
1277                 return r1 - r2;
1278         if (r1 > 0 && r2 == 0)
1279                 return -1;
1280         if (r1 == 0 && r2 > 0)
1281                 return 1;
1282         else
1283                 return  modest_text_utils_utf8_strcmp (folder1, folder2, TRUE);
1284 }
1285
1286 /* FIXME: */
1287 /*   - we're still missing the outbox */
1288 /*   - we need to take care of localization (urgh) */
1289 /*   - what about 'All mail folders'? */
1290 static void
1291 on_dbus_method_get_folders (DBusConnection *con, DBusMessage *message)
1292 {
1293         DBusMessage  *reply = NULL;
1294         ModestAccountMgr *account_mgr = NULL;
1295         gchar *account_name = NULL;
1296         GList *folder_names = NULL;     
1297         TnyAccount *account_local = NULL;
1298         TnyAccount *account_mmc = NULL;
1299         
1300         /* Get the TnyStoreAccount so we can get the folders: */
1301         account_mgr = modest_runtime_get_account_mgr();
1302         account_name = modest_account_mgr_get_default_account (account_mgr);
1303         if (!account_name) {
1304                 g_printerr ("modest: no account found\n");
1305         }
1306         
1307         if (account_name) {
1308                 TnyAccount *account = NULL;
1309                 if (account_mgr) {
1310                         account = modest_tny_account_store_get_server_account (
1311                                 modest_runtime_get_account_store(), account_name, 
1312                                 TNY_ACCOUNT_TYPE_STORE);
1313                 }
1314                 
1315                 if (!account) {
1316                         g_printerr ("modest: failed to get tny account folder'%s'\n", account_name);
1317                 } 
1318                 
1319                 printf("DEBUG: %s: Getting folders for account name=%s\n", __FUNCTION__, account_name);
1320                 g_free (account_name);
1321                 account_name = NULL;
1322                 
1323                 add_folders_to_list (TNY_FOLDER_STORE (account), &folder_names);
1324         
1325                 g_object_unref (account);
1326                 account = NULL;
1327         }
1328         
1329         /* Also add the folders from the local folders account,
1330          * because they are (currently) used with all accounts:
1331          * TODO: This is not working. It seems to get only the Merged Folder (with an ID of "" (not NULL)).
1332          */
1333         account_local = 
1334                 modest_tny_account_store_get_local_folders_account (modest_runtime_get_account_store());
1335         add_folders_to_list (TNY_FOLDER_STORE (account_local), &folder_names);
1336
1337         g_object_unref (account_local);
1338         account_local = NULL;
1339
1340         /* Obtain the mmc account */
1341         account_mmc = 
1342                 modest_tny_account_store_get_mmc_folders_account (modest_runtime_get_account_store());
1343         if (account_mmc) {
1344                 add_folders_to_list (TNY_FOLDER_STORE (account_mmc), &folder_names);
1345                 g_object_unref (account_mmc);
1346                 account_mmc = NULL;
1347         }
1348
1349         /* specs require us to sort the folder names, although
1350          * this is really not the place to do that...
1351          */
1352         folder_names = g_list_sort (folder_names,
1353                                     (GCompareFunc)folder_name_compare_func);
1354
1355         /* Put the result in a DBus reply: */
1356         reply = dbus_message_new_method_return (message);
1357
1358         get_folders_result_to_message (reply, folder_names);
1359
1360         if (reply == NULL) {
1361                 g_warning ("%s: Could not create reply.", __FUNCTION__);
1362         }
1363
1364         if (reply) {
1365                 dbus_uint32_t serial = 0;
1366                 dbus_connection_send (con, reply, &serial);
1367         dbus_connection_flush (con);
1368         dbus_message_unref (reply);
1369         }
1370
1371         g_list_foreach (folder_names, (GFunc)g_free, NULL);
1372         g_list_free (folder_names);
1373 }
1374
1375
1376 /** This D-Bus handler is used when the main osso-rpc 
1377  * D-Bus handler has not handled something.
1378  * We use this for D-Bus methods that need to use more complex types 
1379  * than osso-rpc supports.
1380  */
1381 DBusHandlerResult
1382 modest_dbus_req_filter (DBusConnection *con,
1383                         DBusMessage    *message,
1384                         void           *user_data)
1385 {
1386         gboolean handled = FALSE;
1387
1388         if (dbus_message_is_method_call (message,
1389                                          MODEST_DBUS_IFACE,
1390                                          MODEST_DBUS_METHOD_SEARCH)) {
1391                 on_dbus_method_search (con, message);
1392                 handled = TRUE;                         
1393         } else if (dbus_message_is_method_call (message,
1394                                          MODEST_DBUS_IFACE,
1395                                          MODEST_DBUS_METHOD_GET_FOLDERS)) {
1396                 on_dbus_method_get_folders (con, message);
1397                 handled = TRUE;                         
1398         }
1399         else {
1400                 /* Note that this mentions methods that were already handled in modest_dbus_req_handler(). */
1401                 /* 
1402                 g_debug ("  debug: %s: Unexpected (maybe already handled) D-Bus method:\n   Interface=%s, Member=%s\n", 
1403                         __FUNCTION__, dbus_message_get_interface (message),
1404                         dbus_message_get_member(message));
1405                 */
1406         }
1407         
1408         return (handled ? 
1409                 DBUS_HANDLER_RESULT_HANDLED :
1410                 DBUS_HANDLER_RESULT_NOT_YET_HANDLED);
1411 }
1412
1413 static gboolean
1414 notify_error_in_dbus_callback (gpointer user_data)
1415 {
1416         ModestMailOperation *mail_op;
1417         ModestMailOperationQueue *mail_op_queue;
1418
1419         mail_op = modest_mail_operation_new (NULL);
1420         mail_op_queue = modest_runtime_get_mail_operation_queue ();
1421
1422         /* Issues a noop operation in order to force the queue to emit
1423            the "queue-empty" signal to allow modest to quit */
1424         modest_mail_operation_queue_add (mail_op_queue, mail_op);
1425         modest_mail_operation_noop (mail_op);
1426         g_object_unref (mail_op);
1427
1428         return FALSE;
1429 }