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