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