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