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