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