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