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         gdk_threads_enter ();
189         
190         /* This is based on the implemenation of main.c:start_uil(): */
191         
192         gchar *uri = (gchar*)user_data;
193         GSList *list_names_and_values = NULL;
194         gchar *to = uri_parse_mailto (uri, &list_names_and_values);
195         
196         /* Get the TnyTransportAccount so we can instantiate a mail operation: */
197         ModestAccountMgr *account_mgr = modest_runtime_get_account_mgr();
198         gchar *account_name = modest_account_mgr_get_default_account (account_mgr);
199         if (!account_name) {
200                 g_printerr ("modest: no account found\n");
201         }
202         
203         TnyAccount *account = NULL;
204         if (account_mgr) {
205                 account = modest_tny_account_store_get_transport_account_for_open_connection (
206                         modest_runtime_get_account_store(), account_name);
207         }
208         
209         if (!account) {
210                 g_printerr ("modest: failed to get tny account folder'\n", account_name);
211         } else {
212                 gchar * from = modest_account_mgr_get_from_string (account_mgr,
213                                                                   account_name);
214                 if (!from) {
215                         g_printerr ("modest: no from address for account '%s'\n", account_name);
216                 } else {
217                         const gchar *cc = NULL;
218                         const gchar *bcc = NULL;
219                         const gchar *subject = NULL;
220                         const gchar *body = NULL;
221                         
222                         /* Get the relevant items from the list: */
223                         GSList *list = list_names_and_values;
224                         while (list) {
225                                 const gchar * name = (const gchar*)list->data;
226                                 GSList *list_value = g_slist_next (list);
227                                 const gchar * value = (const gchar*)list_value->data;
228                                 
229                                 if (strcmp (name, "cc") == 0) {
230                                         cc = value;
231                                 } else if (strcmp (name, "bcc") == 0) {
232                                         bcc = value;
233                                 } else if (strcmp (name, "subject") == 0) {
234                                         subject = value;
235                                 } else if (strcmp (name, "body") == 0) {
236                                         body = value;
237                                 }
238                                 
239                                 /* Go to the next pair: */
240                                 if (list_value) {
241                                         list = g_slist_next (list_value);
242                                 } else 
243                                         list = NULL;
244                         }
245                         
246                         /* Create the message: */
247                         TnyMsg *msg  = modest_tny_msg_new (to, from, 
248                                 cc, bcc, subject, body, 
249                                 NULL /* attachments */);
250                                 
251                         if (!msg) {
252                                 g_printerr ("modest: failed to create message\n");
253                         } else
254                         {
255                                 /* Add the message to a folder and show its UI for editing: */
256                                 TnyFolder *folder = modest_tny_account_get_special_folder (account,
257                                                                         TNY_FOLDER_TYPE_DRAFTS);
258                                 if (!folder) {
259                                         g_printerr ("modest: failed to find Drafts folder\n");
260                                 } else {
261                         
262                                         tny_folder_add_msg (folder, msg, NULL); /* TODO: check err */
263                 
264                                         ModestWindow *win = modest_msg_edit_window_new (msg, account_name);
265                                         gtk_widget_show_all (GTK_WIDGET (win));
266                                 
267                                         g_object_unref (G_OBJECT(folder));
268                                 }
269                         
270                                 g_object_unref (G_OBJECT(msg));
271                         }
272                         
273                         g_object_unref (G_OBJECT(account));
274                 }
275         }
276         
277         g_free (account_name);
278         
279         /* Free the list, as required by the uri_parse_mailto() documentation: */
280         if (list_names_and_values)
281                 g_slist_foreach (list_names_and_values, (GFunc)g_free, NULL);
282         g_slist_free (list_names_and_values);
283         
284         g_free(to);
285                 
286         g_free(uri);
287
288         gdk_threads_leave ();
289         
290         return FALSE; /* Do not call this callback again. */
291 }
292
293 static gint on_mail_to(GArray * arguments, gpointer data, osso_rpc_t * retval)
294 {
295         if (arguments->len != MODEST_DEBUS_MAIL_TO_ARGS_COUNT)
296         return OSSO_ERROR;
297         
298     /* Use g_idle to context-switch into the application's thread: */
299  
300     /* Get the arguments: */
301         osso_rpc_t val = g_array_index(arguments, osso_rpc_t, MODEST_DEBUS_MAIL_TO_ARG_URI);
302         gchar *uri = g_strdup (val.value.s);
303         
304         /* printf("  debug: to=%s\n", idle_data->to); */
305         g_idle_add(on_idle_mail_to, (gpointer)uri);
306         
307         /* Note that we cannot report failures during sending, 
308          * because that would be asynchronous. */
309         return OSSO_OK;
310 }
311
312
313
314
315
316 static gboolean
317 on_idle_compose_mail(gpointer user_data)
318 {
319         gdk_threads_enter ();
320         
321         ComposeMailIdleData *idle_data = (ComposeMailIdleData*)user_data;
322         gchar **list = NULL;
323         gint i = 0;
324
325         /* Get the TnyTransportAccount so we can instantiate a mail operation: */
326         ModestAccountMgr *account_mgr = modest_runtime_get_account_mgr();
327         gchar *account_name = modest_account_mgr_get_default_account (account_mgr);
328         if (!account_name) {
329                 g_printerr ("modest: no account found\n");
330         }
331         
332         TnyAccount *account = NULL;
333         if (account_mgr) {
334                 account = modest_tny_account_store_get_transport_account_for_open_connection (
335                         modest_runtime_get_account_store(), account_name);
336         }
337         
338         if (!account) {
339                 g_printerr ("modest: failed to get tny account folder'%s'\n", account_name);
340         } else {
341                 gchar * from = modest_account_mgr_get_from_string (account_mgr,
342                                                                   account_name);
343                 if (!from) {
344                         g_printerr ("modest: no from address for account '%s'\n", account_name);
345                 } else {
346         
347                         /* Create the message: */
348                         TnyMsg *msg  = modest_tny_msg_new (idle_data->to, from, 
349                                 idle_data->cc, idle_data->bcc, idle_data->subject, idle_data->body, 
350                                 NULL); /* NULL because m_t_m_n doesn't use it */
351                                 
352                         if (!msg) {
353                                 g_printerr ("modest: failed to create message\n");
354                         } else
355                         {
356                                 /* Add the message to a folder and show its UI for editing: */
357                                 TnyFolder *folder = modest_tny_account_get_special_folder (account,
358                                                                         TNY_FOLDER_TYPE_DRAFTS);
359                                 if (!folder) {
360                                         g_printerr ("modest: failed to find Drafts folder\n");
361                                 } else {
362                         
363                                         tny_folder_add_msg (folder, msg, NULL); /* TODO: check err */
364                 
365                                         ModestWindow *win = modest_msg_edit_window_new (msg, account_name);
366
367                                         /* it seems Sketch at least sends a leading ',' -- take that into account,
368                                          * ie strip that ,*/
369                                         if (idle_data->attachments && idle_data->attachments[0]==',') {
370                                                 gchar *tmp = g_strdup (idle_data->attachments + 1);
371                                                 g_free(idle_data->attachments);
372                                                 idle_data->attachments = tmp;
373                                         }
374
375                                         list = g_strsplit(idle_data->attachments, ",", 0);
376                                         for (i=0; list[i] != NULL; i++) {
377                                                 modest_msg_edit_window_attach_file_noninteractive(
378                                                                 (ModestMsgEditWindow *)win, list[i]);
379                                         }
380                                         g_strfreev(list);
381                                         
382                                         gtk_widget_show_all (GTK_WIDGET (win));
383                                 
384                                         g_object_unref (G_OBJECT(folder));
385                                 }
386                         
387                                 g_object_unref (G_OBJECT(msg));
388                         }
389                         
390                         g_object_unref (G_OBJECT(account));
391                 }
392         }
393
394         /* Free the idle data: */
395         g_free (idle_data->to);
396         g_free (idle_data->cc);
397         g_free (idle_data->bcc);
398         g_free (idle_data->subject);
399         g_free (idle_data->body);
400         g_free (idle_data->attachments);
401         g_free (idle_data);
402         
403         g_free (account_name);
404         
405         gdk_threads_leave ();
406         
407         return FALSE; /* Do not call this callback again. */
408 }
409
410 static gint on_compose_mail(GArray * arguments, gpointer data, osso_rpc_t * retval)
411 {
412         if (arguments->len != MODEST_DEBUS_COMPOSE_MAIL_ARGS_COUNT)
413         return OSSO_ERROR;
414         
415         /* Use g_idle to context-switch into the application's thread: */
416         ComposeMailIdleData *idle_data = g_new0(ComposeMailIdleData, 1); /* Freed in the idle callback. */
417         
418         /* Get the arguments: */
419         osso_rpc_t val = g_array_index(arguments, osso_rpc_t, MODEST_DEBUS_COMPOSE_MAIL_ARG_TO);
420         idle_data->to = g_strdup (val.value.s);
421         
422         val = g_array_index(arguments, osso_rpc_t, MODEST_DEBUS_COMPOSE_MAIL_ARG_CC);
423         idle_data->cc = g_strdup (val.value.s);
424         
425         val = g_array_index(arguments, osso_rpc_t, MODEST_DEBUS_COMPOSE_MAIL_ARG_BCC);
426         idle_data->bcc = g_strdup (val.value.s);
427         
428         val = g_array_index(arguments, osso_rpc_t, MODEST_DEBUS_COMPOSE_MAIL_ARG_SUBJECT);
429         idle_data->subject = g_strdup (val.value.s);
430         
431         val = g_array_index(arguments, osso_rpc_t, MODEST_DEBUS_COMPOSE_MAIL_ARG_BODY);
432         idle_data->body = g_strdup (val.value.s);
433         
434         val = g_array_index(arguments, osso_rpc_t, MODEST_DEBUS_COMPOSE_MAIL_ARG_ATTACHMENTS);
435         idle_data->attachments = g_strdup (val.value.s);
436
437         g_idle_add(on_idle_compose_mail, (gpointer)idle_data);
438         
439         /* Note that we cannot report failures during sending, 
440          * because that would be asynchronous. */
441         return OSSO_OK;
442 }
443
444
445 static TnyMsg *
446 find_message_by_url (const char *uri, TnyAccount **ac_out)
447 {
448         ModestTnyAccountStore *astore;
449         TnyAccount            *account;
450         TnyFolder             *folder;
451         TnyMsg                *msg;
452         GError *err = NULL;
453         account = NULL;
454         msg = NULL;
455         folder = NULL;
456
457         astore = modest_runtime_get_account_store ();
458         
459         if (astore == NULL) {
460                 return NULL;
461         }
462
463         account = tny_account_store_find_account (TNY_ACCOUNT_STORE (astore),
464                                                   uri);
465         
466         if (account == NULL) {
467                 g_debug ("%s: tny_account_store_find_account() failed.\n", __FUNCTION__);
468                 return NULL;
469         }
470
471         g_debug ("%s: Found account.\n", __FUNCTION__);
472
473         if ( ! TNY_IS_STORE_ACCOUNT (account)) {
474                 goto out;
475         }
476
477         g_debug ("%s: Account is store account.\n", __FUNCTION__);
478
479         *ac_out = account;
480
481         folder = tny_store_account_find_folder (TNY_STORE_ACCOUNT (account),
482                                                 uri,
483                                                 &err);
484
485         if (folder == NULL) {
486                 g_debug ("%s: tny_store_account_find_folder() failed\naccount=%s, uri=%s.\n", __FUNCTION__, 
487                         tny_account_get_id (TNY_ACCOUNT(account)), uri);
488                 goto out;
489         }
490         g_debug ("%s: Found folder. (%s)\n",  __FUNCTION__, uri);
491         
492
493         msg = tny_folder_find_msg (folder, uri, &err);
494         
495         if (!msg) {
496                 g_debug ("%s: tny_folder_find_msg() failed for folder %s\n  with error=%s.\n",
497                          __FUNCTION__, tny_folder_get_id (folder), err->message);
498         }
499
500 out:
501         if (err)
502                 g_error_free (err);
503
504         if (account && !msg) {
505                 g_object_unref (account);
506                 *ac_out = NULL;
507         }
508
509         if (folder) {
510                 g_object_unref (folder);
511         }
512
513         return msg;
514 }
515
516 static gboolean
517 on_idle_open_message (gpointer user_data)
518 {
519         gdk_threads_enter ();
520         
521         ModestWindow *msg_view;
522         TnyMsg       *msg;
523         TnyAccount   *account;
524         TnyHeader    *header; 
525         const char   *msg_uid;
526         const char   *account_name;
527         char         *uri;
528        
529         uri = (char *) user_data;
530
531         g_debug ("%s: Trying to find msg by url: %s", __FUNCTION__, uri);       
532         msg = find_message_by_url (uri, &account);
533         g_free (uri);
534
535         if (msg == NULL) {
536                 g_debug ("  %s: message not found.", __FUNCTION__);
537                 gdk_threads_leave ();
538                 return FALSE;
539         }
540         g_debug ("  %s: Found message.", __FUNCTION__);
541
542         header = tny_msg_get_header (msg);
543         account_name = tny_account_get_name (account);
544         msg_uid = tny_header_get_uid (header);
545         
546         msg_view = modest_msg_view_window_new (msg,
547                                                account_name,
548                                                msg_uid);
549         /* TODO: does that leak the msg_view ?! */
550
551         gtk_widget_show_all (GTK_WIDGET (msg_view));
552
553         g_object_unref (header);
554         g_object_unref (account);
555         
556         gdk_threads_leave ();
557         
558         return FALSE; /* Do not call this callback again. */
559 }
560
561 static gint on_open_message(GArray * arguments, gpointer data, osso_rpc_t * retval)
562 {
563         if (arguments->len != MODEST_DEBUS_OPEN_MESSAGE_ARGS_COUNT)
564         return OSSO_ERROR;
565         
566     /* Use g_idle to context-switch into the application's thread: */
567
568     /* Get the arguments: */
569         osso_rpc_t val = g_array_index(arguments, osso_rpc_t, MODEST_DEBUS_OPEN_MESSAGE_ARG_URI);
570         gchar *uri = g_strdup (val.value.s);
571         
572         /* printf("  debug: to=%s\n", idle_data->to); */
573         g_idle_add(on_idle_open_message, (gpointer)uri);
574         
575         /* Note that we cannot report failures during sending, 
576          * because that would be asynchronous. */
577         return OSSO_OK;
578 }
579
580
581 static gint
582 on_delete_message (GArray *arguments, gpointer data, osso_rpc_t *retval)
583 {
584         TnyList      *headers;
585         TnyFolder    *folder;
586         TnyIterator  *iter; 
587         TnyHeader    *header;
588         TnyHeader    *msg_header;
589         TnyMsg       *msg;
590         TnyAccount   *account;
591         GError       *error;
592         osso_rpc_t    val;
593         const char   *uri;
594         const char   *uid;
595         gint          res;
596
597         if (arguments->len != MODEST_DEBUS_DELETE_MESSAGE_ARGS_COUNT) {
598                 return OSSO_ERROR;
599         }
600
601         val = g_array_index (arguments,
602                              osso_rpc_t,
603                              MODEST_DEBUS_DELETE_MESSAGE_ARG_URI);
604
605         uri = (const char *) val.value.s;
606
607         g_debug ("Searching message (delete message)");
608         
609         msg = find_message_by_url (uri, &account);
610
611         if (msg == NULL) {
612                 return OSSO_ERROR;
613         }
614
615         g_debug ("Found message");
616         
617         msg_header = tny_msg_get_header (msg);
618         uid = tny_header_get_uid (msg_header);
619         folder = tny_msg_get_folder (msg);
620
621
622         /* tny_msg_get_header () flaw:
623          * From tinythingy doc: You can't use the returned instance with the
624          * TnyFolder operations
625          *
626          * To get a header instance that will work with these folder methods,
627          * you can use tny_folder_get_headers.
628          *
629          * Ok, we will do so then. Sigh.
630          * */
631         headers = tny_simple_list_new ();
632
633         tny_folder_get_headers (folder, headers, TRUE, NULL);
634         iter = tny_list_create_iterator (headers);
635         header = NULL;
636
637         g_debug ("Searching header for msg in folder");
638         while (!tny_iterator_is_done (iter)) {
639                 const char *cur_id;
640
641                 header = TNY_HEADER (tny_iterator_get_current (iter));
642                 cur_id = tny_header_get_uid (header);
643                 
644                 if (cur_id && uid && g_str_equal (cur_id, uid)) {
645                         g_debug ("Found correspoding header from folder");
646                         break;
647                 }
648
649                 header = NULL;
650                 g_object_unref (header);
651                 tny_iterator_next (iter);
652         }
653
654         g_object_unref (iter);
655         g_object_unref (headers);
656         
657         g_object_unref (msg_header);
658         g_object_unref (msg);
659
660         if (header == NULL) {
661                 g_object_unref (folder);
662                 return OSSO_ERROR;
663         }
664
665
666         error = NULL;
667         res = OSSO_OK;
668         tny_folder_remove_msg (folder, header, &error);
669
670         if (error != NULL) {
671                 res = OSSO_ERROR;
672                 g_error_free (error);
673         }
674
675         g_object_unref (folder);
676         return res;
677 }
678
679 static gboolean
680 on_idle_send_receive(gpointer user_data)
681 {
682         gdk_threads_enter ();
683         ModestWindow *win;
684
685         /* Pick the main window if it exists */
686         win = modest_window_mgr_get_main_window (modest_runtime_get_window_mgr ());
687
688         /* Send & receive all if "Update automatically" is set */
689         /* TODO: check the auto-update parameter in the configuration */
690         modest_ui_actions_do_send_receive_all (win);
691         
692         gdk_threads_leave ();
693         
694         return FALSE; /* Do not call this callback again. */
695 }
696
697 static gint on_send_receive(GArray * arguments, gpointer data, osso_rpc_t * retval)
698 {       
699     /* Use g_idle to context-switch into the application's thread: */
700
701     /* This method has no arguments. */
702         
703         /* printf("  debug: to=%s\n", idle_data->to); */
704         g_idle_add(on_idle_send_receive, NULL);
705         
706         /* Note that we cannot report failures during send/receive, 
707          * because that would be asynchronous. */
708         return OSSO_OK;
709 }
710
711 static gboolean
712 on_idle_open_default_inbox(gpointer user_data)
713 {
714         gdk_threads_enter ();
715         
716         ModestWindow *win = 
717                 modest_window_mgr_get_main_window (modest_runtime_get_window_mgr ());
718
719         /* Get the folder view */
720         GtkWidget *folder_view = modest_main_window_get_child_widget (MODEST_MAIN_WINDOW (win),
721                                                            MODEST_WIDGET_TYPE_FOLDER_VIEW);
722         modest_folder_view_select_first_inbox_or_local (
723                 MODEST_FOLDER_VIEW (folder_view));
724         
725         gdk_threads_leave ();
726         
727         return FALSE; /* Do not call this callback again. */
728 }
729
730 static gint on_open_default_inbox(GArray * arguments, gpointer data, osso_rpc_t * retval)
731 {
732     /* Use g_idle to context-switch into the application's thread: */
733
734     /* This method has no arguments. */
735         
736         g_idle_add(on_idle_open_default_inbox, NULL);
737         
738         /* Note that we cannot report failures during send/receive, 
739          * because that would be asynchronous. */
740         return OSSO_OK;
741 }
742                       
743 /* Callback for normal D-BUS messages */
744 gint modest_dbus_req_handler(const gchar * interface, const gchar * method,
745                       GArray * arguments, gpointer data,
746                       osso_rpc_t * retval)
747 {
748         
749         g_debug ("debug: %s\n", __FUNCTION__);
750         g_debug ("debug: %s: method received: %s\n", __FUNCTION__, method);
751         
752         if (g_ascii_strcasecmp(method, MODEST_DBUS_METHOD_MAIL_TO) == 0) {
753                 return on_mail_to (arguments, data, retval);
754         } else if (g_ascii_strcasecmp(method, MODEST_DBUS_METHOD_OPEN_MESSAGE) == 0) {
755                 return on_open_message (arguments, data, retval);
756         } else if (g_ascii_strcasecmp(method, MODEST_DBUS_METHOD_SEND_RECEIVE) == 0) {
757                 return on_send_receive (arguments, data, retval);
758         } else if (g_ascii_strcasecmp(method, MODEST_DBUS_METHOD_COMPOSE_MAIL) == 0) {
759                 return on_compose_mail (arguments, data, retval);
760         } else if (g_ascii_strcasecmp(method, MODEST_DBUS_METHOD_DELETE_MESSAGE) == 0) {
761                 return on_delete_message (arguments,data, retval);
762         } else if (g_ascii_strcasecmp(method, MODEST_DBUS_METHOD_OPEN_DEFAULT_INBOX) == 0) {
763                 return on_open_default_inbox (arguments, data, retval);
764         }
765         else { 
766                 /* We need to return INVALID here so
767                  * libosso will return DBUS_HANDLER_RESULT_NOT_YET_HANDLED,
768                  * so that our modest_dbus_req_filter will then be tried instead.
769                  * */
770                 return OSSO_INVALID;
771         }
772 }
773                                          
774 /* A complex D-Bus type (like a struct),
775  * used to return various information about a search hit.
776  */
777 #define SEARCH_HIT_DBUS_TYPE \
778         DBUS_STRUCT_BEGIN_CHAR_AS_STRING \
779         DBUS_TYPE_STRING_AS_STRING /* msgid */ \
780         DBUS_TYPE_STRING_AS_STRING /* subject */ \
781         DBUS_TYPE_STRING_AS_STRING /* folder */ \
782         DBUS_TYPE_STRING_AS_STRING /* sender */ \
783         DBUS_TYPE_UINT64_AS_STRING /* msize */ \
784         DBUS_TYPE_BOOLEAN_AS_STRING /* has_attachment */ \
785         DBUS_TYPE_BOOLEAN_AS_STRING /* is_unread */ \
786         DBUS_TYPE_INT64_AS_STRING /* timestamp */ \
787         DBUS_STRUCT_END_CHAR_AS_STRING
788
789 static DBusMessage *
790 search_result_to_message (DBusMessage *reply,
791                            GList       *hits)
792 {
793         DBusMessageIter iter;
794         DBusMessageIter array_iter;
795         GList          *hit_iter;
796
797         dbus_message_iter_init_append (reply, &iter); 
798         dbus_message_iter_open_container (&iter,
799                                           DBUS_TYPE_ARRAY,
800                                           SEARCH_HIT_DBUS_TYPE,
801                                           &array_iter); 
802
803         for (hit_iter = hits; hit_iter; hit_iter = hit_iter->next) {
804                 DBusMessageIter  struct_iter;
805                 ModestSearchHit *hit;
806                 char            *msg_url;
807                 const char      *subject;
808                 const char      *folder;
809                 const char      *sender;
810                 guint64          size;
811                 gboolean         has_attachment;
812                 gboolean         is_unread;
813                 gint64           ts;
814
815                 hit = (ModestSearchHit *) hit_iter->data;
816
817                 msg_url = hit->msgid;
818                 subject = hit->subject;
819                 folder  = hit->folder;
820                 sender  = hit->sender;
821                 size           = hit->msize;
822                 has_attachment = hit->has_attachment;
823                 is_unread      = hit->is_unread;
824                 ts             = hit->timestamp;
825
826                 g_debug ("DEBUG: %s: Adding hit: %s", __FUNCTION__, msg_url);   
827                 
828                 dbus_message_iter_open_container (&array_iter,
829                                                   DBUS_TYPE_STRUCT,
830                                                   NULL,
831                                                   &struct_iter);
832
833                 dbus_message_iter_append_basic (&struct_iter,
834                                                 DBUS_TYPE_STRING,
835                                                 &msg_url);
836
837                 dbus_message_iter_append_basic (&struct_iter,
838                                                 DBUS_TYPE_STRING,
839                                                 &subject); 
840
841                 dbus_message_iter_append_basic (&struct_iter,
842                                                 DBUS_TYPE_STRING,
843                                                 &folder);
844
845                 dbus_message_iter_append_basic (&struct_iter,
846                                                 DBUS_TYPE_STRING,
847                                                 &sender);
848
849                 dbus_message_iter_append_basic (&struct_iter,
850                                                 DBUS_TYPE_UINT64,
851                                                 &size);
852
853                 dbus_message_iter_append_basic (&struct_iter,
854                                                 DBUS_TYPE_BOOLEAN,
855                                                 &has_attachment);
856
857                 dbus_message_iter_append_basic (&struct_iter,
858                                                 DBUS_TYPE_BOOLEAN,
859                                                 &is_unread);
860                 
861                 dbus_message_iter_append_basic (&struct_iter,
862                                                 DBUS_TYPE_INT64,
863                                                 &ts);
864
865                 dbus_message_iter_close_container (&array_iter,
866                                                    &struct_iter); 
867
868                 g_free (hit->msgid);
869                 g_free (hit->subject);
870                 g_free (hit->folder);
871                 g_free (hit->sender);
872
873                 g_slice_free (ModestSearchHit, hit);
874         }
875
876         dbus_message_iter_close_container (&iter, &array_iter);
877
878         return reply;
879 }
880
881
882 static void
883 on_dbus_method_search (DBusConnection *con, DBusMessage *message)
884 {
885         ModestDBusSearchFlags dbus_flags;
886         DBusMessage  *reply = NULL;
887         dbus_bool_t  res;
888         dbus_int64_t sd_v;
889         dbus_int64_t ed_v;
890         dbus_int32_t flags_v;
891         dbus_uint32_t size_v;
892         const char *folder;
893         const char *query;
894         time_t start_date;
895         time_t end_date;
896         GList *hits;
897
898         DBusError error;
899         dbus_error_init (&error);
900
901         sd_v = ed_v = 0;
902         flags_v = 0;
903
904         res = dbus_message_get_args (message,
905                                      &error,
906                                      DBUS_TYPE_STRING, &query,
907                                      DBUS_TYPE_STRING, &folder, /* e.g. "INBOX/drafts": TODO: Use both an ID and a display name. */
908                                      DBUS_TYPE_INT64, &sd_v,
909                                      DBUS_TYPE_INT64, &ed_v,
910                                      DBUS_TYPE_INT32, &flags_v,
911                                      DBUS_TYPE_UINT32, &size_v,
912                                      DBUS_TYPE_INVALID);
913         
914         dbus_flags = (ModestDBusSearchFlags) flags_v;
915         start_date = (time_t) sd_v;
916         end_date = (time_t) ed_v;
917
918         ModestSearch search;
919         memset (&search, 0, sizeof (search));
920         
921         /* Remember what folder we are searching in:
922          *
923          * Note that we don't copy the strings, 
924          * because this struct will only be used for the lifetime of this function.
925          */
926         search.folder = folder;
927
928    /* Remember the text to search for: */
929 #ifdef MODEST_HAVE_OGS
930         search.query  = query;
931 #endif
932
933         /* Other criteria: */
934         search.before = start_date;
935         search.after  = end_date;
936         search.flags  = 0;
937
938         /* Text to serach for in various parts of the message: */
939         if (dbus_flags & MODEST_DBUS_SEARCH_SUBJECT) {
940                 search.flags |= MODEST_SEARCH_SUBJECT;
941                 search.subject = query;
942         }
943
944         if (dbus_flags & MODEST_DBUS_SEARCH_SENDER) {
945                 search.flags |=  MODEST_SEARCH_SENDER;
946                 search.from = query;
947         }
948
949         if (dbus_flags & MODEST_DBUS_SEARCH_RECIPIENT) {
950                 search.flags |= MODEST_SEARCH_RECIPIENT; 
951                 search.recipient = query;
952         }
953
954         if (dbus_flags & MODEST_DBUS_SEARCH_BODY) {
955                 search.flags |=  MODEST_SEARCH_BODY; 
956                 search.body = query;
957         }
958
959         if (sd_v > 0) {
960                 search.flags |= MODEST_SEARCH_BEFORE;
961                 search.before = start_date;
962         }
963
964         if (ed_v > 0) {
965                 search.flags |= MODEST_SEARCH_AFTER;
966                 search.after = end_date;
967         }
968
969         if (size_v > 0) {
970                 search.flags |= MODEST_SEARCH_SIZE;
971                 search.minsize = size_v;
972         }
973
974 #ifdef MODEST_HAVE_OGS
975         search.flags |= MODEST_SEARCH_USE_OGS;
976         g_debug ("%s: Starting search for %s", __FUNCTION__, search.query);
977 #endif
978
979         /* Note that this currently gets folders and messages from the servers, 
980          * which can take a long time. libmodest_dbus_client_search() can timeout, 
981          * reporting no results, if this takes a long time: */
982         hits = modest_search_all_accounts (&search);
983
984         reply = dbus_message_new_method_return (message);
985
986         search_result_to_message (reply, hits);
987
988         if (reply == NULL) {
989                 g_warning ("%s: Could not create reply.", __FUNCTION__);
990         }
991
992         if (reply) {
993                 dbus_uint32_t serial = 0;
994                 dbus_connection_send (con, reply, &serial);
995         dbus_connection_flush (con);
996         dbus_message_unref (reply);
997         }
998
999         g_list_free (hits);
1000 }
1001
1002
1003 /* A complex D-Bus type (like a struct),
1004  * used to return various information about a folder.
1005  */
1006 #define GET_FOLDERS_RESULT_DBUS_TYPE \
1007         DBUS_STRUCT_BEGIN_CHAR_AS_STRING \
1008         DBUS_TYPE_STRING_AS_STRING /* Folder Name */ \
1009         DBUS_TYPE_STRING_AS_STRING /* Folder URI */ \
1010         DBUS_STRUCT_END_CHAR_AS_STRING
1011
1012 static DBusMessage *
1013 get_folders_result_to_message (DBusMessage *reply,
1014                            GList *folder_ids)
1015 {
1016         DBusMessageIter iter;   
1017         dbus_message_iter_init_append (reply, &iter); 
1018         
1019         DBusMessageIter array_iter;
1020         dbus_message_iter_open_container (&iter,
1021                                           DBUS_TYPE_ARRAY,
1022                                           GET_FOLDERS_RESULT_DBUS_TYPE,
1023                                           &array_iter); 
1024
1025         GList *list_iter = folder_ids;
1026         for (list_iter = folder_ids; list_iter; list_iter = list_iter->next) {
1027                 
1028                 const gchar *folder_name = (const gchar*)list_iter->data;
1029                 if (folder_name) {
1030                         /* g_debug ("DEBUG: %s: Adding folder: %s", __FUNCTION__, folder_name); */
1031                         
1032                         DBusMessageIter struct_iter;
1033                         dbus_message_iter_open_container (&array_iter,
1034                                                           DBUS_TYPE_STRUCT,
1035                                                           NULL,
1036                                                           &struct_iter);
1037         
1038                         /* name: */
1039                         dbus_message_iter_append_basic (&struct_iter,
1040                                                         DBUS_TYPE_STRING,
1041                                                         &folder_name); /* The string will be copied. */
1042                                                         
1043                         /* URI: This is maybe not needed by osso-global-search: */
1044                         const gchar *folder_uri = "TODO:unimplemented";
1045                         dbus_message_iter_append_basic (&struct_iter,
1046                                                         DBUS_TYPE_STRING,
1047                                                         &folder_uri); /* The string will be copied. */
1048         
1049                         dbus_message_iter_close_container (&array_iter,
1050                                                            &struct_iter); 
1051                 }
1052         }
1053
1054         dbus_message_iter_close_container (&iter, &array_iter);
1055
1056         return reply;
1057 }
1058
1059 static void
1060 add_single_folder_to_list (TnyFolder *folder, GList** list)
1061 {
1062         if (!folder)
1063                 return;
1064                 
1065         /* Add this folder to the list: */
1066         /*
1067         const gchar * folder_name = tny_folder_get_name (folder);
1068         if (folder_name)
1069                 *list = g_list_append(*list, g_strdup (folder_name));
1070         else {
1071         */
1072                 /* osso-global-search only uses one string,
1073                  * so ID is the only thing that could possibly identify a folder.
1074                  * TODO: osso-global search should probably be changed to 
1075                  * take an ID and a Name.
1076                  */
1077                 const gchar * id =  tny_folder_get_id (folder);
1078                 if (id && strlen(id))
1079                         *list = g_list_append(*list, g_strdup (id));
1080                 /*
1081                 else {
1082                         g_warning ("DEBUG: %s: folder has no name or ID.\n", __FUNCTION__);     
1083                 }
1084                 
1085         }
1086         */
1087 }
1088
1089 static void
1090 add_folders_to_list (TnyFolderStore *folder_store, GList** list)
1091 {
1092         if (!folder_store)
1093                 return;
1094         
1095         /* Add this folder to the list: */
1096         if (TNY_IS_FOLDER (folder_store)) {
1097                 add_single_folder_to_list (TNY_FOLDER (folder_store), list);
1098         }       
1099                 
1100         /* Recurse into child folders: */
1101                 
1102         /* Get the folders list: */
1103         /*
1104         TnyFolderStoreQuery *query = tny_folder_store_query_new ();
1105         tny_folder_store_query_add_item (query, NULL, 
1106                 TNY_FOLDER_STORE_QUERY_OPTION_SUBSCRIBED);
1107         */
1108         TnyList *all_folders = tny_simple_list_new ();
1109         tny_folder_store_get_folders (folder_store,
1110                                       all_folders,
1111                                       NULL /* query */,
1112                                       NULL /* error */);
1113
1114         TnyIterator *iter = tny_list_create_iterator (all_folders);
1115         while (!tny_iterator_is_done (iter)) {
1116                 
1117                 /* Do not recurse, because the osso-global-search UI specification 
1118                  * does not seem to want the sub-folders, though that spec seems to 
1119                  * be generally unsuitable for Modest.
1120                  */
1121                 TnyFolder *folder = TNY_FOLDER (tny_iterator_get_current (iter));
1122                 add_single_folder_to_list (TNY_FOLDER (folder), list);
1123                  
1124                 #if 0
1125                 if (TNY_IS_FOLDER_STORE (folder))
1126                         add_folders_to_list (TNY_FOLDER_STORE (folder), list);
1127                 else {
1128                         add_single_folder_to_list (TNY_FOLDER (folder), list);
1129                 }
1130                 #endif
1131                 
1132                 tny_iterator_next (iter);
1133         }
1134         g_object_unref (G_OBJECT (iter));
1135 }
1136
1137 static void
1138 on_dbus_method_get_folders (DBusConnection *con, DBusMessage *message)
1139 {
1140         DBusMessage  *reply = NULL;
1141         
1142
1143         /* Get the TnyStoreAccount so we can get the folders: */
1144         ModestAccountMgr *account_mgr = modest_runtime_get_account_mgr();
1145         gchar *account_name = modest_account_mgr_get_default_account (account_mgr);
1146         if (!account_name) {
1147                 g_printerr ("modest: no account found\n");
1148         }
1149         
1150         TnyAccount *account = NULL;
1151         if (account_mgr) {
1152                 account = modest_tny_account_store_get_server_account (
1153                         modest_runtime_get_account_store(), account_name, 
1154                         TNY_ACCOUNT_TYPE_STORE);
1155         }
1156         
1157         if (!account) {
1158                 g_printerr ("modest: failed to get tny account folder'%s'\n", account_name);
1159         } 
1160                 
1161         printf("DEBUG: %s: Getting folders for account name=%s\n", __FUNCTION__, account_name);
1162         g_free (account_name);
1163         account_name = NULL;
1164         
1165         GList *folder_names = NULL;
1166         add_folders_to_list (TNY_FOLDER_STORE (account), &folder_names);
1167
1168         g_object_unref (account);
1169         account = NULL;
1170         
1171         
1172         /* Also add the folders from the local folders account,
1173          * because they are (currently) used with all accounts:
1174          * TODO: This is not working. It seems to get only the Merged Folder (with an ID of "" (not NULL)).
1175          */
1176         TnyAccount *account_local = 
1177                 modest_tny_account_store_get_local_folders_account (
1178                         TNY_ACCOUNT_STORE (modest_runtime_get_account_store()));
1179         add_folders_to_list (TNY_FOLDER_STORE (account_local), &folder_names);
1180
1181         g_object_unref (account_local);
1182         account_local = NULL;
1183
1184
1185         /* Put the result in a DBus reply: */
1186         reply = dbus_message_new_method_return (message);
1187
1188         get_folders_result_to_message (reply, folder_names);
1189
1190         if (reply == NULL) {
1191                 g_warning ("%s: Could not create reply.", __FUNCTION__);
1192         }
1193
1194         if (reply) {
1195                 dbus_uint32_t serial = 0;
1196                 dbus_connection_send (con, reply, &serial);
1197         dbus_connection_flush (con);
1198         dbus_message_unref (reply);
1199         }
1200
1201         g_list_foreach (folder_names, (GFunc)g_free, NULL);
1202         g_list_free (folder_names);
1203 }
1204
1205
1206 /** This D-Bus handler is used when the main osso-rpc 
1207  * D-Bus handler has not handled something.
1208  * We use this for D-Bus methods that need to use more complex types 
1209  * than osso-rpc supports.
1210  */
1211 DBusHandlerResult
1212 modest_dbus_req_filter (DBusConnection *con,
1213                         DBusMessage    *message,
1214                         void           *user_data)
1215 {
1216         gboolean handled = FALSE;
1217
1218         if (dbus_message_is_method_call (message,
1219                                          MODEST_DBUS_IFACE,
1220                                          MODEST_DBUS_METHOD_SEARCH)) {
1221                 on_dbus_method_search (con, message);
1222                 handled = TRUE;                         
1223         } else if (dbus_message_is_method_call (message,
1224                                          MODEST_DBUS_IFACE,
1225                                          MODEST_DBUS_METHOD_GET_FOLDERS)) {
1226                 on_dbus_method_get_folders (con, message);
1227                 handled = TRUE;                         
1228         }
1229         
1230         return (handled ? 
1231                 DBUS_HANDLER_RESULT_HANDLED :
1232                 DBUS_HANDLER_RESULT_NOT_YET_HANDLED);
1233 }
1234
1235
1236 void
1237 modest_osso_cb_hw_state_handler(osso_hw_state_t *state, gpointer data)
1238 {
1239         /* TODO? */
1240     /* printf("%s()\n", __PRETTY_FUNCTION__); */
1241
1242     if(state->system_inactivity_ind)
1243     {
1244     }
1245     else if(state->save_unsaved_data_ind)
1246     {
1247     }
1248     else
1249     {
1250     
1251     }
1252
1253     /* printf("debug: %s(): return\n", __PRETTY_FUNCTION__); */
1254 }