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