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