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