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