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