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