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