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