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