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