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