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