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