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