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