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