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