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