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