* Fixes NB#103918, hide checking names after connecting to the addressbook
[modest] / src / hildon2 / modest-address-book.c
1 /* Copyright (c) 2007, Nokia Corporation
2  * All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
8  * * Redistributions of source code must retain the above copyright
9  *   notice, this list of conditions and the following disclaimer.
10  * * Redistributions in binary form must reproduce the above copyright
11  *   notice, this list of conditions and the following disclaimer in the
12  *   documentation and/or other materials provided with the distribution.
13  * * Neither the name of the Nokia Corporation nor the names of its
14  *   contributors may be used to endorse or promote products derived from
15  *   this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
18  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
19  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
20  * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
21  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 /* modest-address-book.c */
31
32 #include <config.h>
33 #include <glib/gi18n.h>
34 #include <modest-address-book.h>
35 #include <modest-text-utils.h>
36 #include <libebook/e-book.h>
37 #include <libebook/e-book-view.h>
38 #include <libebook/e-vcard.h>
39 #include "modest-hildon-includes.h"
40 #include <libosso-abook/osso-abook.h>
41 #include "modest-platform.h"
42 #include "modest-runtime.h"
43 #include "widgets/modest-window-mgr.h"
44 #include "widgets/modest-ui-constants.h"
45 #include <string.h>
46 #include <gtk/gtksizegroup.h>
47 #include <gtk/gtkbox.h>
48 #include <gtk/gtklabel.h>
49 #include <gtk/gtkcellrenderertext.h>
50 #include <gtk/gtktreeselection.h>
51 #include <gtk/gtkentry.h>
52 #include <modest-maemo-utils.h>
53
54 static OssoABookContactModel *contact_model =  NULL;
55 static EBook *book = NULL;
56 static EBookView * book_view = NULL;
57
58 static GSList *get_recipients_for_given_contact(EContact * contact);
59 static void commit_contact(EContact * contact, gboolean is_new);
60 static gchar *get_email_addr_from_user(const gchar * given_name);
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);
64 static GSList *select_email_addrs_for_contact(GList * email_addr_list);
65 static gboolean resolve_address (const gchar *address, GSList **resolved_addresses, gchar **contact_id);
66 static gchar *unquote_string (const gchar *str);
67
68
69 static void
70 unref_gobject (GObject *obj)
71 {
72         if (obj)
73                 g_object_unref (obj);
74 }
75         
76
77 static void
78 get_book_view_cb (EBook *book, EBookStatus status, EBookView *bookview, gpointer data)
79 {
80         if (status != E_BOOK_ERROR_OK) {
81                 g_object_unref (book);
82                 book = NULL;
83                 return;
84         }
85         book_view = bookview;
86
87         if (contact_model)
88 #if MODEST_ABOOK_API < 4
89                 osso_abook_tree_model_set_book_view (OSSO_ABOOK_TREE_MODEL (contact_model),
90                                                      book_view);
91 #else /* MODEST_ABOOK_API < 4 */
92                 osso_abook_list_store_set_book_view (OSSO_ABOOK_LIST_STORE (contact_model),
93                                                      book_view);
94 #endif /* MODEST_ABOOK_API < 4 */
95
96         e_book_view_start (book_view);
97 }
98
99 static void
100 book_open_cb (EBook *view, EBookStatus status, gpointer data)
101 {
102         EBookQuery *query = NULL;
103
104         if (status != E_BOOK_ERROR_OK) {
105                 g_object_unref (book);
106                 book = NULL;
107                 return;
108         }
109         query = e_book_query_any_field_contains ("");
110         e_book_async_get_book_view (book, query, NULL, -1, get_book_view_cb, NULL);
111         e_book_query_unref (query);
112 }
113
114 static gboolean 
115 open_addressbook ()
116 {
117         book = e_book_new_system_addressbook (NULL);
118         if (!book)
119                 return FALSE;
120
121         if (e_book_async_open (book, FALSE, book_open_cb, NULL) != E_BOOK_ERROR_OK)
122                 return FALSE;
123
124         return TRUE; /* FIXME */        
125 }
126
127 typedef struct _OpenAddressbookSyncInfo {
128         gboolean retval;
129         GMainLoop *mainloop;
130 } OpenAddressbookSyncInfo;
131
132 static void
133 get_book_view_sync_cb (EBook *book, EBookStatus status, EBookView *bookview, gpointer data)
134 {
135         OpenAddressbookSyncInfo *info = (OpenAddressbookSyncInfo *) data;
136
137         if (status != E_BOOK_ERROR_OK) {
138                 g_object_unref (book);
139                 book = NULL;
140                 info->retval = FALSE;
141                 g_main_loop_quit (info->mainloop);
142                 return;
143         }
144         book_view = bookview;
145
146         if (contact_model)
147 #if MODEST_ABOOK_API < 4
148                 osso_abook_tree_model_set_book_view (OSSO_ABOOK_TREE_MODEL (contact_model),
149                                                      book_view);
150 #else /* MODEST_ABOOK_API < 4 */
151                 osso_abook_list_store_set_book_view (OSSO_ABOOK_LIST_STORE (contact_model),
152                                                      book_view);
153 #endif /* MODEST_ABOOK_API < 4 */
154
155         e_book_view_start (book_view);
156         info->retval = TRUE;
157         g_main_loop_quit (info->mainloop);
158 }
159
160 static void
161 book_open_sync_cb (EBook *view, EBookStatus status, gpointer data)
162 {
163         EBookQuery *query = NULL;
164         OpenAddressbookSyncInfo *info = (OpenAddressbookSyncInfo *) data;
165
166         if (status != E_BOOK_ERROR_OK) {
167                 g_object_unref (book);
168                 book = NULL;
169                 info->retval = FALSE;
170                 g_main_loop_quit (info->mainloop);
171                 return;
172         }
173         query = e_book_query_any_field_contains ("");
174         e_book_async_get_book_view (book, query, NULL, -1, get_book_view_sync_cb, info);
175         e_book_query_unref (query);
176 }
177
178 static gboolean
179 open_addressbook_sync ()
180 {
181         OpenAddressbookSyncInfo *info;
182         gboolean retval;
183
184         book = e_book_new_system_addressbook (NULL);
185         if (!book)
186                 return FALSE;
187
188         info = g_slice_new (OpenAddressbookSyncInfo);
189         info->mainloop = g_main_loop_new (NULL, FALSE);
190         info->retval = FALSE;
191         if (e_book_async_open (book, FALSE, book_open_sync_cb, info) == E_BOOK_ERROR_OK) {
192                 GDK_THREADS_LEAVE ();
193                 g_main_loop_run (info->mainloop);
194                 GDK_THREADS_ENTER ();
195         }
196         retval = info->retval;
197         g_main_loop_unref (info->mainloop);
198         g_slice_free (OpenAddressbookSyncInfo, info);
199         /* Make it launch a main loop */
200         return e_book_open (book, FALSE, NULL);
201 }
202
203 void
204 modest_address_book_add_address (const gchar *address)
205 {
206         GtkWidget *dialog = NULL;
207         gchar *email_address;
208         EVCardAttribute *attribute;
209
210         if (!open_addressbook ()) {
211                 return;
212         }
213
214         email_address = modest_text_utils_get_email_address (address);
215         
216         attribute = e_vcard_attribute_new (NULL, EVC_EMAIL);
217         e_vcard_attribute_add_value (attribute, email_address);
218         dialog = osso_abook_temporary_contact_dialog_new (NULL, book, attribute, NULL);
219         gtk_dialog_run (GTK_DIALOG (dialog));
220
221         gtk_widget_destroy (dialog);
222
223         e_vcard_attribute_free (attribute);
224         g_free (email_address);
225
226 }
227
228 void
229 modest_address_book_select_addresses (ModestRecptEditor *recpt_editor)
230 {
231 #if MODEST_ABOOK_API < 4
232         GtkWidget *contact_view = NULL;
233         GtkWidget *contact_dialog;
234         GtkWidget *toplevel;
235 #else /* MODEST_ABOOK_API < 4 */
236         GtkWidget *contact_chooser = NULL;
237 #endif /* MODEST_ABOOK_API < 4 */
238
239         GList *contacts_list = NULL;
240         GSList *email_addrs_per_contact = NULL;
241         gchar *econtact_id;
242         gboolean focus_recpt_editor = FALSE;
243
244         g_return_if_fail (MODEST_IS_RECPT_EDITOR (recpt_editor));
245
246 #if MODEST_ABOOK_API < 4
247         if (!open_addressbook ()) {
248                 if (contact_model) {
249                         g_object_unref (contact_model);
250                         contact_model = NULL;
251                 }
252                 return;
253         }
254         contact_model = osso_abook_contact_model_new ();
255
256         contact_view = osso_abook_contact_selector_new_basic (contact_model);
257         osso_abook_contact_selector_set_minimum_selection (OSSO_ABOOK_CONTACT_SELECTOR (contact_view), 1);
258
259         contact_dialog = osso_abook_select_dialog_new (OSSO_ABOOK_TREE_VIEW (contact_view));
260         toplevel = gtk_widget_get_toplevel (GTK_WIDGET (recpt_editor));
261         modest_window_mgr_set_modal (modest_runtime_get_window_mgr (), GTK_WINDOW (contact_dialog), GTK_WINDOW (toplevel));
262
263         gtk_widget_show (contact_dialog);
264
265         if (gtk_dialog_run (GTK_DIALOG (contact_dialog)) == GTK_RESPONSE_OK) {
266                 contacts_list = 
267                         osso_abook_contact_selector_get_extended_selection (OSSO_ABOOK_CONTACT_SELECTOR
268                                                                              (contact_view));
269         }
270 #else /* MODEST_ABOOK_API < 4 */
271         /* TODO: figure out how to make the contact chooser modal */
272         contact_chooser = osso_abook_contact_chooser_new_with_capabilities (NULL,
273                                                                             _AB("addr_ti_dia_select_contacts"),
274                                                                             OSSO_ABOOK_CAPS_EMAIL, 
275                                                                             OSSO_ABOOK_CONTACT_ORDER_NAME);
276         /* Enable multiselection */
277         osso_abook_contact_chooser_set_maximum_selection (OSSO_ABOOK_CONTACT_CHOOSER (contact_chooser),
278                                                           G_MAXUINT);
279
280         if (gtk_dialog_run (GTK_DIALOG (contact_chooser)) == GTK_RESPONSE_OK)
281                 contacts_list = osso_abook_contact_chooser_get_selection (OSSO_ABOOK_CONTACT_CHOOSER (contact_chooser));
282         gtk_widget_destroy (contact_chooser);
283 #endif
284
285         if (contacts_list) {
286                 GList *node;
287
288                 for (node = contacts_list; node != NULL; node = g_list_next (node)) {
289                         EContact *contact = (EContact *) node->data;
290
291                         email_addrs_per_contact = get_recipients_for_given_contact (contact);
292                         if (email_addrs_per_contact) {
293                                 econtact_id = (gchar *) e_contact_get_const (contact, E_CONTACT_UID);
294                                 modest_recpt_editor_add_resolved_recipient (MODEST_RECPT_EDITOR (recpt_editor), 
295                                                                             email_addrs_per_contact, econtact_id);
296                                 g_slist_foreach (email_addrs_per_contact, (GFunc) g_free, NULL);
297                                 g_slist_free (email_addrs_per_contact);
298                                 email_addrs_per_contact = NULL;
299                                 focus_recpt_editor = TRUE;
300                         }
301                 }
302                 g_list_free (contacts_list);
303         }
304
305 #if MODEST_ABOOK_API < 4
306         if (contact_model) {
307                 g_object_unref (contact_model);
308                 contact_model = NULL;
309         }
310
311         gtk_widget_destroy (contact_dialog);
312 #endif
313
314         if (focus_recpt_editor)
315                 modest_recpt_editor_grab_focus (MODEST_RECPT_EDITOR (recpt_editor));
316
317 }
318
319 /**
320  * This function returns the resolved recipients for a given EContact.
321  * If no e-mail address is defined, it launches 'Add e-mail address to contact'
322  * dialog to obtain one. If multiple e-mail addresses are found, it launches
323  * 'Select e-mail address' dialog to allow user to select one or more e-mail
324  * addresses for that contact.
325  *
326  * @param  Contact of type #EContact
327  * @return List of resolved recipient strings, to be freed by calling function.
328  */
329 static GSList *get_recipients_for_given_contact(EContact * contact)
330 {
331         gchar *givenname = NULL;
332         gchar *familyname = NULL;
333         gchar *nickname = NULL;
334         gchar *emailid = NULL;
335         const gchar *display_name = NULL;
336         GList *list = NULL;
337         gchar *formatted_string = NULL;
338         gboolean email_not_present = FALSE;
339         GSList *formattedlist = NULL, *selected_email_addr_list = NULL, *node = NULL;
340
341         if (!contact) {
342                 return NULL;
343         }
344
345         givenname = (gchar *) e_contact_get_const(contact, E_CONTACT_GIVEN_NAME);
346         familyname = (gchar *) e_contact_get_const(contact, E_CONTACT_FAMILY_NAME);
347         nickname = (gchar *) e_contact_get_const(contact, E_CONTACT_NICKNAME);
348         if (!nickname)
349                 nickname = "";
350         list = (GList *) e_contact_get(contact, E_CONTACT_EMAIL);
351
352         if (!list) {
353                 email_not_present = TRUE;
354         }
355
356         if (list && g_list_length(list) == 1) {
357                 if (list->data == NULL || g_utf8_strlen(list->data, -1) == 0) {
358                         email_not_present = TRUE;
359                 } else {
360                         emailid = g_strstrip(g_strdup(list->data));
361                         if (g_utf8_strlen(emailid, -1) == 0) {
362                                 g_free(emailid);
363                                 email_not_present = TRUE;
364                         }
365                 }
366         }
367
368         /*Launch the 'Add e-mail addr to contact' dialog if required */
369         if (email_not_present) {
370 #if MODEST_ABOOK_API < 4
371                 display_name = osso_abook_contact_get_display_name(contact);            
372 #else
373                 OssoABookContact *abook_contact;
374                
375                 abook_contact = osso_abook_contact_new_from_template (contact);
376                 display_name = osso_abook_contact_get_display_name(abook_contact);
377 #endif
378
379                 emailid = get_email_addr_from_user(display_name);
380                 if (emailid) {
381                         e_contact_set(contact, E_CONTACT_EMAIL_1, emailid);
382                         commit_contact(contact, FALSE);
383                 }
384 #if MODEST_ABOOK_API >= 4
385                 g_object_unref (abook_contact);
386 #endif
387         }
388
389         if (emailid) {
390                 if (givenname || familyname)
391                         formatted_string =
392                             ui_get_formatted_email_id(givenname, familyname, emailid);
393                 else
394                         formatted_string = g_strdup(emailid);
395                 formattedlist = g_slist_append(formattedlist, formatted_string);
396                 g_free(emailid);
397         }
398
399         /*Launch the 'Select e-mail address' dialog if required */
400         if (g_list_length(list) > 1) {
401                 selected_email_addr_list = select_email_addrs_for_contact(list);
402                 for (node = selected_email_addr_list; node != NULL; node = node->next) {
403                         if (givenname || familyname)
404                                 formatted_string =
405                                     ui_get_formatted_email_id(givenname, familyname, node->data);
406                         else
407                                 formatted_string = g_strdup(node->data);
408                         formattedlist = g_slist_append(formattedlist, formatted_string);
409                 }
410                 if (selected_email_addr_list) {
411                         g_slist_foreach(selected_email_addr_list, (GFunc) g_free, NULL);
412                         g_slist_free(selected_email_addr_list);
413                 }
414         }
415
416         if (list) {
417                 g_list_foreach(list, (GFunc) g_free, NULL);
418                 g_list_free(list);
419         }
420
421         return formattedlist;
422 }
423
424 /**
425  * This is a helper function to commit a EContact to Address_Book application.
426  *
427  * @param  contact  Contact of type #EContact
428  * @return void
429  */
430 static void 
431 commit_contact(EContact * contact, gboolean is_new)
432 {
433         g_return_if_fail (contact);
434         g_return_if_fail (book);
435
436         if (!contact || !book)
437                 return;
438
439 #if MODEST_ABOOK_API < 4
440         osso_abook_contact_commit(contact, is_new, book);
441 #else
442         if (OSSO_ABOOK_IS_CONTACT (contact)) {
443                 osso_abook_contact_commit(OSSO_ABOOK_CONTACT(contact), is_new, book, NULL);
444         } else {
445                 if (is_new)
446                         e_book_add_contact (book, contact, NULL);
447                 else
448                         e_book_commit_contact (book, contact, NULL);
449         }
450 #endif /* MODEST_ABOOK_API < 2 */
451 }
452
453 /**
454  * This is a helper function used to launch 'Add e-mail address to contact' dialog
455  * after showing appropriate notification, when there is no e-mail address defined
456  * for a selected contact.
457  *
458  * @param  given_name  Given name of the contact
459  * @param  family_name  Family name of the contact
460  * @return E-mail address string entered by user, to be freed by calling function.
461  */
462 static gchar *
463 get_email_addr_from_user(const gchar * given_name)
464 {
465         gchar *notification = NULL;
466         gchar *email_addr = NULL;
467         GtkWidget *note;
468         gboolean note_response;
469
470
471         notification = g_strdup_printf(_("mcen_nc_email_address_not_defined"), given_name);
472
473         note = hildon_note_new_confirmation (NULL, notification);
474         note_response = gtk_dialog_run (GTK_DIALOG(note));
475         gtk_widget_destroy (note);
476         g_free(notification);
477
478         if (note_response == GTK_RESPONSE_OK) {
479                 email_addr = run_add_email_addr_to_contact_dlg(given_name);
480         }
481
482         return email_addr;
483 }
484
485 /**
486 This function is used to get the formated email id with given name and sur name
487 in the format "GIVENNAME SURNAME <EMAIL ADDRESS>".
488 @param current_given_name    to hold the given name
489 @param current_sur_name      to hold the sur name
490 @param current_email_id      to hold the email id. 
491 @return gchar* string to be freed by calling function
492 */
493 static gchar *
494 ui_get_formatted_email_id(gchar * current_given_name,
495                           gchar * current_sur_name, gchar * current_email_id)
496 {
497         GString *email_id_str = NULL;
498
499         email_id_str = g_string_new(NULL);
500
501         if ((current_given_name != NULL) && ((strlen(current_given_name) != 0))
502             && (current_sur_name != NULL) && ((strlen(current_sur_name) != 0))) {
503                 g_string_append_printf(email_id_str, "%s %s", current_given_name, current_sur_name);
504         } else if ((current_given_name != NULL) && (strlen(current_given_name) != 0)) {
505                 g_string_append_printf(email_id_str, "%s", current_given_name);
506         } else if ((current_sur_name != NULL) && (strlen(current_sur_name) != 0)) {
507                 g_string_append_printf(email_id_str, "%s", current_sur_name);
508         }
509         if (g_utf8_strchr (email_id_str->str, -1, ' ')) {
510                 g_string_prepend_c (email_id_str, '\"');
511                 g_string_append_c (email_id_str, '\"');
512         }
513         g_string_append_printf (email_id_str, " %c%s%c", '<', current_email_id, '>');
514         return g_string_free (email_id_str, FALSE);
515 }
516
517 /**
518  * This is a helper function used to create & run 'Add e-mail address to contact' dialog.
519  * It allows user to enter an e-mail address, and shows appropriate infonote if the
520  * entered string is not a valid e-mail address.
521  *
522  * @param  contact_name  Full name of the contact
523  * @return E-mail address string entered by user, to be freed by calling function.
524  */
525 static gchar *
526 run_add_email_addr_to_contact_dlg(const gchar * contact_name)
527 {
528         GtkWidget *add_email_addr_to_contact_dlg = NULL;
529         GtkSizeGroup *size_group = NULL;
530         GtkWidget *cptn_cntrl = NULL;
531         GtkWidget *name_label = NULL;
532         GtkWidget *email_entry = NULL;
533         gint result = -1;
534         gchar *new_email_addr = NULL;
535         gboolean run_dialog = TRUE;
536
537         add_email_addr_to_contact_dlg =
538             gtk_dialog_new_with_buttons(_("mcen_ti_add_email_title"), NULL,
539                                         GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
540                                         _HL("wdgt_bd_save"), GTK_RESPONSE_ACCEPT, NULL);
541         gtk_dialog_set_has_separator(GTK_DIALOG(add_email_addr_to_contact_dlg), FALSE);
542 #ifdef MODEST_TOOLKIT_HILDON2
543         gtk_container_set_border_width (GTK_CONTAINER (GTK_DIALOG (add_email_addr_to_contact_dlg)->vbox), 
544                                         HILDON_MARGIN_DOUBLE);
545 #endif
546         /*Set app_name & state_save related tags to the window */
547
548         size_group = gtk_size_group_new(GTK_SIZE_GROUP_HORIZONTAL);
549         name_label = gtk_label_new(contact_name);
550         gtk_misc_set_alignment(GTK_MISC(name_label), 0.0, 0.5);
551         cptn_cntrl =
552                 modest_maemo_utils_create_captioned (size_group, NULL,
553                                                      _("mcen_ia_add_email_name"), FALSE,
554                                                      name_label);
555         gtk_box_pack_start(GTK_BOX(GTK_DIALOG(add_email_addr_to_contact_dlg)->vbox), cptn_cntrl,
556                            FALSE, FALSE, 0);
557
558         email_entry = hildon_entry_new (HILDON_SIZE_FINGER_HEIGHT | HILDON_SIZE_AUTO_WIDTH);
559         cptn_cntrl = modest_maemo_utils_create_captioned (size_group, NULL, 
560                                                           _("mcen_fi_add_email_name"), FALSE,
561                                                           email_entry);
562         hildon_gtk_entry_set_input_mode(GTK_ENTRY(email_entry), HILDON_GTK_INPUT_MODE_FULL);
563         gtk_box_pack_start(GTK_BOX(GTK_DIALOG(add_email_addr_to_contact_dlg)->vbox), cptn_cntrl,
564                            TRUE, TRUE, 0);
565
566         gtk_widget_show_all(add_email_addr_to_contact_dlg);
567
568         while (run_dialog) {
569                 run_dialog = FALSE;
570                 gtk_widget_grab_focus(email_entry);
571                 result = gtk_dialog_run(GTK_DIALOG(add_email_addr_to_contact_dlg));
572
573                 if (result == GTK_RESPONSE_ACCEPT) {
574                         const gchar *invalid_char_offset = NULL;
575                         new_email_addr = g_strdup(hildon_entry_get_text(HILDON_ENTRY(email_entry)));
576                         new_email_addr = g_strstrip(new_email_addr);
577                         if (!modest_text_utils_validate_email_address (new_email_addr, &invalid_char_offset)) {
578                                 gtk_widget_grab_focus(email_entry);
579                                 if ((invalid_char_offset != NULL)&&(*invalid_char_offset != '\0')) {
580                                         gchar *char_in_string = g_strdup_printf ("%c", *invalid_char_offset);
581                                         gchar *message = g_strdup_printf(
582                                                 _CS("ckdg_ib_illegal_characters_entered"), 
583                                                 char_in_string);
584                                         hildon_banner_show_information (
585                                                 add_email_addr_to_contact_dlg, NULL, message );
586                                         g_free (message);
587                                 } else {
588                                         hildon_banner_show_information (add_email_addr_to_contact_dlg, NULL, _("mcen_ib_invalid_email"));
589                                         run_dialog = TRUE;
590                                 }
591                                 gtk_editable_select_region((GtkEditable *) email_entry, 0, -1);
592                                 g_free(new_email_addr);
593                                 new_email_addr = NULL;
594                         }
595                 }
596         }
597
598         gtk_widget_destroy(add_email_addr_to_contact_dlg);
599
600         return new_email_addr;
601 }
602
603 /**
604  * This is helper function to create & run 'Select e-mail address' dialog, used when
605  * multiple e-mail addresses are found for a selected contact. It allows user to select
606  * one or more e-mail addresses for that contact.
607  *
608  * @param  email_addr_list  List of e-mail addresses for that contact
609  * @return List of user selected e-mail addresses, to be freed by calling function.
610  */
611 static GSList *
612 select_email_addrs_for_contact(GList * email_addr_list)
613 {
614         GtkWidget *select_email_addr_dlg = NULL;
615         GSList *selected_email_addr_list = NULL;
616         GList *node;
617         GtkWidget *selector;
618         gint result = -1;
619
620         if (!email_addr_list)
621                 return NULL;
622
623         select_email_addr_dlg = hildon_picker_dialog_new (NULL);
624         gtk_window_set_title (GTK_WINDOW (select_email_addr_dlg), _("mcen_ti_select_email_title"));
625
626         selector = hildon_touch_selector_new_text ();
627         for (node = email_addr_list; node != NULL && node->data != NULL; node = node->next) {
628                 gchar *email_addr;
629                 email_addr = g_strstrip(g_strdup(node->data));
630                 hildon_touch_selector_append_text (HILDON_TOUCH_SELECTOR (selector), email_addr);
631                 g_free(email_addr);
632         }
633
634         hildon_picker_dialog_set_selector (HILDON_PICKER_DIALOG (select_email_addr_dlg),
635                                            HILDON_TOUCH_SELECTOR (selector));
636         gtk_window_set_default_size (GTK_WINDOW (select_email_addr_dlg), MODEST_DIALOG_WINDOW_MAX_HEIGHT, -1);
637         
638         gtk_widget_show_all(select_email_addr_dlg);
639         result = gtk_dialog_run(GTK_DIALOG(select_email_addr_dlg));
640
641         if (result == GTK_RESPONSE_OK) {
642                 gchar *current_text;
643
644                 current_text = hildon_touch_selector_get_current_text (HILDON_TOUCH_SELECTOR (selector));
645                 selected_email_addr_list = g_slist_append (selected_email_addr_list, current_text);
646                 
647         }
648
649         gtk_widget_destroy(select_email_addr_dlg);
650         return selected_email_addr_list;
651 }
652
653
654 static gboolean /* make this public? */
655 add_to_address_book (const gchar* address)
656 {
657         EBookQuery *query;
658         GList *contacts = NULL;
659         GError *err = NULL;
660         gchar *email;
661         
662         g_return_val_if_fail (address, FALSE);
663         
664         if (!book) {
665                 if (!open_addressbook ()) {
666                         g_return_val_if_reached (FALSE);
667                 }
668         }
669         
670         g_return_val_if_fail (book, FALSE);
671
672         email = modest_text_utils_get_email_address (address);
673         
674         query = e_book_query_field_test (E_CONTACT_EMAIL, E_BOOK_QUERY_IS, email);
675         if (!e_book_get_contacts (book, query, &contacts, &err)) {
676                 g_printerr ("modest: failed to get contacts: %s",
677                             err ? err->message : "<unknown>");
678                 if (err)
679                         g_error_free (err);
680                 return FALSE;
681         }
682         e_book_query_unref (query);
683         
684         /*  we need to 'commit' it, even if we already found the email
685          * address in the addressbook; thus, it will show up in the 'recent list' */
686         if (contacts)  {                
687                 g_debug ("%s already in the address book", address);
688                 commit_contact ((EContact*)contacts->data, FALSE);
689                 
690                 g_list_foreach (contacts, (GFunc)unref_gobject, NULL);
691                 g_list_free (contacts);
692
693         } else {
694                 /* it's not yet in the addressbook, add it now! */
695                 EContact *new_contact = e_contact_new ();
696                 gchar *display_address;
697                 display_address = g_strdup (address);
698                 if (display_address) {
699                         modest_text_utils_get_display_address (display_address);
700                         if ((display_address[0] != '\0') && (strlen (display_address) != strlen (address)))
701                                 e_contact_set (new_contact, E_CONTACT_FULL_NAME, (const gpointer)display_address);
702                 }
703                 e_contact_set (new_contact, E_CONTACT_EMAIL_1, (const gpointer)email);
704                 g_free (display_address);
705                 commit_contact (new_contact, TRUE);
706                 g_debug ("%s added to address book", address);
707                 g_object_unref (new_contact);
708         }
709
710         g_free (email);
711
712         return TRUE;
713 }
714
715 static gboolean
716 show_check_names_banner (gpointer userdata)
717 {
718         GtkWidget **banner = (GtkWidget **) userdata;
719
720         gdk_threads_enter ();
721         *banner = hildon_banner_show_animation (NULL, NULL, _("mail_ib_checking_names"));
722         gdk_threads_leave ();
723
724         return FALSE;
725 }
726
727 static void
728 hide_check_names_banner (GtkWidget **banner, guint banner_timeout)
729 {
730         if (*banner != NULL) {
731                 gtk_widget_destroy (*banner);
732                 *banner = NULL;
733         } else {
734                 g_source_remove (banner_timeout);
735         }
736
737 }
738
739 gboolean
740 modest_address_book_check_names (ModestRecptEditor *recpt_editor, gboolean update_addressbook)
741 {
742         const gchar *recipients = NULL;
743         GSList *start_indexes = NULL, *end_indexes = NULL;
744         GSList *current_start, *current_end;
745         gboolean result = TRUE;
746         GtkTextBuffer *buffer;
747         gint offset_delta = 0;
748         gint last_length;
749         GtkTextIter start_iter, end_iter;
750
751         g_return_val_if_fail (MODEST_IS_RECPT_EDITOR (recpt_editor), FALSE);
752
753         recipients = modest_recpt_editor_get_recipients (recpt_editor);
754         last_length = g_utf8_strlen (recipients, -1);
755         modest_text_utils_get_addresses_indexes (recipients, &start_indexes, &end_indexes);
756
757         if (start_indexes == NULL) {
758                 if (last_length != 0) {
759                         hildon_banner_show_information (NULL, NULL, _("mcen_nc_no_matching_contacts"));
760                         return FALSE;
761                 } else {
762                         return TRUE;
763                 }
764         }
765
766         current_start = start_indexes;
767         current_end = end_indexes;
768         buffer = modest_recpt_editor_get_buffer (recpt_editor);
769
770         while (current_start != NULL) {
771                 gchar *address;
772                 gchar *start_ptr, *end_ptr;
773                 gint start_pos, end_pos;
774                 const gchar *invalid_char_position = NULL;
775                 gboolean store_address = FALSE;
776
777                 start_pos = (*((gint*) current_start->data)) + offset_delta;
778                 end_pos = (*((gint*) current_end->data)) + offset_delta;
779                
780                 start_ptr = g_utf8_offset_to_pointer (recipients, start_pos);
781                 end_ptr = g_utf8_offset_to_pointer (recipients, end_pos);
782
783                 address = g_strstrip (g_strndup (start_ptr, end_ptr - start_ptr));
784                 gtk_text_buffer_get_iter_at_offset (buffer, &start_iter, start_pos);
785                 gtk_text_buffer_get_iter_at_offset (buffer, &end_iter, end_pos);
786                 gtk_text_buffer_select_range (buffer, &start_iter, &end_iter);
787
788                 if (!modest_text_utils_validate_recipient (address, &invalid_char_position)) {
789                         if ((invalid_char_position != NULL) && (*invalid_char_position != '\0')) {
790                                 gchar *char_in_string = g_strdup_printf("%c", *invalid_char_position);
791                                 gchar *message = 
792                                         g_strdup_printf(_CS("ckdg_ib_illegal_characters_entered"), 
793                                                         char_in_string);
794                                 g_free (char_in_string);
795                                 hildon_banner_show_information (NULL, NULL, message );
796                                 g_free (message);                               
797                                 result = FALSE;
798                         } else if (strstr (address, "@") == NULL) {
799                                 /* here goes searching in addressbook */
800                                 gchar *contact_id = NULL;
801                                 GSList *resolved_addresses = NULL;
802
803                                 result = resolve_address (address, &resolved_addresses, &contact_id);
804
805                                 if (result) {
806                                         gint new_length;
807                                         /* replace string */
808                                         modest_recpt_editor_replace_with_resolved_recipient (recpt_editor,
809                                                                                              &start_iter, &end_iter,
810                                                                                              resolved_addresses, 
811                                                                                              contact_id);
812                                         g_free (contact_id);
813                                         g_slist_foreach (resolved_addresses, (GFunc) g_free, NULL);
814                                         g_slist_free (resolved_addresses);
815
816                                         /* update offset delta */
817                                         recipients = modest_recpt_editor_get_recipients (recpt_editor);
818                                         new_length = g_utf8_strlen (recipients, -1);
819                                         offset_delta = offset_delta + new_length - last_length;
820                                         last_length = new_length;                                       
821                                 } else {
822                                         /* We have to remove the recipient if not resolved */
823                                         modest_recpt_editor_replace_with_resolved_recipient (recpt_editor,
824                                                                                              &start_iter, &end_iter,
825                                                                                              NULL,
826                                                                                              NULL);
827                                 }
828                         } else {
829                                 /* this address is not valid, select it and return control to user showing banner */
830                                 hildon_banner_show_information (NULL, NULL, _("mcen_ib_invalid_email"));
831                                 result = FALSE;
832                         }
833                 } else {
834                         GSList *tags, *node;
835                         gboolean has_recipient = FALSE;
836
837                         tags = gtk_text_iter_get_tags (&start_iter);
838                         for (node = tags; node != NULL; node = g_slist_next (node)) {
839                                 GtkTextTag *tag = GTK_TEXT_TAG (node->data);
840                                 if (g_object_get_data (G_OBJECT (tag), "recipient-tag-id") != NULL) {
841                                         has_recipient = TRUE;
842                                         break;
843                                 }
844                         }
845                         g_slist_free (tags);
846                         if (!has_recipient) {
847                                 GSList * address_list = NULL;
848
849                                 address_list = g_slist_prepend (address_list, address);
850                                 modest_recpt_editor_replace_with_resolved_recipient (recpt_editor,
851                                                                                      &start_iter, &end_iter,
852                                                                                      address_list, 
853                                                                                      "");
854                                 g_slist_free (address_list);
855                                 store_address = TRUE;
856                         }
857                 }
858
859                 /* so, it seems a valid address */
860                 /* note: adding it the to the addressbook if it did not exist yet,
861                  * and adding it to the recent_list */
862                 if (result && update_addressbook && store_address)
863                         add_to_address_book (address);
864
865                 g_free (address);
866                 if (result == FALSE)
867                         break;
868
869                 current_start = g_slist_next (current_start);
870                 current_end = g_slist_next (current_end);
871         }
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 *full_name_book_query = NULL;
910         GList *result;
911         gchar *unquoted;
912         GetContactsInfo *info;
913
914         if (name == NULL)
915                 return NULL;
916
917         unquoted = unquote_string (name);
918         full_name_book_query = e_book_query_field_test (E_CONTACT_FULL_NAME, E_BOOK_QUERY_CONTAINS, unquoted);
919         g_free (unquoted);
920
921         /* TODO: Make it launch a mainloop */
922         info = g_slice_new (GetContactsInfo);
923         info->mainloop = g_main_loop_new (NULL, FALSE);
924         info->result = NULL;
925         if (e_book_async_get_contacts (book, full_name_book_query, get_contacts_for_name_cb, info) == 0) {
926                 GDK_THREADS_LEAVE ();
927                 g_main_loop_run (info->mainloop);
928                 GDK_THREADS_ENTER ();
929         } 
930         result = info->result;
931         e_book_query_unref (full_name_book_query);
932         g_main_loop_unref (info->mainloop);
933         g_slice_free (GetContactsInfo, info);
934
935         return result;
936 }
937
938 static GList *
939 select_contacts_for_name_dialog (const gchar *name)
940 {
941         EBookQuery *full_name_book_query = NULL;
942         EBookView *book_view = NULL;
943         GList *result = NULL;
944         gchar *unquoted;
945
946         unquoted = unquote_string (name);
947         full_name_book_query = e_book_query_field_test (E_CONTACT_FULL_NAME, E_BOOK_QUERY_CONTAINS, unquoted);
948         g_free (unquoted);
949         e_book_get_book_view (book, full_name_book_query, NULL, -1, &book_view, NULL);
950         e_book_query_unref (full_name_book_query);
951
952         if (book_view) {
953                 GtkWidget *contact_dialog = NULL;
954 #if MODEST_ABOOK_API < 4
955                 GtkWidget *contact_view = NULL;
956                 osso_abook_tree_model_set_book_view (OSSO_ABOOK_TREE_MODEL (contact_model), book_view);
957                 e_book_view_start (book_view);
958
959                 contact_view = osso_abook_contact_selector_new_basic (contact_model);
960                 contact_dialog = osso_abook_select_dialog_new (OSSO_ABOOK_TREE_VIEW (contact_view));
961
962                 if (gtk_dialog_run (GTK_DIALOG (contact_dialog)) == GTK_RESPONSE_OK) {
963                         result = osso_abook_contact_view_get_selection (OSSO_ABOOK_CONTACT_VIEW (contact_view));
964                 }
965                 e_book_view_stop (book_view);
966                 g_object_unref (book_view);
967                 gtk_widget_destroy (contact_dialog);
968 #else /* MODEST_ABOOK_API < 4 */
969                 osso_abook_list_store_set_book_view (OSSO_ABOOK_LIST_STORE (contact_model), book_view);
970                 e_book_view_start (book_view);
971
972                 /* TODO: figure out how to make the contact chooser modal */
973                 contact_dialog = osso_abook_contact_chooser_new_with_capabilities (NULL,
974                                                                                    _AB("addr_ti_dia_select_contacts"),
975                                                                                    OSSO_ABOOK_CAPS_EMAIL,
976                                                                                    OSSO_ABOOK_CONTACT_ORDER_NAME);
977                 osso_abook_contact_chooser_set_model (OSSO_ABOOK_CONTACT_CHOOSER (contact_dialog),
978                                                       contact_model);
979
980                 if (gtk_dialog_run (GTK_DIALOG (contact_dialog)) == GTK_RESPONSE_OK)
981                         result = osso_abook_contact_chooser_get_selection (OSSO_ABOOK_CONTACT_CHOOSER (contact_dialog));
982                 e_book_view_stop (book_view);
983                 g_object_unref (book_view);
984                 gtk_widget_destroy (contact_dialog);
985 #endif /* MODEST_ABOOK_API < 4 */
986         }
987
988         return result;
989 }
990
991 static gboolean
992 resolve_address (const gchar *address, GSList **resolved_addresses, gchar **contact_id)
993 {
994         GList *resolved_contacts;
995         guint banner_timeout;
996         GtkWidget *banner = NULL;
997
998         banner_timeout = g_timeout_add (500, show_check_names_banner, &banner);
999
1000         contact_model = osso_abook_contact_model_new ();
1001         if (!open_addressbook_sync ()) {
1002                 hide_check_names_banner (&banner, banner_timeout);
1003                 if (contact_model) {
1004                         g_object_unref (contact_model);
1005                         contact_model = NULL;
1006                 }
1007                 return FALSE;
1008         }
1009         hide_check_names_banner (&banner, banner_timeout);
1010
1011         resolved_contacts = get_contacts_for_name (address);
1012
1013         if (resolved_contacts == NULL) {
1014                 /* no matching contacts for the search string */
1015                 modest_platform_run_information_dialog (NULL, _("mcen_nc_no_matching_contacts"), FALSE);
1016                 return FALSE;
1017         }
1018
1019         if (g_list_length (resolved_contacts) > 1) {
1020                 /* show a dialog to select the contact from the resolved ones */
1021                 g_list_free (resolved_contacts);
1022
1023                 resolved_contacts = select_contacts_for_name_dialog (address);
1024                 banner_timeout = g_timeout_add (500, show_check_names_banner, &banner);
1025
1026         }
1027
1028         /* get the resolved contacts (can be no contact) */
1029         if (resolved_contacts) {
1030                 gboolean found;
1031                 EContact *contact = (EContact *) resolved_contacts->data;
1032
1033                 *resolved_addresses = get_recipients_for_given_contact (contact);
1034                 if (*resolved_addresses) {
1035                         *contact_id = g_strdup (e_contact_get_const (contact, E_CONTACT_UID));
1036                         found = TRUE;
1037                 } else {
1038                         found = FALSE;
1039                 }
1040
1041                 g_list_foreach (resolved_contacts, (GFunc)unref_gobject, NULL);
1042                 g_list_free (resolved_contacts);
1043
1044                 return found;
1045         } else {
1046                 /* cancelled dialog to select more than one contact or
1047                  * selected no contact */
1048                 return FALSE;
1049         }
1050
1051 }
1052
1053 static gchar *
1054 unquote_string (const gchar *str)
1055 {
1056         GString *buffer;
1057         gchar *p;
1058
1059         if (str == NULL)
1060                 return NULL;
1061
1062         buffer = g_string_new_len (NULL, strlen (str));
1063         for (p = (gchar *) str; *p != '\0'; p = g_utf8_next_char (p)) {
1064                 if (*p == '"') {
1065                         p = g_utf8_next_char (p);
1066                         while ((*p != '\0')&&(*p != '"')) {
1067                                 if (*p == '\\') {
1068                                         g_string_append_unichar (buffer, g_utf8_get_char (p));
1069                                         p = g_utf8_next_char (p);
1070                                         
1071                                 }
1072                                 g_string_append_unichar (buffer, g_utf8_get_char (p));
1073                                 p = g_utf8_next_char (p);
1074                         }
1075                 } else {
1076                         g_string_append_unichar (buffer, g_utf8_get_char (p));
1077                 }
1078         }
1079
1080         return g_string_free (buffer, FALSE);
1081
1082 }
1083
1084 gboolean
1085 modest_address_book_has_address (const gchar *address)
1086 {
1087         EBookQuery *query;
1088         GList *contacts = NULL;
1089         GError *err = NULL;
1090         gchar *email;
1091         gboolean result;
1092
1093         g_return_val_if_fail (address, FALSE);
1094         
1095         if (!book) {
1096                 if (!open_addressbook ()) {
1097                         g_return_val_if_reached (FALSE);
1098                 }
1099         }
1100         
1101         g_return_val_if_fail (book, FALSE);
1102
1103         email = modest_text_utils_get_email_address (address);
1104         
1105         query = e_book_query_field_test (E_CONTACT_EMAIL, E_BOOK_QUERY_IS, email);
1106         if (!e_book_get_contacts (book, query, &contacts, &err)) {
1107                 g_printerr ("modest: failed to get contacts: %s",
1108                             err ? err->message : "<unknown>");
1109                 if (err)
1110                         g_error_free (err);
1111                 return FALSE;
1112         }
1113         e_book_query_unref (query);
1114
1115         result = (contacts != NULL);
1116         if (contacts) {
1117                 g_list_foreach (contacts, (GFunc)unref_gobject, NULL);
1118                 g_list_free (contacts);
1119         }
1120         
1121         g_free (email);
1122
1123         return result;
1124 }