Fixes NB#113192, add mailer addresses to the address book after sending
[modest] / src / hildon2 / modest-address-book.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 /* modest-address-book.c */
31
32 #include <config.h>
33 #include <glib/gi18n.h>
34 #include <modest-address-book.h>
35 #include <modest-text-utils.h>
36 #include <libebook/e-book.h>
37 #include <libebook/e-book-view.h>
38 #include <libebook/e-vcard.h>
39 #include "modest-hildon-includes.h"
40 #include <libosso-abook/osso-abook.h>
41 #include "modest-platform.h"
42 #include "modest-runtime.h"
43 #include "widgets/modest-window-mgr.h"
44 #include "widgets/modest-ui-constants.h"
45 #include <string.h>
46 #include <gtk/gtksizegroup.h>
47 #include <gtk/gtkbox.h>
48 #include <gtk/gtklabel.h>
49 #include <gtk/gtkcellrenderertext.h>
50 #include <gtk/gtktreeselection.h>
51 #include <gtk/gtkentry.h>
52 #include <modest-maemo-utils.h>
53
54 static OssoABookContactModel *contact_model =  NULL;
55 static EBook *book = NULL;
56 static EBookView * book_view = NULL;
57
58 static GSList *get_recipients_for_given_contact (EContact * contact, gboolean *canceled);
59 static void commit_contact(EContact * contact, gboolean is_new);
60 static gchar *get_email_addr_from_user(const gchar * given_name, gboolean *canceled);
61 static gchar *ui_get_formatted_email_id(gchar * current_given_name,
62                                         gchar * current_sur_name, gchar * current_email_id);
63 static gchar *run_add_email_addr_to_contact_dlg(const gchar * contact_name, gboolean *canceled);
64 static GSList *select_email_addrs_for_contact(GList * email_addr_list);
65 static gboolean resolve_address (const gchar *address, GSList **resolved_addresses, GSList **contact_id, gboolean *canceled);
66 static gchar *unquote_string (const gchar *str);
67
68
69 static void
70 unref_gobject (GObject *obj)
71 {
72         if (obj)
73                 g_object_unref (obj);
74 }
75         
76
77 static void
78 get_book_view_cb (EBook *book, EBookStatus status, EBookView *bookview, gpointer data)
79 {
80         if (status != E_BOOK_ERROR_OK) {
81                 g_object_unref (book);
82                 book = NULL;
83                 return;
84         }
85         book_view = bookview;
86
87         if (contact_model)
88 #if MODEST_ABOOK_API < 4
89                 osso_abook_tree_model_set_book_view (OSSO_ABOOK_TREE_MODEL (contact_model),
90                                                      book_view);
91 #else /* MODEST_ABOOK_API < 4 */
92                 osso_abook_list_store_set_book_view (OSSO_ABOOK_LIST_STORE (contact_model),
93                                                      book_view);
94 #endif /* MODEST_ABOOK_API < 4 */
95
96         e_book_view_start (book_view);
97 }
98
99 static void
100 book_open_cb (EBook *view, EBookStatus status, gpointer data)
101 {
102         EBookQuery *query = NULL;
103
104         if (status != E_BOOK_ERROR_OK) {
105                 g_object_unref (book);
106                 book = NULL;
107                 return;
108         }
109         query = e_book_query_any_field_contains ("");
110         e_book_async_get_book_view (book, query, NULL, -1, get_book_view_cb, NULL);
111         e_book_query_unref (query);
112 }
113
114 static gboolean 
115 open_addressbook ()
116 {
117         book = e_book_new_system_addressbook (NULL);
118         if (!book)
119                 return FALSE;
120
121         if (e_book_async_open (book, FALSE, book_open_cb, NULL) != E_BOOK_ERROR_OK)
122                 return FALSE;
123
124         return TRUE; /* FIXME */        
125 }
126
127 typedef struct _OpenAddressbookSyncInfo {
128         gboolean retval;
129         GMainLoop *mainloop;
130 } OpenAddressbookSyncInfo;
131
132 static void
133 get_book_view_sync_cb (EBook *book, EBookStatus status, EBookView *bookview, gpointer data)
134 {
135         OpenAddressbookSyncInfo *info = (OpenAddressbookSyncInfo *) data;
136
137         if (status != E_BOOK_ERROR_OK) {
138                 g_object_unref (book);
139                 book = NULL;
140                 info->retval = FALSE;
141                 g_main_loop_quit (info->mainloop);
142                 return;
143         }
144         book_view = bookview;
145
146         if (contact_model)
147 #if MODEST_ABOOK_API < 4
148                 osso_abook_tree_model_set_book_view (OSSO_ABOOK_TREE_MODEL (contact_model),
149                                                      book_view);
150 #else /* MODEST_ABOOK_API < 4 */
151                 osso_abook_list_store_set_book_view (OSSO_ABOOK_LIST_STORE (contact_model),
152                                                      book_view);
153 #endif /* MODEST_ABOOK_API < 4 */
154
155         e_book_view_start (book_view);
156         info->retval = TRUE;
157         g_main_loop_quit (info->mainloop);
158 }
159
160 static void
161 book_open_sync_cb (EBook *view, EBookStatus status, gpointer data)
162 {
163         EBookQuery *query = NULL;
164         OpenAddressbookSyncInfo *info = (OpenAddressbookSyncInfo *) data;
165
166         if (status != E_BOOK_ERROR_OK) {
167                 g_object_unref (book);
168                 book = NULL;
169                 info->retval = FALSE;
170                 g_main_loop_quit (info->mainloop);
171                 return;
172         }
173         query = e_book_query_any_field_contains ("");
174         e_book_async_get_book_view (book, query, NULL, -1, get_book_view_sync_cb, info);
175         e_book_query_unref (query);
176 }
177
178 static gboolean
179 open_addressbook_sync ()
180 {
181         OpenAddressbookSyncInfo *info;
182         gboolean retval;
183
184         book = e_book_new_system_addressbook (NULL);
185         if (!book)
186                 return FALSE;
187
188         info = g_slice_new (OpenAddressbookSyncInfo);
189         info->mainloop = g_main_loop_new (NULL, FALSE);
190         info->retval = FALSE;
191         if (e_book_async_open (book, FALSE, book_open_sync_cb, info) == E_BOOK_ERROR_OK) {
192                 GDK_THREADS_LEAVE ();
193                 g_main_loop_run (info->mainloop);
194                 GDK_THREADS_ENTER ();
195         }
196         retval = info->retval;
197         g_main_loop_unref (info->mainloop);
198         g_slice_free (OpenAddressbookSyncInfo, info);
199         /* Make it launch a main loop */
200         return e_book_open (book, FALSE, NULL);
201 }
202
203 void
204 modest_address_book_add_address (const gchar *address)
205 {
206         GtkWidget *dialog = NULL;
207         gchar *email_address;
208         EVCardAttribute *attribute;
209
210         if (!open_addressbook ()) {
211                 return;
212         }
213
214         email_address = modest_text_utils_get_email_address (address);
215         
216         attribute = e_vcard_attribute_new (NULL, EVC_EMAIL);
217         e_vcard_attribute_add_value (attribute, email_address);
218         dialog = osso_abook_temporary_contact_dialog_new (NULL, book, attribute, NULL);
219         gtk_dialog_run (GTK_DIALOG (dialog));
220
221         gtk_widget_destroy (dialog);
222
223         e_vcard_attribute_free (attribute);
224         g_free (email_address);
225
226 }
227
228 void
229 modest_address_book_select_addresses (ModestRecptEditor *recpt_editor)
230 {
231 #if MODEST_ABOOK_API < 4
232         GtkWidget *contact_view = NULL;
233         GtkWidget *contact_dialog;
234         GtkWidget *toplevel;
235 #else /* MODEST_ABOOK_API < 4 */
236         GtkWidget *contact_chooser = NULL;
237 #endif /* MODEST_ABOOK_API < 4 */
238
239         GList *contacts_list = NULL;
240         GSList *email_addrs_per_contact = NULL;
241         gchar *econtact_id;
242         gboolean focus_recpt_editor = FALSE;
243
244         g_return_if_fail (MODEST_IS_RECPT_EDITOR (recpt_editor));
245
246 #if MODEST_ABOOK_API < 4
247         if (!open_addressbook ()) {
248                 if (contact_model) {
249                         g_object_unref (contact_model);
250                         contact_model = NULL;
251                 }
252                 return;
253         }
254         contact_model = osso_abook_contact_model_new ();
255
256         contact_view = osso_abook_contact_selector_new_basic (contact_model);
257         osso_abook_contact_selector_set_minimum_selection (OSSO_ABOOK_CONTACT_SELECTOR (contact_view), 1);
258
259         contact_dialog = osso_abook_select_dialog_new (OSSO_ABOOK_TREE_VIEW (contact_view));
260         toplevel = gtk_widget_get_toplevel (GTK_WIDGET (recpt_editor));
261         modest_window_mgr_set_modal (modest_runtime_get_window_mgr (), GTK_WINDOW (contact_dialog), GTK_WINDOW (toplevel));
262
263         gtk_widget_show (contact_dialog);
264
265         if (gtk_dialog_run (GTK_DIALOG (contact_dialog)) == GTK_RESPONSE_OK) {
266                 contacts_list = 
267                         osso_abook_contact_selector_get_extended_selection (OSSO_ABOOK_CONTACT_SELECTOR
268                                                                              (contact_view));
269         }
270 #else /* MODEST_ABOOK_API < 4 */
271         /* TODO: figure out how to make the contact chooser modal */
272         contact_chooser = osso_abook_contact_chooser_new_with_capabilities (NULL,
273                                                                             _AB("addr_ti_dia_select_contacts"),
274                                                                             OSSO_ABOOK_CAPS_EMAIL, 
275                                                                             OSSO_ABOOK_CONTACT_ORDER_NAME);
276         /* Enable multiselection */
277         osso_abook_contact_chooser_set_maximum_selection (OSSO_ABOOK_CONTACT_CHOOSER (contact_chooser),
278                                                           G_MAXUINT);
279
280         if (gtk_dialog_run (GTK_DIALOG (contact_chooser)) == GTK_RESPONSE_OK)
281                 contacts_list = osso_abook_contact_chooser_get_selection (OSSO_ABOOK_CONTACT_CHOOSER (contact_chooser));
282         gtk_widget_destroy (contact_chooser);
283 #endif
284
285         if (contacts_list) {
286                 GList *node;
287
288                 for (node = contacts_list; node != NULL; node = g_list_next (node)) {
289                         EContact *contact = (EContact *) node->data;
290                         gboolean canceled;
291
292                         email_addrs_per_contact = get_recipients_for_given_contact (contact, &canceled);
293                         if (email_addrs_per_contact) {
294                                 econtact_id = (gchar *) e_contact_get_const (contact, E_CONTACT_UID);
295                                 modest_recpt_editor_add_resolved_recipient (MODEST_RECPT_EDITOR (recpt_editor), 
296                                                                             email_addrs_per_contact, econtact_id);
297                                 g_slist_foreach (email_addrs_per_contact, (GFunc) g_free, NULL);
298                                 g_slist_free (email_addrs_per_contact);
299                                 email_addrs_per_contact = NULL;
300                                 focus_recpt_editor = TRUE;
301                         }
302                 }
303                 g_list_free (contacts_list);
304         }
305
306 #if MODEST_ABOOK_API < 4
307         if (contact_model) {
308                 g_object_unref (contact_model);
309                 contact_model = NULL;
310         }
311
312         gtk_widget_destroy (contact_dialog);
313 #endif
314
315         if (focus_recpt_editor)
316                 modest_recpt_editor_grab_focus (MODEST_RECPT_EDITOR (recpt_editor));
317
318 }
319
320 /**
321  * This function returns the resolved recipients for a given EContact.
322  * If no e-mail address is defined, it launches 'Add e-mail address to contact'
323  * dialog to obtain one. If multiple e-mail addresses are found, it launches
324  * 'Select e-mail address' dialog to allow user to select one or more e-mail
325  * addresses for that contact.
326  *
327  * @param  Contact of type #EContact
328  * @return List of resolved recipient strings, to be freed by calling function.
329  */
330 static GSList *
331 get_recipients_for_given_contact (EContact * contact,
332                                   gboolean *canceled)
333 {
334         gchar *givenname = NULL;
335         gchar *familyname = NULL;
336         gchar *nickname = NULL;
337         gchar *emailid = NULL;
338         const gchar *display_name = NULL;
339         GList *list = NULL;
340         gchar *formatted_string = NULL;
341         gboolean email_not_present = FALSE;
342         GSList *formattedlist = NULL, *selected_email_addr_list = NULL, *node = NULL;
343
344         if (!contact) {
345                 return NULL;
346         }
347
348         givenname = (gchar *) e_contact_get_const(contact, E_CONTACT_GIVEN_NAME);
349         familyname = (gchar *) e_contact_get_const(contact, E_CONTACT_FAMILY_NAME);
350         nickname = (gchar *) e_contact_get_const(contact, E_CONTACT_NICKNAME);
351         if (!nickname)
352                 nickname = "";
353         list = (GList *) e_contact_get(contact, E_CONTACT_EMAIL);
354
355         if (!list) {
356                 email_not_present = TRUE;
357         }
358
359         if (list && g_list_length(list) == 1) {
360                 if (list->data == NULL || g_utf8_strlen(list->data, -1) == 0) {
361                         email_not_present = TRUE;
362                 } else {
363                         emailid = g_strstrip(g_strdup(list->data));
364                         if (g_utf8_strlen(emailid, -1) == 0) {
365                                 g_free(emailid);
366                                 email_not_present = TRUE;
367                         }
368                 }
369         }
370
371         /*Launch the 'Add e-mail addr to contact' dialog if required */
372         if (email_not_present) {
373 #if MODEST_ABOOK_API < 4
374                 display_name = osso_abook_contact_get_display_name(contact);
375 #else
376                 OssoABookContact *abook_contact;
377
378                 abook_contact = osso_abook_contact_new_from_template (contact);
379                 display_name = osso_abook_contact_get_display_name(abook_contact);
380 #endif
381
382                 emailid = get_email_addr_from_user(display_name, canceled);
383                 if (emailid) {
384                         e_contact_set(contact, E_CONTACT_EMAIL_1, emailid);
385                         commit_contact(contact, FALSE);
386                 }
387 #if MODEST_ABOOK_API >= 4
388                 g_object_unref (abook_contact);
389 #endif
390         }
391
392         if (emailid) {
393                 if (givenname || familyname)
394                         formatted_string =
395                             ui_get_formatted_email_id(givenname, familyname, emailid);
396                 else
397                         formatted_string = g_strdup(emailid);
398                 formattedlist = g_slist_append(formattedlist, formatted_string);
399                 g_free(emailid);
400         }
401
402         /*Launch the 'Select e-mail address' dialog if required */
403         if (g_list_length(list) > 1) {
404                 selected_email_addr_list = select_email_addrs_for_contact(list);
405                 for (node = selected_email_addr_list; node != NULL; node = node->next) {
406                         if (givenname || familyname)
407                                 formatted_string =
408                                     ui_get_formatted_email_id(givenname, familyname, node->data);
409                         else
410                                 formatted_string = g_strdup(node->data);
411                         formattedlist = g_slist_append(formattedlist, formatted_string);
412                 }
413                 if (selected_email_addr_list) {
414                         g_slist_foreach(selected_email_addr_list, (GFunc) g_free, NULL);
415                         g_slist_free(selected_email_addr_list);
416                 }
417         }
418
419         if (list) {
420                 g_list_foreach(list, (GFunc) g_free, NULL);
421                 g_list_free(list);
422         }
423
424         return formattedlist;
425 }
426
427 /**
428  * This is a helper function to commit a EContact to Address_Book application.
429  *
430  * @param  contact  Contact of type #EContact
431  * @return void
432  */
433 static void 
434 commit_contact(EContact * contact, gboolean is_new)
435 {
436         g_return_if_fail (contact);
437         g_return_if_fail (book);
438
439         if (!contact || !book)
440                 return;
441
442 #if MODEST_ABOOK_API < 4
443         osso_abook_contact_commit(contact, is_new, book);
444 #else
445         if (OSSO_ABOOK_IS_CONTACT (contact)) {
446                 osso_abook_contact_commit(OSSO_ABOOK_CONTACT(contact), is_new, book, NULL);
447         } else {
448                 GError *err = NULL;
449                 if (is_new) {
450                         if (!e_book_add_contact (book, contact, &err)) {
451                                 g_warning ("Failed to add contact: %s", err->message);
452                                 g_error_free (err);
453                         }
454                 } else {
455                         if (!e_book_commit_contact (book, contact, &err)) {
456                                 g_warning ("Failed to commit contact: %s", err->message);
457                                 g_error_free (err);
458                         }
459                 }
460         }
461 #endif /* MODEST_ABOOK_API < 2 */
462 }
463
464 /**
465  * This is a helper function used to launch 'Add e-mail address to contact' dialog
466  * after showing appropriate notification, when there is no e-mail address defined
467  * for a selected contact.
468  *
469  * @param  given_name  Given name of the contact
470  * @param  family_name  Family name of the contact
471  * @return E-mail address string entered by user, to be freed by calling function.
472  */
473 static gchar *
474 get_email_addr_from_user(const gchar * given_name, gboolean *canceled)
475 {
476         gchar *notification = NULL;
477         gchar *email_addr = NULL;
478         GtkWidget *note;
479         gboolean note_response;
480
481
482         notification = g_strdup_printf(_("mcen_nc_email_address_not_defined"), given_name);
483
484         note = hildon_note_new_confirmation (NULL, notification);
485         note_response = gtk_dialog_run (GTK_DIALOG(note));
486         gtk_widget_destroy (note);
487         g_free(notification);
488
489         if (note_response == GTK_RESPONSE_OK) {
490                 email_addr = run_add_email_addr_to_contact_dlg (given_name, canceled);
491         }
492
493         return email_addr;
494 }
495
496 /**
497 This function is used to get the formated email id with given name and sur name
498 in the format "GIVENNAME SURNAME <EMAIL ADDRESS>".
499 @param current_given_name    to hold the given name
500 @param current_sur_name      to hold the sur name
501 @param current_email_id      to hold the email id. 
502 @return gchar* string to be freed by calling function
503 */
504 static gchar *
505 ui_get_formatted_email_id(gchar * current_given_name,
506                           gchar * current_sur_name, gchar * current_email_id)
507 {
508         GString *email_id_str = NULL;
509
510         email_id_str = g_string_new(NULL);
511
512         if ((current_given_name != NULL) && ((strlen(current_given_name) != 0))
513             && (current_sur_name != NULL) && ((strlen(current_sur_name) != 0))) {
514                 g_string_append_printf(email_id_str, "%s %s", current_given_name, current_sur_name);
515         } else if ((current_given_name != NULL) && (strlen(current_given_name) != 0)) {
516                 g_string_append_printf(email_id_str, "%s", current_given_name);
517         } else if ((current_sur_name != NULL) && (strlen(current_sur_name) != 0)) {
518                 g_string_append_printf(email_id_str, "%s", current_sur_name);
519         }
520         if (g_utf8_strchr (email_id_str->str, -1, ' ')) {
521                 g_string_prepend_c (email_id_str, '\"');
522                 g_string_append_c (email_id_str, '\"');
523         }
524         g_string_append_printf (email_id_str, " %c%s%c", '<', current_email_id, '>');
525         return g_string_free (email_id_str, FALSE);
526 }
527
528 /**
529  * This is a helper function used to create & run 'Add e-mail address to contact' dialog.
530  * It allows user to enter an e-mail address, and shows appropriate infonote if the
531  * entered string is not a valid e-mail address.
532  *
533  * It must return TRUE in canceled if the dialog was canceled by the user
534  *
535  * @param  contact_name  Full name of the contact
536  * @return E-mail address string entered by user, to be freed by calling function.
537  */
538 static gchar *
539 run_add_email_addr_to_contact_dlg(const gchar * contact_name,
540                                   gboolean *canceled)
541 {
542         GtkWidget *add_email_addr_to_contact_dlg = NULL;
543         GtkSizeGroup *size_group = NULL;
544         GtkWidget *cptn_cntrl = NULL;
545         GtkWidget *name_label = NULL;
546         GtkWidget *email_entry = NULL;
547         gint result = -1;
548         gchar *new_email_addr = NULL;
549         gboolean run_dialog = TRUE;
550
551         g_return_val_if_fail (canceled, NULL);
552
553         *canceled = FALSE;
554
555         add_email_addr_to_contact_dlg =
556             gtk_dialog_new_with_buttons(_("mcen_ti_add_email_title"), NULL,
557                                         GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
558                                         _HL("wdgt_bd_save"), GTK_RESPONSE_ACCEPT, NULL);
559         gtk_dialog_set_has_separator(GTK_DIALOG(add_email_addr_to_contact_dlg), FALSE);
560 #ifdef MODEST_TOOLKIT_HILDON2
561         gtk_container_set_border_width (GTK_CONTAINER (GTK_DIALOG (add_email_addr_to_contact_dlg)->vbox), 
562                                         HILDON_MARGIN_DOUBLE);
563 #endif
564         /*Set app_name & state_save related tags to the window */
565
566         size_group = gtk_size_group_new(GTK_SIZE_GROUP_HORIZONTAL);
567         name_label = gtk_label_new(contact_name);
568         gtk_misc_set_alignment(GTK_MISC(name_label), 0.0, 0.5);
569         cptn_cntrl =
570                 modest_maemo_utils_create_captioned (size_group, NULL,
571                                                      _("mcen_ia_add_email_name"), FALSE,
572                                                      name_label);
573         gtk_box_pack_start(GTK_BOX(GTK_DIALOG(add_email_addr_to_contact_dlg)->vbox), cptn_cntrl,
574                            FALSE, FALSE, 0);
575
576         email_entry = hildon_entry_new (HILDON_SIZE_FINGER_HEIGHT | HILDON_SIZE_AUTO_WIDTH);
577         cptn_cntrl = modest_maemo_utils_create_captioned (size_group, NULL, 
578                                                           _("mcen_fi_add_email_name"), FALSE,
579                                                           email_entry);
580         hildon_gtk_entry_set_input_mode(GTK_ENTRY(email_entry), HILDON_GTK_INPUT_MODE_FULL);
581         gtk_box_pack_start(GTK_BOX(GTK_DIALOG(add_email_addr_to_contact_dlg)->vbox), cptn_cntrl,
582                            TRUE, TRUE, 0);
583
584         gtk_widget_show_all(add_email_addr_to_contact_dlg);
585
586         while (run_dialog) {
587                 run_dialog = FALSE;
588                 gtk_widget_grab_focus(email_entry);
589                 result = gtk_dialog_run(GTK_DIALOG(add_email_addr_to_contact_dlg));
590
591                 if (result == GTK_RESPONSE_ACCEPT) {
592                         const gchar *invalid_char_offset = NULL;
593                         new_email_addr = g_strdup(hildon_entry_get_text(HILDON_ENTRY(email_entry)));
594                         new_email_addr = g_strstrip(new_email_addr);
595                         if (!modest_text_utils_validate_email_address (new_email_addr, &invalid_char_offset)) {
596                                 gtk_widget_grab_focus(email_entry);
597                                 if ((invalid_char_offset != NULL)&&(*invalid_char_offset != '\0')) {
598                                         gchar *char_in_string = g_strdup_printf ("%c", *invalid_char_offset);
599                                         gchar *message = g_strdup_printf(
600                                                 _CS("ckdg_ib_illegal_characters_entered"), 
601                                                 char_in_string);
602                                         g_free (char_in_string);
603                                         hildon_banner_show_information (
604                                                 add_email_addr_to_contact_dlg, NULL, message );
605                                         g_free (message);
606                                 } else {
607                                         hildon_banner_show_information (add_email_addr_to_contact_dlg, NULL, _("mcen_ib_invalid_email"));
608                                         run_dialog = TRUE;
609                                 }
610                                 gtk_editable_select_region((GtkEditable *) email_entry, 0, -1);
611                                 g_free(new_email_addr);
612                                 new_email_addr = NULL;
613                         }
614                 } else {
615                         *canceled = TRUE;
616                 }
617         }
618
619         gtk_widget_destroy(add_email_addr_to_contact_dlg);
620
621         return new_email_addr;
622 }
623
624 /**
625  * This is helper function to create & run 'Select e-mail address' dialog, used when
626  * multiple e-mail addresses are found for a selected contact. It allows user to select
627  * one or more e-mail addresses for that contact.
628  *
629  * @param  email_addr_list  List of e-mail addresses for that contact
630  * @return List of user selected e-mail addresses, to be freed by calling function.
631  */
632 static GSList *
633 select_email_addrs_for_contact(GList * email_addr_list)
634 {
635         GtkWidget *select_email_addr_dlg = NULL;
636         GSList *selected_email_addr_list = NULL;
637         GList *node;
638         GtkWidget *selector;
639         gint result = -1;
640
641         if (!email_addr_list)
642                 return NULL;
643
644         select_email_addr_dlg = hildon_picker_dialog_new (NULL);
645         gtk_window_set_title (GTK_WINDOW (select_email_addr_dlg), _("mcen_ti_select_email_title"));
646
647         selector = hildon_touch_selector_new_text ();
648         for (node = email_addr_list; node != NULL && node->data != NULL; node = node->next) {
649                 gchar *email_addr;
650                 email_addr = g_strstrip(g_strdup(node->data));
651                 hildon_touch_selector_append_text (HILDON_TOUCH_SELECTOR (selector), email_addr);
652                 g_free(email_addr);
653         }
654
655         hildon_picker_dialog_set_selector (HILDON_PICKER_DIALOG (select_email_addr_dlg),
656                                            HILDON_TOUCH_SELECTOR (selector));
657         gtk_window_set_default_size (GTK_WINDOW (select_email_addr_dlg), MODEST_DIALOG_WINDOW_MAX_HEIGHT, -1);
658
659         gtk_widget_show_all(select_email_addr_dlg);
660         result = gtk_dialog_run(GTK_DIALOG(select_email_addr_dlg));
661
662         if (result == GTK_RESPONSE_OK) {
663                 gchar *current_text;
664
665                 current_text = hildon_touch_selector_get_current_text (HILDON_TOUCH_SELECTOR (selector));
666                 selected_email_addr_list = g_slist_append (selected_email_addr_list, current_text);
667         }
668
669         gtk_widget_destroy(select_email_addr_dlg);
670         return selected_email_addr_list;
671 }
672
673 static EContact *
674 get_contact_for_address (GList *contacts,
675                          const gchar *address)
676 {
677         EContact *retval = NULL, *contact;
678         GList *iter;
679
680         iter = contacts;
681         while (iter && !retval) {
682                 GList *emails = NULL;
683
684                 contact = E_CONTACT (iter->data);
685                 emails = e_contact_get (contact, E_CONTACT_EMAIL);
686                 if (emails) {
687                         /* Look for the email address */
688                         if (g_list_find_custom (emails, address, (GCompareFunc) g_strcmp0))
689                                 retval = contact;
690
691                         /* Free the list */
692                         g_list_foreach (emails, (GFunc) g_free, NULL);
693                         g_list_free (emails);
694                 }
695                 iter = g_list_next (iter);
696         }
697         return retval;
698 }
699
700 static void
701 async_get_contacts_cb (EBook *book,
702                        EBookStatus status,
703                        GList *contacts,
704                        gpointer closure)
705 {
706         GSList *addresses, *iter;
707         GList *to_commit_contacts, *to_add_contacts;
708
709         addresses = (GSList *) closure;
710
711         /* Check errors */
712         if (status != E_BOOK_ERROR_OK)
713                 goto frees;
714
715         iter = addresses;
716         to_commit_contacts = NULL;
717         to_add_contacts = NULL;
718         while (iter) {
719                 EContact *contact;
720                 const gchar *address;
721
722                 /* Look for a contact with such address. We perform
723                    this kind of search because we assume that users
724                    don't usually send emails to tons of addresses */
725                 address = (const gchar *) iter->data;
726                 contact = get_contact_for_address (contacts, address);
727
728                 /* Add new or commit existing contact */
729                 if (contact) {
730                         to_commit_contacts = g_list_prepend (to_commit_contacts, contact);
731                         g_debug ("----Preparing to commit contact %s", address);
732                 } else {
733                         gchar *email_address, *display_address;
734
735                         /* Create new contact and add it to the list */
736                         contact = e_contact_new ();
737                         email_address = modest_text_utils_get_email_address (address);
738                         e_contact_set (contact, E_CONTACT_EMAIL_1, email_address);
739                         g_free (email_address);
740
741                         display_address = g_strdup (address);
742                         if (display_address) {
743                                 modest_text_utils_get_display_address (display_address);
744                                 if ((display_address[0] != '\0') && (strlen (display_address) != strlen (address)))
745                                         e_contact_set (contact, E_CONTACT_FULL_NAME, (const gpointer)display_address);
746                                 g_free (display_address);
747                         }
748
749                         to_add_contacts = g_list_prepend (to_add_contacts, contact);
750                         g_debug ("----Preparing to add contact %s", address);
751                 }
752
753                 iter = g_slist_next (iter);
754         }
755
756         /* Asynchronously add contacts */
757         if (to_add_contacts)
758                 e_book_async_add_contacts (book, to_add_contacts, NULL, NULL);
759
760         /* Asynchronously commit contacts */
761         if (to_commit_contacts)
762                 e_book_async_commit_contacts (book, to_commit_contacts, NULL, NULL);
763
764         /* Free lists */
765         g_list_free (to_add_contacts);
766         g_list_free (to_commit_contacts);
767
768  frees:
769         if (addresses) {
770                 g_slist_foreach (addresses, (GFunc) g_free, NULL);
771                 g_slist_free (addresses);
772         }
773         if (contacts) {
774                 g_list_foreach (contacts, (GFunc) g_object_unref, NULL);
775                 g_list_free (contacts);
776         }
777 }
778
779
780 static void
781 add_to_address_book (GSList *addresses)
782 {
783         EBookQuery **queries, *composite_query;
784         gint num_add, i;
785
786         g_return_if_fail (addresses);
787
788         if (!book)
789                 if (!open_addressbook ())
790                         g_return_if_reached ();
791
792         /* Create the list of queries */
793         num_add = g_slist_length (addresses);
794         queries = g_malloc0 (sizeof (EBookQuery *) * num_add);
795         for (i = 0; i < num_add; i++) {
796                 gchar *email;
797
798                 email = modest_text_utils_get_email_address (g_slist_nth_data (addresses, i));
799                 queries[i] = e_book_query_field_test (E_CONTACT_EMAIL, E_BOOK_QUERY_IS, email);
800                 g_free (email);
801         }
802
803         /* Create the query */
804         composite_query = e_book_query_or (num_add, queries, TRUE);
805
806         /* Asynchronously retrieve contacts */
807         e_book_async_get_contacts (book, composite_query, async_get_contacts_cb, addresses);
808
809         /* Frees. This will unref the subqueries as well */
810         e_book_query_unref (composite_query);
811 }
812
813 typedef struct _CheckNamesInfo {
814         GtkWidget *banner;
815         guint show_banner_timeout;
816         guint hide_banner_timeout;
817         gboolean hide;
818         gboolean free_info;
819 } CheckNamesInfo;
820
821 static void
822 hide_check_names_banner (CheckNamesInfo *info)
823 {
824         if (info->show_banner_timeout > 0) {
825                 g_source_remove (info->show_banner_timeout);
826                 info->show_banner_timeout = 0;
827         }
828         if (info->hide_banner_timeout > 0) {
829                 info->hide = TRUE;
830                 return;
831         }
832
833         if (info->banner) {
834                 gtk_widget_destroy (info->banner);
835                 info->banner = NULL;
836                 info->hide = FALSE;
837         }
838
839         if (info->free_info) {
840                 g_slice_free (CheckNamesInfo, info);
841         }
842 }
843
844 static gboolean hide_banner_timeout_handler (CheckNamesInfo *info)
845 {
846         info->hide_banner_timeout = 0;
847         if (info->hide) {
848                 gtk_widget_destroy (info->banner);
849                 info->banner = NULL;
850         }
851         if (info->free_info) {
852                 g_slice_free (CheckNamesInfo, info);
853         }
854         return FALSE;
855 }
856
857 static gboolean show_banner_timeout_handler (CheckNamesInfo *info)
858 {
859         info->show_banner_timeout = 0;
860         info->banner = hildon_banner_show_animation (NULL, NULL, _("mail_ib_checking_names"));
861         info->hide_banner_timeout = g_timeout_add (1000, (GSourceFunc) hide_banner_timeout_handler, (gpointer) info);
862         return FALSE;
863 }
864
865 static void show_check_names_banner (CheckNamesInfo *info)
866 {
867         if (info->hide_banner_timeout > 0) {
868                 g_source_remove (info->hide_banner_timeout);
869                 info->hide_banner_timeout = 0;
870         }
871
872         info->hide = FALSE;
873         if (info->show_banner_timeout > 0)
874                 return;
875
876         if (info->banner == NULL) {
877                 info->show_banner_timeout = g_timeout_add (500, (GSourceFunc) show_banner_timeout_handler, (gpointer) info);
878         }
879 }
880
881 static void clean_check_names_banner (CheckNamesInfo *info)
882 {
883         if (info->hide_banner_timeout) {
884                 info->free_info = TRUE;
885         } else {
886                 if (info->show_banner_timeout) {
887                         g_source_remove (info->show_banner_timeout);
888                 }
889                 if (info->banner)
890                         gtk_widget_destroy (info->banner);
891                 g_slice_free (CheckNamesInfo, info);
892         }
893 }
894
895 void free_resolved_addresses_list (gpointer data,
896                                    gpointer ignored)
897 {
898         GSList *list = (GSList *)data;
899         g_slist_foreach (list, (GFunc) g_free, NULL);
900         g_slist_free (list);
901 }
902
903 gboolean
904 modest_address_book_check_names (ModestRecptEditor *recpt_editor, gboolean update_addressbook)
905 {
906         const gchar *recipients = NULL;
907         GSList *start_indexes = NULL, *end_indexes = NULL;
908         GSList *current_start, *current_end, *to_commit_addresses;
909         gboolean result = TRUE;
910         GtkTextBuffer *buffer;
911         gint offset_delta = 0;
912         gint last_length;
913         GtkTextIter start_iter, end_iter;
914
915         g_return_val_if_fail (MODEST_IS_RECPT_EDITOR (recpt_editor), FALSE);
916
917         recipients = modest_recpt_editor_get_recipients (recpt_editor);
918         last_length = g_utf8_strlen (recipients, -1);
919         modest_text_utils_get_addresses_indexes (recipients, &start_indexes, &end_indexes);
920
921         if (start_indexes == NULL) {
922                 if (last_length != 0) {
923                         hildon_banner_show_information (NULL, NULL, _("mcen_nc_no_matching_contacts"));
924                         return FALSE;
925                 } else {
926                         return TRUE;
927                 }
928         }
929
930         current_start = start_indexes;
931         current_end = end_indexes;
932         buffer = modest_recpt_editor_get_buffer (recpt_editor);
933         to_commit_addresses = NULL;
934
935         while (current_start != NULL) {
936                 gchar *address;
937                 gchar *start_ptr, *end_ptr;
938                 gint start_pos, end_pos;
939                 const gchar *invalid_char_position = NULL;
940                 gboolean store_address = FALSE;
941
942                 start_pos = (*((gint*) current_start->data)) + offset_delta;
943                 end_pos = (*((gint*) current_end->data)) + offset_delta;
944                
945                 start_ptr = g_utf8_offset_to_pointer (recipients, start_pos);
946                 end_ptr = g_utf8_offset_to_pointer (recipients, end_pos);
947
948                 address = g_strstrip (g_strndup (start_ptr, end_ptr - start_ptr));
949                 gtk_text_buffer_get_iter_at_offset (buffer, &start_iter, start_pos);
950                 gtk_text_buffer_get_iter_at_offset (buffer, &end_iter, end_pos);
951                 gtk_text_buffer_select_range (buffer, &start_iter, &end_iter);
952
953                 if (!modest_text_utils_validate_recipient (address, &invalid_char_position)) {
954                         if ((invalid_char_position != NULL) && (*invalid_char_position != '\0')) {
955                                 gchar *char_in_string = g_strdup_printf("%c", *invalid_char_position);
956                                 gchar *message = 
957                                         g_strdup_printf(_CS("ckdg_ib_illegal_characters_entered"), 
958                                                         char_in_string);
959                                 g_free (char_in_string);
960                                 hildon_banner_show_information (NULL, NULL, message );
961                                 g_free (message);
962                                 result = FALSE;
963                         } else if (strstr (address, "@") == NULL) {
964                                 /* here goes searching in addressbook */
965                                 gboolean canceled;
966                                 GSList *contact_ids = NULL;
967                                 GSList *resolved_addresses = NULL;
968
969                                 result = resolve_address (address, &resolved_addresses, &contact_ids, &canceled);
970
971                                 if (result) {
972                                         gint new_length;
973
974                                         modest_recpt_editor_replace_with_resolved_recipients (recpt_editor,
975                                                                                               &start_iter, &end_iter,
976                                                                                               resolved_addresses,
977                                                                                               contact_ids);
978                                         g_slist_foreach (contact_ids, (GFunc) g_free, NULL);
979                                         g_slist_foreach (resolved_addresses, free_resolved_addresses_list, NULL);
980                                         g_slist_free (contact_ids);
981                                         g_slist_free (resolved_addresses);
982
983                                         /* update offset delta */
984                                         recipients = modest_recpt_editor_get_recipients (recpt_editor);
985                                         new_length = g_utf8_strlen (recipients, -1);
986                                         offset_delta = offset_delta + new_length - last_length;
987                                         last_length = new_length;
988                                 } else {
989                                         if (canceled) {
990                                                 /* We have to remove the recipient if not resolved */
991                                                 modest_recpt_editor_replace_with_resolved_recipient (recpt_editor,
992                                                                                                      &start_iter, 
993                                                                                                      &end_iter,
994                                                                                                      NULL,
995                                                                                                      NULL);
996                                         } else {
997                                                 /* There is no contact with that name so it's not
998                                                    valid. Don't show any error because it'll be done
999                                                    later */
1000                                                 result = FALSE;
1001                                         }
1002                                 }
1003                         } else {
1004                                 /* this address is not valid, select it and return control to user showing banner */
1005                                 hildon_banner_show_information (NULL, NULL, _("mcen_ib_invalid_email"));
1006                                 result = FALSE;
1007                         }
1008                 } else {
1009                         GSList *tags, *node;
1010                         gboolean has_recipient = FALSE;
1011
1012                         tags = gtk_text_iter_get_tags (&start_iter);
1013                         for (node = tags; node != NULL; node = g_slist_next (node)) {
1014                                 GtkTextTag *tag = GTK_TEXT_TAG (node->data);
1015                                 if (g_object_get_data (G_OBJECT (tag), "recipient-tag-id") != NULL) {
1016                                         has_recipient = TRUE;
1017                                         break;
1018                                 }
1019                         }
1020                         g_slist_free (tags);
1021                         if (!has_recipient) {
1022                                 GSList * address_list = NULL;
1023
1024                                 address_list = g_slist_prepend (address_list, address);
1025                                 modest_recpt_editor_replace_with_resolved_recipient (recpt_editor,
1026                                                                                      &start_iter, &end_iter,
1027                                                                                      address_list, 
1028                                                                                      "");
1029                                 g_slist_free (address_list);
1030                                 store_address = TRUE;
1031                         }
1032                 }
1033
1034                 /* so, it seems a valid address */
1035                 /* note: adding it the to the addressbook if it did not exist yet,
1036                  * and adding it to the recent_list */
1037                 if (result && update_addressbook && store_address)
1038                         to_commit_addresses = g_slist_prepend (to_commit_addresses, address);
1039                 else
1040                         g_free (address);
1041
1042                 if (result == FALSE)
1043                         break;
1044
1045                 current_start = g_slist_next (current_start);
1046                 current_end = g_slist_next (current_end);
1047         }
1048
1049         /* Add addresses to address-book */
1050         if (to_commit_addresses)
1051                 add_to_address_book (to_commit_addresses);
1052
1053         if (current_start == NULL) {
1054                 gtk_text_buffer_get_end_iter (buffer, &end_iter);
1055                 gtk_text_buffer_place_cursor (buffer, &end_iter);
1056         }
1057
1058         g_slist_foreach (start_indexes, (GFunc) g_free, NULL);
1059         g_slist_foreach (end_indexes, (GFunc) g_free, NULL);
1060         g_slist_free (start_indexes);
1061         g_slist_free (end_indexes);
1062
1063         return result;
1064
1065 }
1066
1067 typedef struct _GetContactsInfo {
1068         GMainLoop *mainloop;
1069         GList *result;
1070 } GetContactsInfo;
1071
1072 static void 
1073 get_contacts_for_name_cb (EBook *book, 
1074                           EBookStatus status, 
1075                           GList *list, 
1076                           gpointer userdata)
1077 {
1078         GetContactsInfo *info = (GetContactsInfo *) userdata;
1079
1080         if (status == E_BOOK_ERROR_OK)
1081                 info->result = list;
1082
1083         g_main_loop_quit (info->mainloop);
1084 }
1085
1086 static GList *
1087 get_contacts_for_name (const gchar *name)
1088 {
1089         EBookQuery *full_name_book_query = NULL;
1090         GList *result;
1091         gchar *unquoted;
1092         GetContactsInfo *info;
1093
1094         if (name == NULL)
1095                 return NULL;
1096
1097         unquoted = unquote_string (name);
1098         full_name_book_query = e_book_query_field_test (E_CONTACT_FULL_NAME, E_BOOK_QUERY_CONTAINS, unquoted);
1099         g_free (unquoted);
1100
1101         /* TODO: Make it launch a mainloop */
1102         info = g_slice_new (GetContactsInfo);
1103         info->mainloop = g_main_loop_new (NULL, FALSE);
1104         info->result = NULL;
1105         if (e_book_async_get_contacts (book, full_name_book_query, get_contacts_for_name_cb, info) == 0) {
1106                 GDK_THREADS_LEAVE ();
1107                 g_main_loop_run (info->mainloop);
1108                 GDK_THREADS_ENTER ();
1109         } 
1110         result = info->result;
1111         e_book_query_unref (full_name_book_query);
1112         g_main_loop_unref (info->mainloop);
1113         g_slice_free (GetContactsInfo, info);
1114
1115         return result;
1116 }
1117
1118 static GList *
1119 select_contacts_for_name_dialog (const gchar *name)
1120 {
1121         EBookQuery *full_name_book_query = NULL;
1122         EBookView *book_view = NULL;
1123         GList *result = NULL;
1124         gchar *unquoted;
1125
1126         unquoted = unquote_string (name);
1127         full_name_book_query = e_book_query_field_test (E_CONTACT_FULL_NAME, E_BOOK_QUERY_CONTAINS, unquoted);
1128         g_free (unquoted);
1129         e_book_get_book_view (book, full_name_book_query, NULL, -1, &book_view, NULL);
1130         e_book_query_unref (full_name_book_query);
1131
1132         if (book_view) {
1133                 GtkWidget *contact_dialog = NULL;
1134 #if MODEST_ABOOK_API < 4
1135                 GtkWidget *contact_view = NULL;
1136                 osso_abook_tree_model_set_book_view (OSSO_ABOOK_TREE_MODEL (contact_model), book_view);
1137                 e_book_view_start (book_view);
1138
1139                 contact_view = osso_abook_contact_selector_new_basic (contact_model);
1140                 contact_dialog = osso_abook_select_dialog_new (OSSO_ABOOK_TREE_VIEW (contact_view));
1141
1142                 if (gtk_dialog_run (GTK_DIALOG (contact_dialog)) == GTK_RESPONSE_OK) {
1143                         result = osso_abook_contact_view_get_selection (OSSO_ABOOK_CONTACT_VIEW (contact_view));
1144                 }
1145                 e_book_view_stop (book_view);
1146                 g_object_unref (book_view);
1147                 gtk_widget_destroy (contact_dialog);
1148 #else /* MODEST_ABOOK_API < 4 */
1149                 osso_abook_list_store_set_book_view (OSSO_ABOOK_LIST_STORE (contact_model), book_view);
1150                 e_book_view_start (book_view);
1151
1152                 /* TODO: figure out how to make the contact chooser modal */
1153                 contact_dialog = osso_abook_contact_chooser_new_with_capabilities (NULL,
1154                                                                                    _AB("addr_ti_dia_select_contacts"),
1155                                                                                    OSSO_ABOOK_CAPS_EMAIL,
1156                                                                                    OSSO_ABOOK_CONTACT_ORDER_NAME);
1157                 /* Enable multiselection */
1158                 osso_abook_contact_chooser_set_maximum_selection (OSSO_ABOOK_CONTACT_CHOOSER (contact_dialog),
1159                                                                   G_MAXUINT);
1160                 osso_abook_contact_chooser_set_model (OSSO_ABOOK_CONTACT_CHOOSER (contact_dialog),
1161                                                       contact_model);
1162
1163                 if (gtk_dialog_run (GTK_DIALOG (contact_dialog)) == GTK_RESPONSE_OK)
1164                         result = osso_abook_contact_chooser_get_selection (OSSO_ABOOK_CONTACT_CHOOSER (contact_dialog));
1165                 e_book_view_stop (book_view);
1166                 g_object_unref (book_view);
1167                 gtk_widget_destroy (contact_dialog);
1168 #endif /* MODEST_ABOOK_API < 4 */
1169         }
1170
1171         return result;
1172 }
1173
1174 static gboolean
1175 resolve_address (const gchar *address, 
1176                  GSList **resolved_addresses, 
1177                  GSList **contact_ids,
1178                  gboolean *canceled)
1179 {
1180         GList *resolved_contacts;
1181         CheckNamesInfo *info;;
1182
1183         g_return_val_if_fail (canceled, FALSE);
1184
1185         *resolved_addresses = NULL;
1186         *contact_ids = NULL;
1187         *canceled = FALSE;
1188         info = g_slice_new0 (CheckNamesInfo);
1189         show_check_names_banner (info);
1190         
1191         contact_model = osso_abook_contact_model_new ();
1192         if (!open_addressbook_sync ()) {
1193                 hide_check_names_banner (info);
1194                 if (contact_model) {
1195                         g_object_unref (contact_model);
1196                         contact_model = NULL;
1197                 }
1198                 clean_check_names_banner (info);
1199                 return FALSE;
1200         }
1201
1202         resolved_contacts = get_contacts_for_name (address);
1203         hide_check_names_banner (info);
1204
1205         if (resolved_contacts == NULL) {
1206                 /* no matching contacts for the search string */
1207                 modest_platform_run_information_dialog (NULL, _("mcen_nc_no_matching_contacts"), FALSE);
1208                 clean_check_names_banner (info);
1209                 return FALSE;
1210         }
1211
1212         if (g_list_length (resolved_contacts) > 1) {
1213                 /* show a dialog to select the contact from the resolved ones */
1214                 g_list_free (resolved_contacts);
1215
1216                 resolved_contacts = select_contacts_for_name_dialog (address);
1217         }
1218
1219         /* get the resolved contacts (can be no contact) */
1220         if (resolved_contacts) {
1221                 GList *node;
1222                 gboolean found = FALSE;
1223
1224                 for (node = resolved_contacts; node != NULL; node = g_list_next (node)) {
1225                         EContact *contact = (EContact *) node->data;
1226                         GSList *resolved;
1227                         gchar *contact_id;
1228
1229                         resolved = get_recipients_for_given_contact (contact, canceled);
1230                         if (resolved) {
1231                                 contact_id = g_strdup (e_contact_get_const (contact, E_CONTACT_UID));
1232                                 *contact_ids = g_slist_append (*contact_ids, contact_id);
1233                                 found = TRUE;
1234                                 *resolved_addresses = g_slist_append (*resolved_addresses, resolved);
1235                         }
1236                 }
1237
1238                 g_list_foreach (resolved_contacts, (GFunc)unref_gobject, NULL);
1239                 g_list_free (resolved_contacts);
1240                 clean_check_names_banner (info);
1241
1242                 return found;
1243         } else {
1244                 /* cancelled dialog to select more than one contact or
1245                  * selected no contact */
1246                 clean_check_names_banner (info);
1247                 return FALSE;
1248         }
1249
1250 }
1251
1252 static gchar *
1253 unquote_string (const gchar *str)
1254 {
1255         GString *buffer;
1256         gchar *p;
1257
1258         if (str == NULL)
1259                 return NULL;
1260
1261         buffer = g_string_new_len (NULL, strlen (str));
1262         for (p = (gchar *) str; *p != '\0'; p = g_utf8_next_char (p)) {
1263                 if (*p == '"') {
1264                         p = g_utf8_next_char (p);
1265                         while ((*p != '\0')&&(*p != '"')) {
1266                                 if (*p == '\\') {
1267                                         g_string_append_unichar (buffer, g_utf8_get_char (p));
1268                                         p = g_utf8_next_char (p);
1269
1270                                 }
1271                                 g_string_append_unichar (buffer, g_utf8_get_char (p));
1272                                 p = g_utf8_next_char (p);
1273                         }
1274                 } else {
1275                         g_string_append_unichar (buffer, g_utf8_get_char (p));
1276                 }
1277         }
1278
1279         return g_string_free (buffer, FALSE);
1280
1281 }
1282
1283 gboolean
1284 modest_address_book_has_address (const gchar *address)
1285 {
1286         EBookQuery *query;
1287         GList *contacts = NULL;
1288         GError *err = NULL;
1289         gchar *email;
1290         gboolean result;
1291
1292         g_return_val_if_fail (address, FALSE);
1293         
1294         if (!book) {
1295                 if (!open_addressbook ()) {
1296                         g_return_val_if_reached (FALSE);
1297                 }
1298         }
1299         
1300         g_return_val_if_fail (book, FALSE);
1301
1302         email = modest_text_utils_get_email_address (address);
1303         
1304         query = e_book_query_field_test (E_CONTACT_EMAIL, E_BOOK_QUERY_IS, email);
1305         if (!e_book_get_contacts (book, query, &contacts, &err)) {
1306                 g_printerr ("modest: failed to get contacts: %s",
1307                             err ? err->message : "<unknown>");
1308                 if (err)
1309                         g_error_free (err);
1310                 g_free (email);
1311                 e_book_query_unref (query);
1312                 return FALSE;
1313         }
1314         e_book_query_unref (query);
1315
1316         result = (contacts != NULL);
1317         if (contacts) {
1318                 g_list_foreach (contacts, (GFunc)unref_gobject, NULL);
1319                 g_list_free (contacts);
1320         }
1321         
1322         g_free (email);
1323
1324         return result;
1325 }