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