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