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