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