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