* Fixes NB#97235, show "check names" banner
[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
53 static OssoABookContactModel *contact_model =  NULL;
54 static EBook *book = NULL;
55 static EBookView * book_view = NULL;
56
57 static GSList *get_recipients_for_given_contact(EContact * contact);
58 static void commit_contact(EContact * contact, gboolean is_new);
59 static gchar *get_email_addr_from_user(const gchar * given_name);
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);
63 static GSList *select_email_addrs_for_contact(GList * email_addr_list);
64 static gboolean resolve_address (const gchar *address, GSList **resolved_addresses, gchar **contact_id);
65 static gchar *unquote_string (const gchar *str);
66
67
68 static void
69 unref_gobject (GObject *obj)
70 {
71         if (obj)
72                 g_object_unref (obj);
73 }
74         
75
76 static void
77 get_book_view_cb (EBook *book, EBookStatus status, EBookView *bookview, gpointer data)
78 {
79         if (status != E_BOOK_ERROR_OK) {
80                 g_object_unref (book);
81                 book = NULL;
82                 return;
83         }
84         book_view = bookview;
85
86         if (contact_model)
87 #if MODEST_ABOOK_API < 4
88                 osso_abook_tree_model_set_book_view (OSSO_ABOOK_TREE_MODEL (contact_model),
89                                                      book_view);
90 #else /* MODEST_ABOOK_API < 4 */
91                 osso_abook_list_store_set_book_view (OSSO_ABOOK_LIST_STORE (contact_model),
92                                                      book_view);
93 #endif /* MODEST_ABOOK_API < 4 */
94
95         e_book_view_start (book_view);
96 }
97
98 static void
99 book_open_cb (EBook *view, EBookStatus status, gpointer data)
100 {
101         EBookQuery *query = NULL;
102
103         if (status != E_BOOK_ERROR_OK) {
104                 g_object_unref (book);
105                 book = NULL;
106                 return;
107         }
108         query = e_book_query_any_field_contains ("");
109         e_book_async_get_book_view (book, query, NULL, -1, get_book_view_cb, NULL);
110         e_book_query_unref (query);
111 }
112
113 static gboolean 
114 open_addressbook ()
115 {
116         book = e_book_new_system_addressbook (NULL);
117         if (!book)
118                 return FALSE;
119
120         if (e_book_async_open (book, FALSE, book_open_cb, NULL) != E_BOOK_ERROR_OK)
121                 return FALSE;
122
123         return TRUE; /* FIXME */        
124 }
125
126 static gboolean
127 open_addressbook_sync ()
128 {
129         book = e_book_new_system_addressbook (NULL);
130         if (!book)
131                 return FALSE;
132
133         return e_book_open (book, FALSE, NULL);
134 }
135
136 void
137 modest_address_book_add_address (const gchar *address)
138 {
139         GtkWidget *dialog = NULL;
140         gchar *email_address;
141         EVCardAttribute *attribute;
142
143         if (!open_addressbook ()) {
144                 return;
145         }
146
147         email_address = modest_text_utils_get_email_address (address);
148         
149         attribute = e_vcard_attribute_new (NULL, EVC_EMAIL);
150         e_vcard_attribute_add_value (attribute, email_address);
151         dialog = osso_abook_temporary_contact_dialog_new (NULL, book, attribute, NULL);
152         gtk_dialog_run (GTK_DIALOG (dialog));
153
154         gtk_widget_destroy (dialog);
155
156         e_vcard_attribute_free (attribute);
157         g_free (email_address);
158
159 }
160
161 void
162 modest_address_book_select_addresses (ModestRecptEditor *recpt_editor)
163 {
164 #if MODEST_ABOOK_API < 4
165         GtkWidget *contact_view = NULL;
166         GtkWidget *contact_dialog;
167         GtkWidget *toplevel;
168 #else /* MODEST_ABOOK_API < 4 */
169         GtkWidget *contact_chooser = NULL;
170 #endif /* MODEST_ABOOK_API < 4 */
171
172         GList *contacts_list = NULL;
173         GSList *email_addrs_per_contact = NULL;
174         gchar *econtact_id;
175         gboolean focus_recpt_editor = FALSE;
176
177         g_return_if_fail (MODEST_IS_RECPT_EDITOR (recpt_editor));
178
179 #if MODEST_ABOOK_API < 4
180         if (!open_addressbook ()) {
181                 if (contact_model) {
182                         g_object_unref (contact_model);
183                         contact_model = NULL;
184                 }
185                 return;
186         }
187         contact_model = osso_abook_contact_model_new ();
188
189         contact_view = osso_abook_contact_selector_new_basic (contact_model);
190         osso_abook_contact_selector_set_minimum_selection (OSSO_ABOOK_CONTACT_SELECTOR (contact_view), 1);
191
192         contact_dialog = osso_abook_select_dialog_new (OSSO_ABOOK_TREE_VIEW (contact_view));
193         toplevel = gtk_widget_get_toplevel (GTK_WIDGET (recpt_editor));
194         modest_window_mgr_set_modal (modest_runtime_get_window_mgr (), GTK_WINDOW (contact_dialog), GTK_WINDOW (toplevel));
195
196         gtk_widget_show (contact_dialog);
197
198         if (gtk_dialog_run (GTK_DIALOG (contact_dialog)) == GTK_RESPONSE_OK) {
199                 contacts_list = 
200                         osso_abook_contact_selector_get_extended_selection (OSSO_ABOOK_CONTACT_SELECTOR
201                                                                              (contact_view));
202         }
203 #else /* MODEST_ABOOK_API < 4 */
204         /* TODO: figure out how to make the contact chooser modal */
205         contact_chooser = osso_abook_contact_chooser_new_with_capabilities (NULL,
206                                                                             _AB("addr_ti_dia_select_contacts"),
207                                                                             OSSO_ABOOK_CAPS_EMAIL, 
208                                                                             OSSO_ABOOK_CONTACT_ORDER_NAME);
209         /* Enable multiselection */
210         osso_abook_contact_chooser_set_maximum_selection (OSSO_ABOOK_CONTACT_CHOOSER (contact_chooser),
211                                                           G_MAXUINT);
212
213         if (gtk_dialog_run (GTK_DIALOG (contact_chooser)) == GTK_RESPONSE_OK)
214                 contacts_list = osso_abook_contact_chooser_get_selection (OSSO_ABOOK_CONTACT_CHOOSER (contact_chooser));
215         gtk_widget_destroy (contact_chooser);
216 #endif
217
218         if (contacts_list) {
219                 GList *node;
220
221                 for (node = contacts_list; node != NULL; node = g_list_next (node)) {
222                         EContact *contact = (EContact *) node->data;
223
224                         email_addrs_per_contact = get_recipients_for_given_contact (contact);
225                         if (email_addrs_per_contact) {
226                                 econtact_id = (gchar *) e_contact_get_const (contact, E_CONTACT_UID);
227                                 modest_recpt_editor_add_resolved_recipient (MODEST_RECPT_EDITOR (recpt_editor), 
228                                                                             email_addrs_per_contact, econtact_id);
229                                 g_slist_foreach (email_addrs_per_contact, (GFunc) g_free, NULL);
230                                 g_slist_free (email_addrs_per_contact);
231                                 email_addrs_per_contact = NULL;
232                                 focus_recpt_editor = TRUE;
233                         }
234                 }
235                 g_list_free (contacts_list);
236         }
237
238 #if MODEST_ABOOK_API < 4
239         if (contact_model) {
240                 g_object_unref (contact_model);
241                 contact_model = NULL;
242         }
243
244         gtk_widget_destroy (contact_dialog);
245 #endif
246
247         if (focus_recpt_editor)
248                 modest_recpt_editor_grab_focus (MODEST_RECPT_EDITOR (recpt_editor));
249
250 }
251
252 /**
253  * This function returns the resolved recipients for a given EContact.
254  * If no e-mail address is defined, it launches 'Add e-mail address to contact'
255  * dialog to obtain one. If multiple e-mail addresses are found, it launches
256  * 'Select e-mail address' dialog to allow user to select one or more e-mail
257  * addresses for that contact.
258  *
259  * @param  Contact of type #EContact
260  * @return List of resolved recipient strings, to be freed by calling function.
261  */
262 static GSList *get_recipients_for_given_contact(EContact * contact)
263 {
264         gchar *givenname = NULL;
265         gchar *familyname = NULL;
266         gchar *nickname = NULL;
267         gchar *emailid = NULL;
268         const gchar *display_name = NULL;
269         GList *list = NULL;
270         gchar *formatted_string = NULL;
271         gboolean email_not_present = FALSE;
272         GSList *formattedlist = NULL, *selected_email_addr_list = NULL, *node = NULL;
273
274         if (!contact) {
275                 return NULL;
276         }
277
278         givenname = (gchar *) e_contact_get_const(contact, E_CONTACT_GIVEN_NAME);
279         familyname = (gchar *) e_contact_get_const(contact, E_CONTACT_FAMILY_NAME);
280         nickname = (gchar *) e_contact_get_const(contact, E_CONTACT_NICKNAME);
281         if (!nickname)
282                 nickname = "";
283         list = (GList *) e_contact_get(contact, E_CONTACT_EMAIL);
284
285         if (!list) {
286                 email_not_present = TRUE;
287         }
288
289         if (list && g_list_length(list) == 1) {
290                 if (list->data == NULL || g_utf8_strlen(list->data, -1) == 0) {
291                         email_not_present = TRUE;
292                 } else {
293                         emailid = g_strstrip(g_strdup(list->data));
294                         if (g_utf8_strlen(emailid, -1) == 0) {
295                                 g_free(emailid);
296                                 email_not_present = TRUE;
297                         }
298                 }
299         }
300
301         /*Launch the 'Add e-mail addr to contact' dialog if required */
302         if (email_not_present) {
303 #if MODEST_ABOOK_API < 4
304                 display_name = osso_abook_contact_get_display_name(contact);            
305 #else
306                 OssoABookContact *abook_contact;
307                
308                 abook_contact = osso_abook_contact_new_from_template (contact);
309                 display_name = osso_abook_contact_get_display_name(abook_contact);
310 #endif
311
312                 emailid = get_email_addr_from_user(display_name);
313                 if (emailid) {
314                         e_contact_set(contact, E_CONTACT_EMAIL_1, emailid);
315                         commit_contact(contact, FALSE);
316                 }
317 #if MODEST_ABOOK_API >= 4
318                 g_object_unref (abook_contact);
319 #endif
320         }
321
322         if (emailid) {
323                 if (givenname || familyname)
324                         formatted_string =
325                             ui_get_formatted_email_id(givenname, familyname, emailid);
326                 else
327                         formatted_string = g_strdup(emailid);
328                 formattedlist = g_slist_append(formattedlist, formatted_string);
329                 g_free(emailid);
330         }
331
332         /*Launch the 'Select e-mail address' dialog if required */
333         if (g_list_length(list) > 1) {
334                 selected_email_addr_list = select_email_addrs_for_contact(list);
335                 for (node = selected_email_addr_list; node != NULL; node = node->next) {
336                         if (givenname || familyname)
337                                 formatted_string =
338                                     ui_get_formatted_email_id(givenname, familyname, node->data);
339                         else
340                                 formatted_string = g_strdup(node->data);
341                         formattedlist = g_slist_append(formattedlist, formatted_string);
342                 }
343                 if (selected_email_addr_list) {
344                         g_slist_foreach(selected_email_addr_list, (GFunc) g_free, NULL);
345                         g_slist_free(selected_email_addr_list);
346                 }
347         }
348
349         if (list) {
350                 g_list_foreach(list, (GFunc) g_free, NULL);
351                 g_list_free(list);
352         }
353
354         return formattedlist;
355 }
356
357 /**
358  * This is a helper function to commit a EContact to Address_Book application.
359  *
360  * @param  contact  Contact of type #EContact
361  * @return void
362  */
363 static void 
364 commit_contact(EContact * contact, gboolean is_new)
365 {
366         g_return_if_fail (contact);
367         g_return_if_fail (book);
368
369         if (!contact || !book)
370                 return;
371
372 #if MODEST_ABOOK_API < 4
373         osso_abook_contact_commit(contact, is_new, book);
374 #else
375         if (OSSO_ABOOK_IS_CONTACT (contact)) {
376                 osso_abook_contact_commit(OSSO_ABOOK_CONTACT(contact), is_new, book, NULL);
377         } else {
378                 if (is_new)
379                         e_book_add_contact (book, contact, NULL);
380                 else
381                         e_book_commit_contact (book, contact, NULL);
382         }
383 #endif /* MODEST_ABOOK_API < 2 */
384 }
385
386 /**
387  * This is a helper function used to launch 'Add e-mail address to contact' dialog
388  * after showing appropriate notification, when there is no e-mail address defined
389  * for a selected contact.
390  *
391  * @param  given_name  Given name of the contact
392  * @param  family_name  Family name of the contact
393  * @return E-mail address string entered by user, to be freed by calling function.
394  */
395 static gchar *
396 get_email_addr_from_user(const gchar * given_name)
397 {
398         gchar *notification = NULL;
399         gchar *email_addr = NULL;
400         GtkWidget *note;
401         gboolean note_response;
402
403
404         notification = g_strdup_printf(_("mcen_nc_email_address_not_defined"), given_name);
405
406         note = hildon_note_new_confirmation (NULL, notification);
407         note_response = gtk_dialog_run (GTK_DIALOG(note));
408         gtk_widget_destroy (note);
409         g_free(notification);
410
411         if (note_response == GTK_RESPONSE_OK) {
412                 email_addr = run_add_email_addr_to_contact_dlg(given_name);
413         }
414
415         return email_addr;
416 }
417
418 /**
419 This function is used to get the formated email id with given name and sur name
420 in the format "GIVENNAME SURNAME <EMAIL ADDRESS>".
421 @param current_given_name    to hold the given name
422 @param current_sur_name      to hold the sur name
423 @param current_email_id      to hold the email id. 
424 @return gchar* string to be freed by calling function
425 */
426 static gchar *
427 ui_get_formatted_email_id(gchar * current_given_name,
428                           gchar * current_sur_name, gchar * current_email_id)
429 {
430         GString *email_id_str = NULL;
431
432         email_id_str = g_string_new(NULL);
433
434         if ((current_given_name != NULL) && ((strlen(current_given_name) != 0))
435             && (current_sur_name != NULL) && ((strlen(current_sur_name) != 0))) {
436                 g_string_append_printf(email_id_str, "%s %s", current_given_name, current_sur_name);
437         } else if ((current_given_name != NULL) && (strlen(current_given_name) != 0)) {
438                 g_string_append_printf(email_id_str, "%s", current_given_name);
439         } else if ((current_sur_name != NULL) && (strlen(current_sur_name) != 0)) {
440                 g_string_append_printf(email_id_str, "%s", current_sur_name);
441         }
442         if (g_utf8_strchr (email_id_str->str, -1, ' ')) {
443                 g_string_prepend_c (email_id_str, '\"');
444                 g_string_append_c (email_id_str, '\"');
445         }
446         g_string_append_printf (email_id_str, " %c%s%c", '<', current_email_id, '>');
447         return g_string_free (email_id_str, FALSE);
448 }
449
450 /**
451  * This is a helper function used to create & run 'Add e-mail address to contact' dialog.
452  * It allows user to enter an e-mail address, and shows appropriate infonote if the
453  * entered string is not a valid e-mail address.
454  *
455  * @param  contact_name  Full name of the contact
456  * @return E-mail address string entered by user, to be freed by calling function.
457  */
458 static gchar *
459 run_add_email_addr_to_contact_dlg(const gchar * contact_name)
460 {
461         GtkWidget *add_email_addr_to_contact_dlg = NULL;
462         GtkSizeGroup *size_group = NULL;
463         GtkWidget *cptn_cntrl = NULL;
464         GtkWidget *name_label = NULL;
465         GtkWidget *email_entry = NULL;
466         gint result = -1;
467         gchar *new_email_addr = NULL;
468         gboolean run_dialog = TRUE;
469
470         add_email_addr_to_contact_dlg =
471             gtk_dialog_new_with_buttons(_("mcen_ti_add_email_title"), NULL,
472                                         GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
473                                         _HL("wdgt_bd_done"), GTK_RESPONSE_ACCEPT, NULL);
474         gtk_dialog_set_has_separator(GTK_DIALOG(add_email_addr_to_contact_dlg), FALSE);
475         /*Set app_name & state_save related tags to the window */
476
477         size_group = gtk_size_group_new(GTK_SIZE_GROUP_HORIZONTAL);
478         name_label = gtk_label_new(contact_name);
479         gtk_misc_set_alignment(GTK_MISC(name_label), 0, 0);
480         cptn_cntrl =
481             hildon_caption_new(size_group, _("mcen_ia_add_email_name"), name_label, NULL,
482                                HILDON_CAPTION_OPTIONAL);
483         gtk_box_pack_start(GTK_BOX(GTK_DIALOG(add_email_addr_to_contact_dlg)->vbox), cptn_cntrl,
484                            FALSE, FALSE, 0);
485
486         email_entry = gtk_entry_new();
487         cptn_cntrl =
488             hildon_caption_new(size_group, _("mcen_fi_add_email_name"), email_entry, NULL,
489                                HILDON_CAPTION_OPTIONAL);
490         hildon_gtk_entry_set_input_mode(GTK_ENTRY(email_entry), HILDON_GTK_INPUT_MODE_FULL);
491         gtk_box_pack_start(GTK_BOX(GTK_DIALOG(add_email_addr_to_contact_dlg)->vbox), cptn_cntrl,
492                            TRUE, TRUE, 0);
493
494         gtk_widget_show_all(add_email_addr_to_contact_dlg);
495
496         while (run_dialog) {
497                 run_dialog = FALSE;
498                 gtk_widget_grab_focus(email_entry);
499                 result = gtk_dialog_run(GTK_DIALOG(add_email_addr_to_contact_dlg));
500
501                 if (result == GTK_RESPONSE_ACCEPT) {
502                         const gchar *invalid_char_offset = NULL;
503                         new_email_addr = g_strdup(gtk_entry_get_text(GTK_ENTRY(email_entry)));
504                         new_email_addr = g_strstrip(new_email_addr);
505                         if (!modest_text_utils_validate_email_address (new_email_addr, &invalid_char_offset)) {
506                                 gtk_widget_grab_focus(email_entry);
507                                 if ((invalid_char_offset != NULL)&&(*invalid_char_offset != '\0')) {
508                                         gchar *char_in_string = g_strdup_printf ("%c", *invalid_char_offset);
509                                         gchar *message = g_strdup_printf(
510                                                 _CS("ckdg_ib_illegal_characters_entered"), 
511                                                 char_in_string);
512                                         hildon_banner_show_information (
513                                                 add_email_addr_to_contact_dlg, NULL, message );
514                                         g_free (message);
515                                 } else {
516                                         hildon_banner_show_information (add_email_addr_to_contact_dlg, NULL, _("mcen_ib_invalid_email"));
517                                         run_dialog = TRUE;
518                                 }
519                                 gtk_editable_select_region((GtkEditable *) email_entry, 0, -1);
520                                 g_free(new_email_addr);
521                                 new_email_addr = NULL;
522                         }
523                 }
524         }
525
526         gtk_widget_destroy(add_email_addr_to_contact_dlg);
527
528         return new_email_addr;
529 }
530
531 /**
532  * This is helper function to create & run 'Select e-mail address' dialog, used when
533  * multiple e-mail addresses are found for a selected contact. It allows user to select
534  * one or more e-mail addresses for that contact.
535  *
536  * @param  email_addr_list  List of e-mail addresses for that contact
537  * @return List of user selected e-mail addresses, to be freed by calling function.
538  */
539 static GSList *
540 select_email_addrs_for_contact(GList * email_addr_list)
541 {
542         GtkWidget *select_email_addr_dlg = NULL;
543         GtkWidget *view = NULL, *scrolledwindow = NULL;
544         GtkTreeSelection *selection = NULL;
545         GtkCellRenderer *renderer = NULL;
546         GtkTreeViewColumn *col = NULL;
547         GtkListStore *list_store = NULL;
548         GtkTreeModel *model = NULL;
549         GtkTreeIter iter;
550         GList *pathslist = NULL, *node = NULL;
551         gint result = -1;
552         gchar *email_addr = NULL;
553         GSList *selected_email_addr_list = NULL;
554
555         if (!email_addr_list)
556                 return NULL;
557
558         select_email_addr_dlg =
559             gtk_dialog_new_with_buttons(_("mcen_ti_select_email_title"),
560                                         NULL,
561                                         GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
562                                         _HL("wdgt_bd_done"), GTK_RESPONSE_ACCEPT, NULL);
563         gtk_dialog_set_has_separator(GTK_DIALOG(select_email_addr_dlg), FALSE);
564
565         /* Make the window approximately big enough, because it doesn't resize to be big enough 
566          * for the window title text: */
567         gtk_window_set_default_size (GTK_WINDOW (select_email_addr_dlg), MODEST_DIALOG_WINDOW_MAX_HEIGHT, -1);
568
569         scrolledwindow = gtk_scrolled_window_new(NULL, NULL);
570         gtk_box_pack_start(GTK_BOX(GTK_DIALOG(select_email_addr_dlg)->vbox), scrolledwindow, TRUE,
571                            TRUE, 0);
572         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwindow), GTK_POLICY_AUTOMATIC,
573                                        GTK_POLICY_AUTOMATIC);
574
575         view = gtk_tree_view_new();
576         col = gtk_tree_view_column_new();
577         renderer = gtk_cell_renderer_text_new();
578         gtk_tree_view_append_column(GTK_TREE_VIEW(view), col);
579         gtk_tree_view_column_pack_start(col, renderer, TRUE);
580         gtk_tree_view_column_add_attribute(col, renderer, "text", 0);
581         selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(view));
582         gtk_tree_selection_set_mode(selection, GTK_SELECTION_MULTIPLE);
583         gtk_container_add(GTK_CONTAINER(scrolledwindow), view);
584
585         list_store = gtk_list_store_new(1, G_TYPE_STRING);
586         model = GTK_TREE_MODEL(list_store);
587         gtk_tree_view_set_model(GTK_TREE_VIEW(view), model);
588
589         for (node = email_addr_list; node != NULL && node->data != NULL; node = node->next) {
590                 email_addr = g_strstrip(g_strdup(node->data));
591                 gtk_list_store_append(list_store, &iter);
592                 gtk_list_store_set(list_store, &iter, 0, email_addr, -1);
593                 g_free(email_addr);
594         }
595         gtk_tree_model_get_iter_first (GTK_TREE_MODEL (list_store), &iter);
596         gtk_tree_selection_select_iter (selection, &iter);
597
598         gtk_widget_show_all(select_email_addr_dlg);
599         result = gtk_dialog_run(GTK_DIALOG(select_email_addr_dlg));
600
601         if (result == GTK_RESPONSE_ACCEPT) {
602                 pathslist = gtk_tree_selection_get_selected_rows(selection, NULL);
603                 for (node = pathslist; node != NULL; node = node->next) {
604                         if (gtk_tree_model_get_iter(model, &iter, (GtkTreePath *) node->data)) {
605                                 gtk_tree_model_get(model, &iter, 0, &email_addr, -1);
606                                 selected_email_addr_list =
607                                     g_slist_append(selected_email_addr_list, g_strdup(email_addr));
608                                 g_free(email_addr);
609                         }
610                 }
611         }
612
613         gtk_list_store_clear(list_store);
614         gtk_widget_destroy(select_email_addr_dlg);
615         return selected_email_addr_list;
616 }
617
618
619 static gboolean /* make this public? */
620 add_to_address_book (const gchar* address)
621 {
622         EBookQuery *query;
623         GList *contacts = NULL;
624         GError *err = NULL;
625         gchar *email;
626         
627         g_return_val_if_fail (address, FALSE);
628         
629         if (!book) {
630                 if (!open_addressbook ()) {
631                         g_return_val_if_reached (FALSE);
632                 }
633         }
634         
635         g_return_val_if_fail (book, FALSE);
636
637         email = modest_text_utils_get_email_address (address);
638         
639         query = e_book_query_field_test (E_CONTACT_EMAIL, E_BOOK_QUERY_IS, email);
640         if (!e_book_get_contacts (book, query, &contacts, &err)) {
641                 g_printerr ("modest: failed to get contacts: %s",
642                             err ? err->message : "<unknown>");
643                 if (err)
644                         g_error_free (err);
645                 return FALSE;
646         }
647         e_book_query_unref (query);
648         
649         /*  we need to 'commit' it, even if we already found the email
650          * address in the addressbook; thus, it will show up in the 'recent list' */
651         if (contacts)  {                
652                 g_debug ("%s already in the address book", address);
653                 commit_contact ((EContact*)contacts->data, FALSE);
654                 
655                 g_list_foreach (contacts, (GFunc)unref_gobject, NULL);
656                 g_list_free (contacts);
657
658         } else {
659                 /* it's not yet in the addressbook, add it now! */
660                 EContact *new_contact = e_contact_new ();
661                 gchar *display_address;
662                 display_address = g_strdup (address);
663                 if (display_address) {
664                         modest_text_utils_get_display_address (display_address);
665                         if ((display_address[0] != '\0') && (strlen (display_address) != strlen (address)))
666                                 e_contact_set (new_contact, E_CONTACT_FULL_NAME, (const gpointer)display_address);
667                 }
668                 e_contact_set (new_contact, E_CONTACT_EMAIL_1, (const gpointer)email);
669                 g_free (display_address);
670                 commit_contact (new_contact, TRUE);
671                 g_debug ("%s added to address book", address);
672                 g_object_unref (new_contact);
673         }
674
675         g_free (email);
676
677         return TRUE;
678 }
679
680 static gboolean
681 show_check_names_banner (gpointer userdata)
682 {
683         GtkWidget **banner = (GtkWidget **) userdata;
684
685         gdk_threads_enter ();
686         *banner = hildon_banner_show_animation (NULL, NULL, _("mail_ib_checking_names"));
687         gdk_threads_leave ();
688
689         return FALSE;
690 }
691
692 static void
693 hide_check_names_banner (GtkWidget **banner, guint banner_timeout)
694 {
695         if (*banner != NULL) {
696                 gtk_widget_destroy (*banner);
697                 *banner = NULL;
698         } else {
699                 g_source_remove (banner_timeout);
700         }
701
702 }
703
704 gboolean
705 modest_address_book_check_names (ModestRecptEditor *recpt_editor, gboolean update_addressbook)
706 {
707         const gchar *recipients = NULL;
708         GSList *start_indexes = NULL, *end_indexes = NULL;
709         GSList *current_start, *current_end;
710         gboolean result = TRUE;
711         GtkTextBuffer *buffer;
712         gint offset_delta = 0;
713         gint last_length;
714         GtkTextIter start_iter, end_iter;
715
716         g_return_val_if_fail (MODEST_IS_RECPT_EDITOR (recpt_editor), FALSE);
717
718         recipients = modest_recpt_editor_get_recipients (recpt_editor);
719         last_length = g_utf8_strlen (recipients, -1);
720         modest_text_utils_get_addresses_indexes (recipients, &start_indexes, &end_indexes);
721
722         if (start_indexes == NULL) {
723                 if (last_length != 0) {
724                         hildon_banner_show_information (NULL, NULL, _("mcen_nc_no_matching_contacts"));
725                         return FALSE;
726                 } else {
727                         return TRUE;
728                 }
729         }
730
731         current_start = start_indexes;
732         current_end = end_indexes;
733         buffer = modest_recpt_editor_get_buffer (recpt_editor);
734
735         while (current_start != NULL) {
736                 gchar *address;
737                 gchar *start_ptr, *end_ptr;
738                 gint start_pos, end_pos;
739                 const gchar *invalid_char_position = NULL;
740                 gboolean store_address = FALSE;
741
742                 start_pos = (*((gint*) current_start->data)) + offset_delta;
743                 end_pos = (*((gint*) current_end->data)) + offset_delta;
744                
745                 start_ptr = g_utf8_offset_to_pointer (recipients, start_pos);
746                 end_ptr = g_utf8_offset_to_pointer (recipients, end_pos);
747
748                 address = g_strstrip (g_strndup (start_ptr, end_ptr - start_ptr));
749                 gtk_text_buffer_get_iter_at_offset (buffer, &start_iter, start_pos);
750                 gtk_text_buffer_get_iter_at_offset (buffer, &end_iter, end_pos);
751                 gtk_text_buffer_select_range (buffer, &start_iter, &end_iter);
752
753                 if (!modest_text_utils_validate_recipient (address, &invalid_char_position)) {
754                         if ((invalid_char_position != NULL) && (*invalid_char_position != '\0')) {
755                                 gchar *char_in_string = g_strdup_printf("%c", *invalid_char_position);
756                                 gchar *message = 
757                                         g_strdup_printf(_CS("ckdg_ib_illegal_characters_entered"), 
758                                                         char_in_string);
759                                 g_free (char_in_string);
760                                 hildon_banner_show_information (NULL, NULL, message );
761                                 g_free (message);                               
762                                 result = FALSE;
763                         } else if (strstr (address, "@") == NULL) {
764                                 /* here goes searching in addressbook */
765                                 gchar *contact_id = NULL;
766                                 GSList *resolved_addresses = NULL;
767
768                                 result = resolve_address (address, &resolved_addresses, &contact_id);
769
770                                 if (result) {
771                                         gint new_length;
772                                         /* replace string */
773                                         modest_recpt_editor_replace_with_resolved_recipient (recpt_editor,
774                                                                                              &start_iter, &end_iter,
775                                                                                              resolved_addresses, 
776                                                                                              contact_id);
777                                         g_free (contact_id);
778                                         g_slist_foreach (resolved_addresses, (GFunc) g_free, NULL);
779                                         g_slist_free (resolved_addresses);
780
781                                         /* update offset delta */
782                                         recipients = modest_recpt_editor_get_recipients (recpt_editor);
783                                         new_length = g_utf8_strlen (recipients, -1);
784                                         offset_delta = offset_delta + new_length - last_length;
785                                         last_length = new_length;                                       
786                                 }
787                         } else {
788                                 /* this address is not valid, select it and return control to user showing banner */
789                                 hildon_banner_show_information (NULL, NULL, _("mcen_ib_invalid_email"));
790                                 result = FALSE;
791                         }
792                 } else {
793                         GSList *tags, *node;
794                         gboolean has_recipient = FALSE;
795
796                         tags = gtk_text_iter_get_tags (&start_iter);
797                         for (node = tags; node != NULL; node = g_slist_next (node)) {
798                                 GtkTextTag *tag = GTK_TEXT_TAG (node->data);
799                                 if (g_object_get_data (G_OBJECT (tag), "recipient-tag-id") != NULL) {
800                                         has_recipient = TRUE;
801                                         break;
802                                 }
803                         }
804                         g_slist_free (tags);
805                         if (!has_recipient) {
806                                 GSList * address_list = NULL;
807
808                                 address_list = g_slist_prepend (address_list, address);
809                                 modest_recpt_editor_replace_with_resolved_recipient (recpt_editor,
810                                                                                      &start_iter, &end_iter,
811                                                                                      address_list, 
812                                                                                      "");
813                                 g_slist_free (address_list);
814                                 store_address = TRUE;
815                         }
816                 }
817
818                 /* so, it seems a valid address */
819                 /* note: adding it the to the addressbook if it did not exist yet,
820                  * and adding it to the recent_list */
821                 if (result && update_addressbook && store_address)
822                         add_to_address_book (address);
823
824                 g_free (address);
825                 if (result == FALSE)
826                         break;
827
828                 current_start = g_slist_next (current_start);
829                 current_end = g_slist_next (current_end);
830         }
831
832         if (current_start == NULL) {
833                 gtk_text_buffer_get_end_iter (buffer, &end_iter);
834                 gtk_text_buffer_place_cursor (buffer, &end_iter);
835         }
836
837         g_slist_foreach (start_indexes, (GFunc) g_free, NULL);
838         g_slist_foreach (end_indexes, (GFunc) g_free, NULL);
839         g_slist_free (start_indexes);
840         g_slist_free (end_indexes);
841
842         return result;
843
844 }
845
846 static GList *
847 get_contacts_for_name (const gchar *name)
848 {
849         EBookQuery *full_name_book_query = NULL;
850         GList *result;
851         gchar *unquoted;
852
853         if (name == NULL)
854                 return NULL;
855
856         unquoted = unquote_string (name);
857         full_name_book_query = e_book_query_field_test (E_CONTACT_FULL_NAME, E_BOOK_QUERY_CONTAINS, unquoted);
858         g_free (unquoted);
859
860         e_book_get_contacts (book, full_name_book_query, &result, NULL);
861         e_book_query_unref (full_name_book_query);
862
863         return result;
864 }
865
866 static GList *
867 select_contacts_for_name_dialog (const gchar *name)
868 {
869         EBookQuery *full_name_book_query = NULL;
870         EBookView *book_view = NULL;
871         GList *result = NULL;
872         gchar *unquoted;
873
874         unquoted = unquote_string (name);
875         full_name_book_query = e_book_query_field_test (E_CONTACT_FULL_NAME, E_BOOK_QUERY_CONTAINS, unquoted);
876         g_free (unquoted);
877         e_book_get_book_view (book, full_name_book_query, NULL, -1, &book_view, NULL);
878         e_book_query_unref (full_name_book_query);
879
880         if (book_view) {
881                 GtkWidget *contact_dialog = NULL;
882 #if MODEST_ABOOK_API < 4
883                 GtkWidget *contact_view = NULL;
884                 osso_abook_tree_model_set_book_view (OSSO_ABOOK_TREE_MODEL (contact_model), book_view);
885                 e_book_view_start (book_view);
886
887                 contact_view = osso_abook_contact_selector_new_basic (contact_model);
888                 contact_dialog = osso_abook_select_dialog_new (OSSO_ABOOK_TREE_VIEW (contact_view));
889
890                 if (gtk_dialog_run (GTK_DIALOG (contact_dialog)) == GTK_RESPONSE_OK) {
891                         result = osso_abook_contact_view_get_selection (OSSO_ABOOK_CONTACT_VIEW (contact_view));
892                 }
893                 e_book_view_stop (book_view);
894                 g_object_unref (book_view);
895                 gtk_widget_destroy (contact_dialog);
896 #else /* MODEST_ABOOK_API < 4 */
897                 osso_abook_list_store_set_book_view (OSSO_ABOOK_LIST_STORE (contact_model), book_view);
898                 e_book_view_start (book_view);
899
900                 /* TODO: figure out how to make the contact chooser modal */
901                 contact_dialog = osso_abook_contact_chooser_new_with_capabilities (NULL,
902                                                                                    _AB("addr_ti_dia_select_contacts"),
903                                                                                    OSSO_ABOOK_CAPS_EMAIL,
904                                                                                    OSSO_ABOOK_CONTACT_ORDER_NAME);
905                 osso_abook_contact_chooser_set_model (OSSO_ABOOK_CONTACT_CHOOSER (contact_dialog),
906                                                       contact_model);
907
908                 if (gtk_dialog_run (GTK_DIALOG (contact_dialog)) == GTK_RESPONSE_OK)
909                         result = osso_abook_contact_chooser_get_selection (OSSO_ABOOK_CONTACT_CHOOSER (contact_dialog));
910                 e_book_view_stop (book_view);
911                 g_object_unref (book_view);
912                 gtk_widget_destroy (contact_dialog);
913 #endif /* MODEST_ABOOK_API < 4 */
914         }
915
916         return result;
917 }
918
919 static gboolean
920 resolve_address (const gchar *address, GSList **resolved_addresses, gchar **contact_id)
921 {
922         GList *resolved_contacts;
923         guint banner_timeout;
924         GtkWidget *banner = NULL;
925
926         banner_timeout = g_timeout_add (500, show_check_names_banner, &banner);
927
928         contact_model = osso_abook_contact_model_new ();
929         if (!open_addressbook_sync ()) {
930                 if (contact_model) {
931                         g_object_unref (contact_model);
932                         contact_model = NULL;
933                 }
934                 return FALSE;
935         }
936
937         resolved_contacts = get_contacts_for_name (address);
938
939         if (resolved_contacts == NULL) {
940                 /* no matching contacts for the search string */
941                 modest_platform_run_information_dialog (NULL, _("mcen_nc_no_matching_contacts"), FALSE);
942                 hide_check_names_banner (&banner, banner_timeout);
943      
944                 return FALSE;
945         }
946
947         if (g_list_length (resolved_contacts) > 1) {
948                 /* show a dialog to select the contact from the resolved ones */
949                 g_list_free (resolved_contacts);
950
951                 hide_check_names_banner (&banner, banner_timeout);     
952                 resolved_contacts = select_contacts_for_name_dialog (address);
953                 banner_timeout = g_timeout_add (500, show_check_names_banner, &banner);
954
955         }
956         
957         /* get the resolved contacts (can be no contact) */
958         if (resolved_contacts) {
959                 gboolean found;
960                 EContact *contact = (EContact *) resolved_contacts->data;
961
962                 *resolved_addresses = get_recipients_for_given_contact (contact);
963                 hide_check_names_banner (&banner, banner_timeout);     
964                 if (*resolved_addresses) {
965                         *contact_id = g_strdup (e_contact_get_const (contact, E_CONTACT_UID));
966                         found = TRUE;
967                 } else {
968                         found = FALSE;
969                 }
970
971                 g_list_foreach (resolved_contacts, (GFunc)unref_gobject, NULL);
972                 g_list_free (resolved_contacts);
973
974                 return found;
975         } else {
976                 /* cancelled dialog to select more than one contact or
977                  * selected no contact */
978                 hide_check_names_banner (&banner, banner_timeout);     
979                 return FALSE;
980         }
981
982 }
983
984 static gchar *
985 unquote_string (const gchar *str)
986 {
987         GString *buffer;
988         gchar *p;
989
990         if (str == NULL)
991                 return NULL;
992
993         buffer = g_string_new_len (NULL, strlen (str));
994         for (p = (gchar *) str; *p != '\0'; p = g_utf8_next_char (p)) {
995                 if (*p == '"') {
996                         p = g_utf8_next_char (p);
997                         while ((*p != '\0')&&(*p != '"')) {
998                                 if (*p == '\\') {
999                                         g_string_append_unichar (buffer, g_utf8_get_char (p));
1000                                         p = g_utf8_next_char (p);
1001                                         
1002                                 }
1003                                 g_string_append_unichar (buffer, g_utf8_get_char (p));
1004                                 p = g_utf8_next_char (p);
1005                         }
1006                 } else {
1007                         g_string_append_unichar (buffer, g_utf8_get_char (p));
1008                 }
1009         }
1010
1011         return g_string_free (buffer, FALSE);
1012
1013 }
1014
1015 gboolean
1016 modest_address_book_has_address (const gchar *address)
1017 {
1018         EBookQuery *query;
1019         GList *contacts = NULL;
1020         GError *err = NULL;
1021         gchar *email;
1022         gboolean result;
1023
1024         g_return_val_if_fail (address, FALSE);
1025         
1026         if (!book) {
1027                 if (!open_addressbook ()) {
1028                         g_return_val_if_reached (FALSE);
1029                 }
1030         }
1031         
1032         g_return_val_if_fail (book, FALSE);
1033
1034         email = modest_text_utils_get_email_address (address);
1035         
1036         query = e_book_query_field_test (E_CONTACT_EMAIL, E_BOOK_QUERY_IS, email);
1037         if (!e_book_get_contacts (book, query, &contacts, &err)) {
1038                 g_printerr ("modest: failed to get contacts: %s",
1039                             err ? err->message : "<unknown>");
1040                 if (err)
1041                         g_error_free (err);
1042                 return FALSE;
1043         }
1044         e_book_query_unref (query);
1045
1046         result = (contacts != NULL);
1047         if (contacts) {
1048                 g_list_foreach (contacts, (GFunc)unref_gobject, NULL);
1049                 g_list_free (contacts);
1050         }
1051         
1052         g_free (email);
1053
1054         return result;
1055 }