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