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