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