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