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