4e19d8989bae61434c6da14997882bd323b55ab7
[modest] / src / hildon2 / modest-address-book.c
1 /* Copyright (c) 2007, Nokia Corporation
2  * All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
8  * * Redistributions of source code must retain the above copyright
9  *   notice, this list of conditions and the following disclaimer.
10  * * Redistributions in binary form must reproduce the above copyright
11  *   notice, this list of conditions and the following disclaimer in the
12  *   documentation and/or other materials provided with the distribution.
13  * * Neither the name of the Nokia Corporation nor the names of its
14  *   contributors may be used to endorse or promote products derived from
15  *   this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
18  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
19  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
20  * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
21  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 /* modest-address-book.c */
31
32 #include <config.h>
33 #include <glib/gi18n.h>
34 #include <modest-address-book.h>
35 #include <modest-text-utils.h>
36 #include <libebook/e-book.h>
37 #include <libebook/e-book-view.h>
38 #include <libebook/e-vcard.h>
39 #include "modest-hildon-includes.h"
40 #include <libosso-abook/osso-abook.h>
41 #include <libedataserver/e-data-server-util.h>
42 #include "modest-platform.h"
43 #include "modest-runtime.h"
44 #include "widgets/modest-window-mgr.h"
45 #include "widgets/modest-ui-constants.h"
46 #include <string.h>
47 #include <gtk/gtksizegroup.h>
48 #include <gtk/gtkbox.h>
49 #include <gtk/gtklabel.h>
50 #include <gtk/gtkcellrenderertext.h>
51 #include <gtk/gtktreeselection.h>
52 #include <gtk/gtkentry.h>
53 #include <modest-maemo-utils.h>
54
55 static OssoABookContactModel *contact_model =  NULL;
56 static EBook *book = NULL;
57 static EBookView * book_view = NULL;
58
59 static GSList *get_recipients_for_given_contact (EContact * contact, gboolean *canceled);
60 static gchar *get_email_addr_from_user(const gchar * given_name, gboolean *canceled);
61 static gchar *ui_get_formatted_email_id(gchar * current_given_name,
62                                         gchar * current_sur_name, gchar * current_email_id);
63 static gchar *run_add_email_addr_to_contact_dlg(const gchar * contact_name, gboolean *canceled);
64 static GSList *select_email_addrs_for_contact(GList * email_addr_list);
65 static gboolean resolve_address (const gchar *address, GSList **resolved_addresses, GSList **contact_id, gboolean *canceled);
66 static gchar *unquote_string (const gchar *str);
67
68 static gboolean
69 open_addressbook ()
70 {
71         OssoABookRoster *roster;
72         GError *error = NULL;
73         time_t init,end;
74
75         if (book && book_view)
76                 return TRUE;
77
78         roster = osso_abook_aggregator_get_default (&error);
79         if (error)
80                 goto error;
81
82         /* Wait until it's ready */
83         init = time (NULL);
84         osso_abook_waitable_run ((OssoABookWaitable *) roster,
85                                  g_main_context_default (),
86                                  &error);
87         end = time (NULL);
88         g_debug ("Opening addressbook lasted %ld seconds", (gint) end-init);
89
90         if (error)
91                 goto error;
92
93         if (!osso_abook_waitable_is_ready ((OssoABookWaitable *) roster,
94                                            &error))
95                 goto error;
96
97         book = osso_abook_roster_get_book (roster);
98         book_view = osso_abook_roster_get_book_view (roster);
99
100         return TRUE;
101  error:
102         g_warning ("error opening addressbook %s", error->message);
103         g_error_free (error);
104         return FALSE;
105 }
106
107 void
108 modest_address_book_add_address (const gchar *address,
109                                  GtkWindow *parent)
110 {
111         GtkWidget *dialog = NULL;
112         gchar *email_address;
113         EVCardAttribute *attribute;
114
115         if (!open_addressbook ()) {
116                 return;
117         }
118
119         email_address = modest_text_utils_get_email_address (address);
120
121         attribute = e_vcard_attribute_new (NULL, EVC_EMAIL);
122         e_vcard_attribute_add_value (attribute, email_address);
123         dialog = osso_abook_temporary_contact_dialog_new (parent, book, attribute, NULL);
124
125         gtk_dialog_run (GTK_DIALOG (dialog));
126
127         gtk_widget_destroy (dialog);
128
129         e_vcard_attribute_free (attribute);
130         g_free (email_address);
131
132 }
133
134 void
135 modest_address_book_select_addresses (ModestRecptEditor *recpt_editor,
136                                       GtkWindow *parent_window)
137 {
138         GtkWidget *contact_chooser = NULL;
139         GList *contacts_list = NULL;
140         GSList *email_addrs_per_contact = NULL;
141         gchar *econtact_id;
142         gboolean focus_recpt_editor = FALSE;
143
144         g_return_if_fail (MODEST_IS_RECPT_EDITOR (recpt_editor));
145
146         /* TODO: figure out how to make the contact chooser modal */
147         contact_chooser = osso_abook_contact_chooser_new_with_capabilities (parent_window,
148                                                                             _AB("addr_ti_dia_select_contacts"),
149                                                                             OSSO_ABOOK_CAPS_EMAIL, 
150                                                                             OSSO_ABOOK_CONTACT_ORDER_NAME);
151         /* Enable multiselection */
152         osso_abook_contact_chooser_set_maximum_selection (OSSO_ABOOK_CONTACT_CHOOSER (contact_chooser),
153                                                           G_MAXUINT);
154
155         if (gtk_dialog_run (GTK_DIALOG (contact_chooser)) == GTK_RESPONSE_OK)
156                 contacts_list = osso_abook_contact_chooser_get_selection (OSSO_ABOOK_CONTACT_CHOOSER (contact_chooser));
157         gtk_widget_destroy (contact_chooser);
158
159         if (contacts_list) {
160                 GList *node;
161
162                 for (node = contacts_list; node != NULL; node = g_list_next (node)) {
163                         EContact *contact = (EContact *) node->data;
164                         gboolean canceled;
165
166                         email_addrs_per_contact = get_recipients_for_given_contact (contact, &canceled);
167                         if (email_addrs_per_contact) {
168                                 econtact_id = (gchar *) e_contact_get_const (contact, E_CONTACT_UID);
169                                 modest_recpt_editor_add_resolved_recipient (MODEST_RECPT_EDITOR (recpt_editor), 
170                                                                             email_addrs_per_contact, econtact_id);
171                                 g_slist_foreach (email_addrs_per_contact, (GFunc) g_free, NULL);
172                                 g_slist_free (email_addrs_per_contact);
173                                 email_addrs_per_contact = NULL;
174                                 focus_recpt_editor = TRUE;
175                         }
176                 }
177                 g_list_free (contacts_list);
178         }
179
180         if (focus_recpt_editor)
181                 modest_recpt_editor_grab_focus (MODEST_RECPT_EDITOR (recpt_editor));
182
183 }
184
185 /**
186  * This function returns the resolved recipients for a given EContact.
187  * If no e-mail address is defined, it launches 'Add e-mail address to contact'
188  * dialog to obtain one. If multiple e-mail addresses are found, it launches
189  * 'Select e-mail address' dialog to allow user to select one or more e-mail
190  * addresses for that contact.
191  *
192  * @param  Contact of type #EContact
193  * @return List of resolved recipient strings, to be freed by calling function.
194  */
195 static GSList *
196 get_recipients_for_given_contact (EContact * contact,
197                                   gboolean *canceled)
198 {
199         gchar *givenname = NULL;
200         gchar *familyname = NULL;
201         gchar *nickname = NULL;
202         gchar *emailid = NULL;
203         const gchar *display_name = NULL;
204         GList *list = NULL;
205         gchar *formatted_string = NULL;
206         gboolean email_not_present = FALSE;
207         GSList *formattedlist = NULL, *selected_email_addr_list = NULL, *node = NULL;
208
209         if (!contact) {
210                 return NULL;
211         }
212
213         givenname = (gchar *) e_contact_get_const(contact, E_CONTACT_GIVEN_NAME);
214         familyname = (gchar *) e_contact_get_const(contact, E_CONTACT_FAMILY_NAME);
215         nickname = (gchar *) e_contact_get_const(contact, E_CONTACT_NICKNAME);
216         if (!nickname)
217                 nickname = "";
218         list = (GList *) e_contact_get(contact, E_CONTACT_EMAIL);
219
220         if (!list) {
221                 email_not_present = TRUE;
222         }
223
224         if (list && g_list_length(list) == 1) {
225                 if (list->data == NULL || g_utf8_strlen(list->data, -1) == 0) {
226                         email_not_present = TRUE;
227                 } else {
228                         emailid = g_strstrip(g_strdup(list->data));
229                         if (g_utf8_strlen(emailid, -1) == 0) {
230                                 g_free(emailid);
231                                 email_not_present = TRUE;
232                         }
233                 }
234         }
235
236         /*Launch the 'Add e-mail addr to contact' dialog if required */
237         if (email_not_present) {
238                 OssoABookContact *abook_contact;
239
240                 abook_contact = osso_abook_contact_new_from_template (contact);
241                 display_name = osso_abook_contact_get_display_name(abook_contact);
242
243                 emailid = get_email_addr_from_user(display_name, canceled);
244                 if (emailid) {
245                         list = g_list_append (list, g_strdup (emailid));
246                         e_contact_set(E_CONTACT (abook_contact), E_CONTACT_EMAIL, list);
247                         osso_abook_contact_commit (abook_contact, FALSE, NULL, NULL);
248                 }
249                 g_object_unref (abook_contact);
250         }
251
252         if (emailid) {
253                 if (givenname || familyname)
254                         formatted_string =
255                             ui_get_formatted_email_id(givenname, familyname, emailid);
256                 else
257                         formatted_string = g_strdup(emailid);
258                 formattedlist = g_slist_append(formattedlist, formatted_string);
259                 g_free(emailid);
260         }
261
262         /*Launch the 'Select e-mail address' dialog if required */
263         if (g_list_length(list) > 1) {
264                 selected_email_addr_list = select_email_addrs_for_contact(list);
265                 for (node = selected_email_addr_list; node != NULL; node = node->next) {
266                         if (givenname || familyname)
267                                 formatted_string =
268                                     ui_get_formatted_email_id(givenname, familyname, node->data);
269                         else
270                                 formatted_string = g_strdup(node->data);
271                         formattedlist = g_slist_append(formattedlist, formatted_string);
272                 }
273                 if (selected_email_addr_list) {
274                         g_slist_foreach(selected_email_addr_list, (GFunc) g_free, NULL);
275                         g_slist_free(selected_email_addr_list);
276                 }
277         }
278
279         if (list) {
280                 g_list_foreach(list, (GFunc) g_free, NULL);
281                 g_list_free(list);
282         }
283
284         return formattedlist;
285 }
286
287 /**
288  * This is a helper function used to launch 'Add e-mail address to contact' dialog
289  * after showing appropriate notification, when there is no e-mail address defined
290  * for a selected contact.
291  *
292  * @param  given_name  Given name of the contact
293  * @param  family_name  Family name of the contact
294  * @return E-mail address string entered by user, to be freed by calling function.
295  */
296 static gchar *
297 get_email_addr_from_user(const gchar * given_name, gboolean *canceled)
298 {
299         gchar *notification = NULL;
300         gchar *email_addr = NULL;
301         GtkWidget *note;
302         gboolean note_response;
303
304
305         notification = g_strdup_printf(_("mcen_nc_email_address_not_defined"), given_name);
306
307         note = hildon_note_new_confirmation (NULL, notification);
308         note_response = gtk_dialog_run (GTK_DIALOG(note));
309         gtk_widget_destroy (note);
310         g_free(notification);
311
312         if (note_response == GTK_RESPONSE_OK) {
313                 email_addr = run_add_email_addr_to_contact_dlg (given_name, canceled);
314         }
315
316         return email_addr;
317 }
318
319 /**
320 This function is used to get the formated email id with given name and sur name
321 in the format "GIVENNAME SURNAME <EMAIL ADDRESS>".
322 @param current_given_name    to hold the given name
323 @param current_sur_name      to hold the sur name
324 @param current_email_id      to hold the email id. 
325 @return gchar* string to be freed by calling function
326 */
327 static gchar *
328 ui_get_formatted_email_id(gchar * current_given_name,
329                           gchar * current_sur_name, gchar * current_email_id)
330 {
331         GString *email_id_str = NULL;
332
333         email_id_str = g_string_new(NULL);
334
335         if ((current_given_name != NULL) && ((strlen(current_given_name) != 0))
336             && (current_sur_name != NULL) && ((strlen(current_sur_name) != 0))) {
337                 g_string_append_printf(email_id_str, "%s %s", current_given_name, current_sur_name);
338         } else if ((current_given_name != NULL) && (strlen(current_given_name) != 0)) {
339                 g_string_append_printf(email_id_str, "%s", current_given_name);
340         } else if ((current_sur_name != NULL) && (strlen(current_sur_name) != 0)) {
341                 g_string_append_printf(email_id_str, "%s", current_sur_name);
342         }
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, *mail1_down, *mail2_down;
503
504         /* Perform a case insensitive comparison */
505         mail1 = modest_text_utils_get_email_address (address1);
506         mail1_down = g_ascii_strdown (mail1, -1);
507         mail2_down = g_ascii_strdown (mail2, -1);
508         retval = g_strcmp0 (mail1_down, mail2_down);
509         g_free (mail1);
510         g_free (mail1_down);
511         g_free (mail2_down);
512
513         return retval;
514 }
515
516 static EContact *
517 get_contact_for_address (GList *contacts,
518                          const gchar *address)
519 {
520         EContact *retval = NULL, *contact;
521         GList *iter;
522         gchar *email;
523
524         email = modest_text_utils_get_email_address (address);
525         iter = contacts;
526         while (iter && !retval) {
527                 GList *emails = NULL;
528
529                 contact = E_CONTACT (iter->data);
530                 emails = e_contact_get (contact, E_CONTACT_EMAIL);
531                 if (emails) {
532                         /* Look for the email address */
533                         if (g_list_find_custom (emails, email, (GCompareFunc) compare_addresses))
534                                 retval = contact;
535
536                         /* Free the list */
537                         g_list_foreach (emails, (GFunc) g_free, NULL);
538                         g_list_free (emails);
539                 }
540                 iter = g_list_next (iter);
541         }
542         g_free (email);
543
544         return retval;
545 }
546
547 static void
548 async_get_contacts_cb (EBook *book,
549                        EBookStatus status,
550                        GList *contacts,
551                        gpointer closure)
552 {
553         GSList *addresses, *iter;
554         GList *to_commit_contacts, *to_add_contacts;
555         EContact *self_contact;
556
557         addresses = (GSList *) closure;
558
559         /* Check errors */
560         if (status != E_BOOK_ERROR_OK)
561                 goto frees;
562
563         self_contact = (EContact *) osso_abook_self_contact_get_default ();
564         if (self_contact) {
565                 contacts = g_list_prepend (contacts, self_contact);
566         }
567
568         iter = addresses;
569         to_commit_contacts = NULL;
570         to_add_contacts = NULL;
571         while (iter) {
572                 EContact *contact;
573                 const gchar *address;
574
575                 /* Look for a contact with such address. We perform
576                    this kind of search because we assume that users
577                    don't usually send emails to tons of addresses */
578                 address = (const gchar *) iter->data;
579                 contact = get_contact_for_address (contacts, address);
580
581                 /* Add new or commit existing contact */
582                 if (contact) {
583                         to_commit_contacts = g_list_prepend (to_commit_contacts, contact);
584                         g_debug ("----Preparing to commit contact %s", address);
585                 } else {
586                         gchar *email_address, *display_address;
587                         GList *email_list = NULL;
588
589                         /* Create new contact and add it to the list */
590                         contact = e_contact_new ();
591                         email_address = modest_text_utils_get_email_address (address);
592                         email_list = g_list_append (email_list, email_address);
593                         e_contact_set (contact, E_CONTACT_EMAIL, email_list);
594                         g_free (email_address);
595                         g_list_free (email_list);
596
597                         display_address = g_strdup (address);
598                         if (display_address) {
599                                 modest_text_utils_get_display_address (display_address);
600                                 if ((display_address[0] != '\0') && (strlen (display_address) != strlen (address)))
601                                         e_contact_set (contact, E_CONTACT_FULL_NAME, (const gpointer)display_address);
602                                 g_free (display_address);
603                         }
604
605                         to_add_contacts = g_list_prepend (to_add_contacts, contact);
606                         g_debug ("----Preparing to add contact %s", address);
607                 }
608
609                 iter = g_slist_next (iter);
610         }
611
612         /* Asynchronously add contacts */
613         if (to_add_contacts)
614                 e_book_async_add_contacts (book, to_add_contacts, NULL, NULL);
615
616         /* Asynchronously commit contacts */
617         if (to_commit_contacts)
618                 e_book_async_commit_contacts (book, to_commit_contacts, NULL, NULL);
619
620         /* Free lists */
621         g_list_free (to_add_contacts);
622         g_list_free (to_commit_contacts);
623
624  frees:
625         if (addresses) {
626                 g_slist_foreach (addresses, (GFunc) g_free, NULL);
627                 g_slist_free (addresses);
628         }
629         if (contacts)
630                 g_list_free (contacts);
631 }
632
633 typedef struct _CheckNamesInfo {
634         GtkWidget *banner;
635         guint show_banner_timeout;
636         guint hide_banner_timeout;
637         gboolean hide;
638         gboolean free_info;
639 } CheckNamesInfo;
640
641 static void
642 hide_check_names_banner (CheckNamesInfo *info)
643 {
644         if (info->show_banner_timeout > 0) {
645                 g_source_remove (info->show_banner_timeout);
646                 info->show_banner_timeout = 0;
647         }
648         if (info->hide_banner_timeout > 0) {
649                 info->hide = TRUE;
650                 return;
651         }
652
653         if (info->banner) {
654                 gtk_widget_destroy (info->banner);
655                 info->banner = NULL;
656                 info->hide = FALSE;
657         }
658
659         if (info->free_info) {
660                 g_slice_free (CheckNamesInfo, info);
661         }
662 }
663
664 static gboolean hide_banner_timeout_handler (CheckNamesInfo *info)
665 {
666         info->hide_banner_timeout = 0;
667         if (info->hide) {
668                 gtk_widget_destroy (info->banner);
669                 info->banner = NULL;
670         }
671         if (info->free_info) {
672                 g_slice_free (CheckNamesInfo, info);
673         }
674         return FALSE;
675 }
676
677 static gboolean show_banner_timeout_handler (CheckNamesInfo *info)
678 {
679         info->show_banner_timeout = 0;
680         info->banner = hildon_banner_show_animation (NULL, NULL, _("mail_ib_checking_names"));
681         info->hide_banner_timeout = g_timeout_add (1000, (GSourceFunc) hide_banner_timeout_handler, (gpointer) info);
682         return FALSE;
683 }
684
685 static void show_check_names_banner (CheckNamesInfo *info)
686 {
687         if (info->hide_banner_timeout > 0) {
688                 g_source_remove (info->hide_banner_timeout);
689                 info->hide_banner_timeout = 0;
690         }
691
692         info->hide = FALSE;
693         if (info->show_banner_timeout > 0)
694                 return;
695
696         if (info->banner == NULL) {
697                 info->show_banner_timeout = g_timeout_add (500, (GSourceFunc) show_banner_timeout_handler, (gpointer) info);
698         }
699 }
700
701 static void clean_check_names_banner (CheckNamesInfo *info)
702 {
703         if (info->hide_banner_timeout) {
704                 info->free_info = TRUE;
705         } else {
706                 if (info->show_banner_timeout) {
707                         g_source_remove (info->show_banner_timeout);
708                 }
709                 if (info->banner)
710                         gtk_widget_destroy (info->banner);
711                 g_slice_free (CheckNamesInfo, info);
712         }
713 }
714
715 void free_resolved_addresses_list (gpointer data,
716                                    gpointer ignored)
717 {
718         GSList *list = (GSList *)data;
719         g_slist_foreach (list, (GFunc) g_free, NULL);
720         g_slist_free (list);
721 }
722
723 gboolean
724 modest_address_book_check_names (ModestRecptEditor *recpt_editor,
725                                  GSList **address_list)
726 {
727         const gchar *recipients = NULL;
728         GSList *start_indexes = NULL, *end_indexes = NULL;
729         GSList *current_start, *current_end;
730         gboolean result = TRUE;
731         GtkTextBuffer *buffer;
732         gint offset_delta = 0;
733         gint last_length;
734         GtkTextIter start_iter, end_iter;
735
736         g_return_val_if_fail (MODEST_IS_RECPT_EDITOR (recpt_editor), FALSE);
737
738         recipients = modest_recpt_editor_get_recipients (recpt_editor);
739         last_length = g_utf8_strlen (recipients, -1);
740         modest_text_utils_get_addresses_indexes (recipients, &start_indexes, &end_indexes);
741
742         if (start_indexes == NULL) {
743                 if (last_length != 0) {
744                         hildon_banner_show_information (NULL, NULL, _("mcen_nc_no_matching_contacts"));
745                         return FALSE;
746                 } else {
747                         return TRUE;
748                 }
749         }
750
751         current_start = start_indexes;
752         current_end = end_indexes;
753         buffer = modest_recpt_editor_get_buffer (recpt_editor);
754
755         while (current_start != NULL) {
756                 gchar *address;
757                 gchar *start_ptr, *end_ptr;
758                 gint start_pos, end_pos;
759                 const gchar *invalid_char_position = NULL;
760                 gboolean store_address = FALSE;
761
762                 start_pos = (*((gint*) current_start->data)) + offset_delta;
763                 end_pos = (*((gint*) current_end->data)) + offset_delta;
764
765                 start_ptr = g_utf8_offset_to_pointer (recipients, start_pos);
766                 end_ptr = g_utf8_offset_to_pointer (recipients, end_pos);
767
768                 address = g_strstrip (g_strndup (start_ptr, end_ptr - start_ptr));
769                 gtk_text_buffer_get_iter_at_offset (buffer, &start_iter, start_pos);
770                 gtk_text_buffer_get_iter_at_offset (buffer, &end_iter, end_pos);
771                 gtk_text_buffer_select_range (buffer, &start_iter, &end_iter);
772
773                 if (!modest_text_utils_validate_recipient (address, &invalid_char_position)) {
774                         if ((invalid_char_position != NULL) && (*invalid_char_position != '\0')) {
775                                 gchar *char_in_string = g_strdup_printf("%c", *invalid_char_position);
776                                 gchar *message = 
777                                         g_strdup_printf(_CS("ckdg_ib_illegal_characters_entered"), 
778                                                         char_in_string);
779                                 g_free (char_in_string);
780                                 hildon_banner_show_information (NULL, NULL, message );
781                                 g_free (message);
782                                 result = FALSE;
783                         } else if (strstr (address, "@") == NULL) {
784                                 /* here goes searching in addressbook */
785                                 gboolean canceled;
786                                 GSList *contact_ids = NULL;
787                                 GSList *resolved_addresses = NULL;
788
789                                 result = resolve_address (address, &resolved_addresses, &contact_ids, &canceled);
790
791                                 if (result) {
792                                         gint new_length;
793
794                                         modest_recpt_editor_replace_with_resolved_recipients (recpt_editor,
795                                                                                               &start_iter, &end_iter,
796                                                                                               resolved_addresses,
797                                                                                               contact_ids);
798                                         g_slist_foreach (contact_ids, (GFunc) g_free, NULL);
799                                         g_slist_foreach (resolved_addresses, free_resolved_addresses_list, NULL);
800                                         g_slist_free (contact_ids);
801                                         g_slist_free (resolved_addresses);
802
803                                         /* update offset delta */
804                                         recipients = modest_recpt_editor_get_recipients (recpt_editor);
805                                         new_length = g_utf8_strlen (recipients, -1);
806                                         offset_delta = offset_delta + new_length - last_length;
807                                         last_length = new_length;
808                                 } else {
809                                         if (canceled) {
810                                                 /* We have to remove the recipient if not resolved */
811                                                 modest_recpt_editor_replace_with_resolved_recipient (recpt_editor,
812                                                                                                      &start_iter, 
813                                                                                                      &end_iter,
814                                                                                                      NULL,
815                                                                                                      NULL);
816                                         } else {
817                                                 /* There is no contact with that name so it's not
818                                                    valid. Don't show any error because it'll be done
819                                                    later */
820                                                 result = FALSE;
821                                         }
822                                 }
823                         } else {
824                                 /* this address is not valid, select it and return control to user showing banner */
825                                 hildon_banner_show_information (NULL, NULL, _("mcen_ib_invalid_email"));
826                                 result = FALSE;
827                         }
828                 } else {
829                         GSList *tags, *node;
830                         gboolean has_recipient = FALSE;
831
832                         tags = gtk_text_iter_get_tags (&start_iter);
833                         for (node = tags; node != NULL; node = g_slist_next (node)) {
834                                 GtkTextTag *tag = GTK_TEXT_TAG (node->data);
835                                 if (g_object_get_data (G_OBJECT (tag), "recipient-tag-id") != NULL) {
836                                         has_recipient = TRUE;
837                                         break;
838                                 }
839                         }
840                         g_slist_free (tags);
841                         if (!has_recipient) {
842                                 GSList * addr_list = NULL;
843
844                                 addr_list = g_slist_prepend (addr_list, address);
845                                 modest_recpt_editor_replace_with_resolved_recipient (recpt_editor,
846                                                                                      &start_iter, &end_iter,
847                                                                                      addr_list,
848                                                                                      "");
849                                 g_slist_free (addr_list);
850                                 store_address = TRUE;
851                         }
852                 }
853
854                 /* so, it seems a valid address */
855                 /* note: adding it the to the addressbook if it did not exist yet,
856                  * and adding it to the recent_list */
857                 if (result && address_list && store_address)
858                         *address_list = g_slist_prepend (*address_list, address);
859                 else
860                         g_free (address);
861
862                 if (result == FALSE)
863                         break;
864
865                 current_start = g_slist_next (current_start);
866                 current_end = g_slist_next (current_end);
867         }
868
869         /* Remove dup's */
870         if (address_list && *address_list)
871                 *address_list = modest_text_utils_remove_duplicate_addresses_list (*address_list);
872
873         if (current_start == NULL) {
874                 gtk_text_buffer_get_end_iter (buffer, &end_iter);
875                 gtk_text_buffer_place_cursor (buffer, &end_iter);
876         }
877
878         g_slist_foreach (start_indexes, (GFunc) g_free, NULL);
879         g_slist_foreach (end_indexes, (GFunc) g_free, NULL);
880         g_slist_free (start_indexes);
881         g_slist_free (end_indexes);
882
883         return result;
884
885 }
886
887 typedef struct _GetContactsInfo {
888         GMainLoop *mainloop;
889         GList *result;
890 } GetContactsInfo;
891
892 static void 
893 get_contacts_for_name_cb (EBook *book, 
894                           EBookStatus status, 
895                           GList *list, 
896                           gpointer userdata)
897 {
898         GetContactsInfo *info = (GetContactsInfo *) userdata;
899
900         if (status == E_BOOK_ERROR_OK)
901                 info->result = list;
902
903         g_main_loop_quit (info->mainloop);
904 }
905
906 static GList *
907 get_contacts_for_name (const gchar *name)
908 {
909         EBookQuery *book_query = NULL;
910         GList *result;
911         gchar *unquoted;
912         GetContactsInfo *info;
913         EBookQuery *queries[10];
914
915         if (name == NULL)
916                 return NULL;
917
918         unquoted = unquote_string (name);
919
920         queries[0] = e_book_query_field_test (E_CONTACT_FULL_NAME, E_BOOK_QUERY_BEGINS_WITH, unquoted);
921         queries[1] = e_book_query_field_test (E_CONTACT_GIVEN_NAME, E_BOOK_QUERY_BEGINS_WITH, unquoted);
922         queries[2] = e_book_query_field_test (E_CONTACT_FAMILY_NAME, E_BOOK_QUERY_BEGINS_WITH, unquoted);
923         queries[3] = e_book_query_field_test (E_CONTACT_NICKNAME, E_BOOK_QUERY_BEGINS_WITH, unquoted);
924         queries[4] = e_book_query_field_test (E_CONTACT_EMAIL_1, E_BOOK_QUERY_BEGINS_WITH, unquoted);
925         queries[5] = e_book_query_field_test (E_CONTACT_EMAIL_2, E_BOOK_QUERY_BEGINS_WITH, unquoted);
926         queries[6] = e_book_query_field_test (E_CONTACT_EMAIL_3, E_BOOK_QUERY_BEGINS_WITH, unquoted);
927         queries[7] = e_book_query_field_test (E_CONTACT_EMAIL_4, E_BOOK_QUERY_BEGINS_WITH, unquoted);
928         queries[8] = e_book_query_field_test (E_CONTACT_EMAIL, E_BOOK_QUERY_BEGINS_WITH, unquoted);
929         queries[9] = e_book_query_field_test (E_CONTACT_NAME, E_BOOK_QUERY_BEGINS_WITH, unquoted);
930         book_query = e_book_query_or (10, queries, TRUE);
931
932         g_free (unquoted);
933
934         /* TODO: Make it launch a mainloop */
935         info = g_slice_new (GetContactsInfo);
936         info->mainloop = g_main_loop_new (NULL, FALSE);
937         info->result = NULL;
938         if (e_book_async_get_contacts (book, book_query, get_contacts_for_name_cb, info) == 0) {
939                 GDK_THREADS_LEAVE ();
940                 g_main_loop_run (info->mainloop);
941                 GDK_THREADS_ENTER ();
942         } 
943         result = info->result;
944         e_book_query_unref (book_query);
945         g_main_loop_unref (info->mainloop);
946         g_slice_free (GetContactsInfo, info);
947
948         return result;
949 }
950
951
952 static GList *
953 select_contacts_for_name_dialog (const gchar *name)
954 {
955         EBookQuery *book_query = NULL;
956         EBookView *book_view = NULL;
957         GList *result = NULL;
958         gchar *unquoted;
959         EBookQuery *queries[10];
960
961         unquoted = unquote_string (name);
962
963         queries[0] = e_book_query_field_test (E_CONTACT_FULL_NAME, E_BOOK_QUERY_BEGINS_WITH, unquoted);
964         queries[1] = e_book_query_field_test (E_CONTACT_GIVEN_NAME, E_BOOK_QUERY_BEGINS_WITH, unquoted);
965         queries[2] = e_book_query_field_test (E_CONTACT_FAMILY_NAME, E_BOOK_QUERY_BEGINS_WITH, unquoted);
966         queries[3] = e_book_query_field_test (E_CONTACT_NICKNAME, E_BOOK_QUERY_BEGINS_WITH, unquoted);
967         queries[4] = e_book_query_field_test (E_CONTACT_EMAIL_1, E_BOOK_QUERY_BEGINS_WITH, unquoted);
968         queries[5] = e_book_query_field_test (E_CONTACT_EMAIL_2, E_BOOK_QUERY_BEGINS_WITH, unquoted);
969         queries[6] = e_book_query_field_test (E_CONTACT_EMAIL_3, E_BOOK_QUERY_BEGINS_WITH, unquoted);
970         queries[7] = e_book_query_field_test (E_CONTACT_EMAIL_4, E_BOOK_QUERY_BEGINS_WITH, unquoted);
971         queries[8] = e_book_query_field_test (E_CONTACT_EMAIL, E_BOOK_QUERY_BEGINS_WITH, unquoted);
972         queries[9] = e_book_query_field_test (E_CONTACT_NAME, E_BOOK_QUERY_BEGINS_WITH, unquoted);
973         book_query = e_book_query_or (10, queries, TRUE);
974         e_book_get_book_view (book, book_query, NULL, -1, &book_view, NULL);
975         e_book_query_unref (book_query);
976
977         if (book_view) {
978                 GtkWidget *contact_dialog = NULL;
979                 osso_abook_list_store_set_book_view (OSSO_ABOOK_LIST_STORE (contact_model), book_view);
980                 e_book_view_start (book_view);
981
982                 /* TODO: figure out how to make the contact chooser modal */
983                 contact_dialog = osso_abook_contact_chooser_new_with_capabilities (NULL,
984                                                                                    _AB("addr_ti_dia_select_contacts"),
985                                                                                    OSSO_ABOOK_CAPS_EMAIL,
986                                                                                    OSSO_ABOOK_CONTACT_ORDER_NAME);
987                 /* Enable multiselection */
988                 osso_abook_contact_chooser_set_maximum_selection (OSSO_ABOOK_CONTACT_CHOOSER (contact_dialog),
989                                                                   G_MAXUINT);
990                 osso_abook_contact_chooser_set_model (OSSO_ABOOK_CONTACT_CHOOSER (contact_dialog),
991                                                       contact_model);
992
993                 if (gtk_dialog_run (GTK_DIALOG (contact_dialog)) == GTK_RESPONSE_OK)
994                         result = osso_abook_contact_chooser_get_selection (OSSO_ABOOK_CONTACT_CHOOSER (contact_dialog));
995                 e_book_view_stop (book_view);
996                 g_object_unref (book_view);
997                 gtk_widget_destroy (contact_dialog);
998         }
999         g_free (unquoted);
1000
1001         return result;
1002 }
1003
1004 static gboolean
1005 resolve_address (const gchar *address, 
1006                  GSList **resolved_addresses, 
1007                  GSList **contact_ids,
1008                  gboolean *canceled)
1009 {
1010         GList *resolved_contacts;
1011         CheckNamesInfo *info;;
1012
1013         g_return_val_if_fail (canceled, FALSE);
1014
1015         *resolved_addresses = NULL;
1016         *contact_ids = NULL;
1017         *canceled = FALSE;
1018         info = g_slice_new0 (CheckNamesInfo);
1019         show_check_names_banner (info);
1020
1021         contact_model = osso_abook_contact_model_get_default ();
1022         if (!open_addressbook ()) {
1023                 hide_check_names_banner (info);
1024                 if (contact_model) {
1025                         g_object_unref (contact_model);
1026                         contact_model = NULL;
1027                 }
1028                 clean_check_names_banner (info);
1029                 return FALSE;
1030         }
1031
1032         resolved_contacts = get_contacts_for_name (address);
1033         hide_check_names_banner (info);
1034
1035         if (resolved_contacts == NULL) {
1036                 /* no matching contacts for the search string */
1037                 modest_platform_run_information_dialog (NULL, _("mcen_nc_no_matching_contacts"), FALSE);
1038                 clean_check_names_banner (info);
1039                 return FALSE;
1040         }
1041
1042         if (g_list_length (resolved_contacts) > 1) {
1043                 /* show a dialog to select the contact from the resolved ones */
1044                 g_list_free (resolved_contacts);
1045
1046                 resolved_contacts = select_contacts_for_name_dialog (address);
1047         }
1048
1049         /* get the resolved contacts (can be no contact) */
1050         if (resolved_contacts) {
1051                 GList *node;
1052                 gboolean found = FALSE;
1053
1054                 for (node = resolved_contacts; node != NULL; node = g_list_next (node)) {
1055                         EContact *contact = (EContact *) node->data;
1056                         GSList *resolved;
1057                         gchar *contact_id;
1058
1059                         resolved = get_recipients_for_given_contact (contact, canceled);
1060                         if (resolved) {
1061                                 contact_id = g_strdup (e_contact_get_const (contact, E_CONTACT_UID));
1062                                 *contact_ids = g_slist_append (*contact_ids, contact_id);
1063                                 found = TRUE;
1064                                 *resolved_addresses = g_slist_append (*resolved_addresses, resolved);
1065                         }
1066                 }
1067
1068                 g_list_free (resolved_contacts);
1069                 clean_check_names_banner (info);
1070
1071                 return found;
1072         } else {
1073                 /* cancelled dialog to select more than one contact or
1074                  * selected no contact */
1075                 clean_check_names_banner (info);
1076                 return FALSE;
1077         }
1078
1079 }
1080
1081 static gchar *
1082 unquote_string (const gchar *str)
1083 {
1084         GString *buffer;
1085         gchar *p;
1086
1087         if (str == NULL)
1088                 return NULL;
1089
1090         buffer = g_string_new_len (NULL, strlen (str));
1091         for (p = (gchar *) str; *p != '\0'; p = g_utf8_next_char (p)) {
1092                 if (*p == '"') {
1093                         p = g_utf8_next_char (p);
1094                         while ((*p != '\0')&&(*p != '"')) {
1095                                 if (*p == '\\') {
1096                                         g_string_append_unichar (buffer, g_utf8_get_char (p));
1097                                         p = g_utf8_next_char (p);
1098
1099                                 }
1100                                 g_string_append_unichar (buffer, g_utf8_get_char (p));
1101                                 p = g_utf8_next_char (p);
1102                         }
1103                 } else {
1104                         g_string_append_unichar (buffer, g_utf8_get_char (p));
1105                 }
1106         }
1107
1108         return g_string_free (buffer, FALSE);
1109
1110 }
1111
1112 gboolean
1113 modest_address_book_has_address (const gchar *address)
1114 {
1115         GList *contacts = NULL;
1116         GError *err = NULL;
1117         gchar *email;
1118         gboolean result;
1119         OssoABookAggregator *roster;
1120
1121         g_return_val_if_fail (address, FALSE);
1122
1123         if (!book) {
1124                 if (!open_addressbook ()) {
1125                         g_return_val_if_reached (FALSE);
1126                 }
1127         }
1128         g_return_val_if_fail (book, FALSE);
1129
1130         email = modest_text_utils_get_email_address (address);
1131
1132         roster = (OssoABookAggregator *) osso_abook_aggregator_get_default (NULL);
1133         contacts = osso_abook_aggregator_find_contacts_for_email_address (roster, email);
1134         if (!contacts) {
1135                 if (err)
1136                         g_error_free (err);
1137                 g_free (email);
1138                 return FALSE;
1139         }
1140
1141         if (contacts) {
1142                 g_list_free (contacts);
1143                 result = TRUE;
1144         }
1145
1146         g_free (email);
1147
1148         return result;
1149 }
1150
1151 const gchar *
1152 modest_address_book_get_my_name ()
1153 {
1154         OssoABookSelfContact *self_contact = osso_abook_self_contact_get_default ();
1155
1156         /* We are not using osso_abook_contact_get_display_name
1157            because that method fallbacks to another fields if the name
1158            is not defined */
1159         if (self_contact)
1160                 return e_contact_get ((EContact *) self_contact, E_CONTACT_FULL_NAME);
1161         else
1162                 return NULL;
1163 }
1164
1165 void
1166 modest_address_book_init (void)
1167 {
1168         open_addressbook ();
1169 }
1170
1171 void
1172 modest_address_book_add_address_list (GSList *address_list)
1173 {
1174         EBookQuery **queries, *composite_query;
1175         gint num_add, i;
1176
1177         g_return_if_fail (address_list);
1178
1179         if (!book)
1180                 if (!open_addressbook ())
1181                         g_return_if_reached ();
1182
1183         /* Create the list of queries */
1184         num_add = g_slist_length (address_list);
1185         queries = g_malloc0 (sizeof (EBookQuery *) * num_add);
1186         for (i = 0; i < num_add; i++) {
1187                 gchar *email;
1188
1189                 email = modest_text_utils_get_email_address (g_slist_nth_data (address_list, i));
1190                 queries[i] = e_book_query_field_test (E_CONTACT_EMAIL, E_BOOK_QUERY_IS, email);
1191                 g_free (email);
1192         }
1193
1194         /* Create the query */
1195         composite_query = e_book_query_or (num_add, queries, TRUE);
1196
1197         /* Asynchronously retrieve contacts */
1198         e_book_async_get_contacts (book, composite_query, async_get_contacts_cb, address_list);
1199
1200         /* Frees. This will unref the subqueries as well */
1201         e_book_query_unref (composite_query);
1202 }