Set margin of password dialog
[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 "modest-hildon-includes.h"
40 #include <libosso-abook/osso-abook.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 typedef struct _OpenAddressbookSyncInfo {
127         gboolean retval;
128         GMainLoop *mainloop;
129 } OpenAddressbookSyncInfo;
130
131 static void
132 get_book_view_sync_cb (EBook *book, EBookStatus status, EBookView *bookview, gpointer data)
133 {
134         OpenAddressbookSyncInfo *info = (OpenAddressbookSyncInfo *) data;
135
136         if (status != E_BOOK_ERROR_OK) {
137                 g_object_unref (book);
138                 book = NULL;
139                 info->retval = FALSE;
140                 g_main_loop_quit (info->mainloop);
141                 return;
142         }
143         book_view = bookview;
144
145         if (contact_model)
146 #if MODEST_ABOOK_API < 4
147                 osso_abook_tree_model_set_book_view (OSSO_ABOOK_TREE_MODEL (contact_model),
148                                                      book_view);
149 #else /* MODEST_ABOOK_API < 4 */
150                 osso_abook_list_store_set_book_view (OSSO_ABOOK_LIST_STORE (contact_model),
151                                                      book_view);
152 #endif /* MODEST_ABOOK_API < 4 */
153
154         e_book_view_start (book_view);
155         info->retval = TRUE;
156         g_main_loop_quit (info->mainloop);
157 }
158
159 static void
160 book_open_sync_cb (EBook *view, EBookStatus status, gpointer data)
161 {
162         EBookQuery *query = NULL;
163         OpenAddressbookSyncInfo *info = (OpenAddressbookSyncInfo *) data;
164
165         if (status != E_BOOK_ERROR_OK) {
166                 g_object_unref (book);
167                 book = NULL;
168                 info->retval = FALSE;
169                 g_main_loop_quit (info->mainloop);
170                 return;
171         }
172         query = e_book_query_any_field_contains ("");
173         e_book_async_get_book_view (book, query, NULL, -1, get_book_view_sync_cb, info);
174         e_book_query_unref (query);
175 }
176
177 static gboolean
178 open_addressbook_sync ()
179 {
180         OpenAddressbookSyncInfo *info;
181         gboolean retval;
182
183         book = e_book_new_system_addressbook (NULL);
184         if (!book)
185                 return FALSE;
186
187         info = g_slice_new (OpenAddressbookSyncInfo);
188         info->mainloop = g_main_loop_new (NULL, FALSE);
189         info->retval = FALSE;
190         if (e_book_async_open (book, FALSE, book_open_sync_cb, info) == E_BOOK_ERROR_OK) {
191                 GDK_THREADS_LEAVE ();
192                 g_main_loop_run (info->mainloop);
193                 GDK_THREADS_ENTER ();
194         }
195         retval = info->retval;
196         g_main_loop_unref (info->mainloop);
197         g_slice_free (OpenAddressbookSyncInfo, info);
198         /* Make it launch a main loop */
199         return e_book_open (book, FALSE, NULL);
200 }
201
202 void
203 modest_address_book_add_address (const gchar *address)
204 {
205         GtkWidget *dialog = NULL;
206         gchar *email_address;
207         EVCardAttribute *attribute;
208
209         if (!open_addressbook ()) {
210                 return;
211         }
212
213         email_address = modest_text_utils_get_email_address (address);
214         
215         attribute = e_vcard_attribute_new (NULL, EVC_EMAIL);
216         e_vcard_attribute_add_value (attribute, email_address);
217         dialog = osso_abook_temporary_contact_dialog_new (NULL, book, attribute, NULL);
218         gtk_dialog_run (GTK_DIALOG (dialog));
219
220         gtk_widget_destroy (dialog);
221
222         e_vcard_attribute_free (attribute);
223         g_free (email_address);
224
225 }
226
227 void
228 modest_address_book_select_addresses (ModestRecptEditor *recpt_editor)
229 {
230 #if MODEST_ABOOK_API < 4
231         GtkWidget *contact_view = NULL;
232         GtkWidget *contact_dialog;
233         GtkWidget *toplevel;
234 #else /* MODEST_ABOOK_API < 4 */
235         GtkWidget *contact_chooser = NULL;
236 #endif /* MODEST_ABOOK_API < 4 */
237
238         GList *contacts_list = NULL;
239         GSList *email_addrs_per_contact = NULL;
240         gchar *econtact_id;
241         gboolean focus_recpt_editor = FALSE;
242
243         g_return_if_fail (MODEST_IS_RECPT_EDITOR (recpt_editor));
244
245 #if MODEST_ABOOK_API < 4
246         if (!open_addressbook ()) {
247                 if (contact_model) {
248                         g_object_unref (contact_model);
249                         contact_model = NULL;
250                 }
251                 return;
252         }
253         contact_model = osso_abook_contact_model_new ();
254
255         contact_view = osso_abook_contact_selector_new_basic (contact_model);
256         osso_abook_contact_selector_set_minimum_selection (OSSO_ABOOK_CONTACT_SELECTOR (contact_view), 1);
257
258         contact_dialog = osso_abook_select_dialog_new (OSSO_ABOOK_TREE_VIEW (contact_view));
259         toplevel = gtk_widget_get_toplevel (GTK_WIDGET (recpt_editor));
260         modest_window_mgr_set_modal (modest_runtime_get_window_mgr (), GTK_WINDOW (contact_dialog), GTK_WINDOW (toplevel));
261
262         gtk_widget_show (contact_dialog);
263
264         if (gtk_dialog_run (GTK_DIALOG (contact_dialog)) == GTK_RESPONSE_OK) {
265                 contacts_list = 
266                         osso_abook_contact_selector_get_extended_selection (OSSO_ABOOK_CONTACT_SELECTOR
267                                                                              (contact_view));
268         }
269 #else /* MODEST_ABOOK_API < 4 */
270         /* TODO: figure out how to make the contact chooser modal */
271         contact_chooser = osso_abook_contact_chooser_new_with_capabilities (NULL,
272                                                                             _AB("addr_ti_dia_select_contacts"),
273                                                                             OSSO_ABOOK_CAPS_EMAIL, 
274                                                                             OSSO_ABOOK_CONTACT_ORDER_NAME);
275         /* Enable multiselection */
276         osso_abook_contact_chooser_set_maximum_selection (OSSO_ABOOK_CONTACT_CHOOSER (contact_chooser),
277                                                           G_MAXUINT);
278
279         if (gtk_dialog_run (GTK_DIALOG (contact_chooser)) == GTK_RESPONSE_OK)
280                 contacts_list = osso_abook_contact_chooser_get_selection (OSSO_ABOOK_CONTACT_CHOOSER (contact_chooser));
281         gtk_widget_destroy (contact_chooser);
282 #endif
283
284         if (contacts_list) {
285                 GList *node;
286
287                 for (node = contacts_list; node != NULL; node = g_list_next (node)) {
288                         EContact *contact = (EContact *) node->data;
289
290                         email_addrs_per_contact = get_recipients_for_given_contact (contact);
291                         if (email_addrs_per_contact) {
292                                 econtact_id = (gchar *) e_contact_get_const (contact, E_CONTACT_UID);
293                                 modest_recpt_editor_add_resolved_recipient (MODEST_RECPT_EDITOR (recpt_editor), 
294                                                                             email_addrs_per_contact, econtact_id);
295                                 g_slist_foreach (email_addrs_per_contact, (GFunc) g_free, NULL);
296                                 g_slist_free (email_addrs_per_contact);
297                                 email_addrs_per_contact = NULL;
298                                 focus_recpt_editor = TRUE;
299                         }
300                 }
301                 g_list_free (contacts_list);
302         }
303
304 #if MODEST_ABOOK_API < 4
305         if (contact_model) {
306                 g_object_unref (contact_model);
307                 contact_model = NULL;
308         }
309
310         gtk_widget_destroy (contact_dialog);
311 #endif
312
313         if (focus_recpt_editor)
314                 modest_recpt_editor_grab_focus (MODEST_RECPT_EDITOR (recpt_editor));
315
316 }
317
318 /**
319  * This function returns the resolved recipients for a given EContact.
320  * If no e-mail address is defined, it launches 'Add e-mail address to contact'
321  * dialog to obtain one. If multiple e-mail addresses are found, it launches
322  * 'Select e-mail address' dialog to allow user to select one or more e-mail
323  * addresses for that contact.
324  *
325  * @param  Contact of type #EContact
326  * @return List of resolved recipient strings, to be freed by calling function.
327  */
328 static GSList *get_recipients_for_given_contact(EContact * contact)
329 {
330         gchar *givenname = NULL;
331         gchar *familyname = NULL;
332         gchar *nickname = NULL;
333         gchar *emailid = NULL;
334         const gchar *display_name = NULL;
335         GList *list = NULL;
336         gchar *formatted_string = NULL;
337         gboolean email_not_present = FALSE;
338         GSList *formattedlist = NULL, *selected_email_addr_list = NULL, *node = NULL;
339
340         if (!contact) {
341                 return NULL;
342         }
343
344         givenname = (gchar *) e_contact_get_const(contact, E_CONTACT_GIVEN_NAME);
345         familyname = (gchar *) e_contact_get_const(contact, E_CONTACT_FAMILY_NAME);
346         nickname = (gchar *) e_contact_get_const(contact, E_CONTACT_NICKNAME);
347         if (!nickname)
348                 nickname = "";
349         list = (GList *) e_contact_get(contact, E_CONTACT_EMAIL);
350
351         if (!list) {
352                 email_not_present = TRUE;
353         }
354
355         if (list && g_list_length(list) == 1) {
356                 if (list->data == NULL || g_utf8_strlen(list->data, -1) == 0) {
357                         email_not_present = TRUE;
358                 } else {
359                         emailid = g_strstrip(g_strdup(list->data));
360                         if (g_utf8_strlen(emailid, -1) == 0) {
361                                 g_free(emailid);
362                                 email_not_present = TRUE;
363                         }
364                 }
365         }
366
367         /*Launch the 'Add e-mail addr to contact' dialog if required */
368         if (email_not_present) {
369 #if MODEST_ABOOK_API < 4
370                 display_name = osso_abook_contact_get_display_name(contact);            
371 #else
372                 OssoABookContact *abook_contact;
373                
374                 abook_contact = osso_abook_contact_new_from_template (contact);
375                 display_name = osso_abook_contact_get_display_name(abook_contact);
376 #endif
377
378                 emailid = get_email_addr_from_user(display_name);
379                 if (emailid) {
380                         e_contact_set(contact, E_CONTACT_EMAIL_1, emailid);
381                         commit_contact(contact, FALSE);
382                 }
383 #if MODEST_ABOOK_API >= 4
384                 g_object_unref (abook_contact);
385 #endif
386         }
387
388         if (emailid) {
389                 if (givenname || familyname)
390                         formatted_string =
391                             ui_get_formatted_email_id(givenname, familyname, emailid);
392                 else
393                         formatted_string = g_strdup(emailid);
394                 formattedlist = g_slist_append(formattedlist, formatted_string);
395                 g_free(emailid);
396         }
397
398         /*Launch the 'Select e-mail address' dialog if required */
399         if (g_list_length(list) > 1) {
400                 selected_email_addr_list = select_email_addrs_for_contact(list);
401                 for (node = selected_email_addr_list; node != NULL; node = node->next) {
402                         if (givenname || familyname)
403                                 formatted_string =
404                                     ui_get_formatted_email_id(givenname, familyname, node->data);
405                         else
406                                 formatted_string = g_strdup(node->data);
407                         formattedlist = g_slist_append(formattedlist, formatted_string);
408                 }
409                 if (selected_email_addr_list) {
410                         g_slist_foreach(selected_email_addr_list, (GFunc) g_free, NULL);
411                         g_slist_free(selected_email_addr_list);
412                 }
413         }
414
415         if (list) {
416                 g_list_foreach(list, (GFunc) g_free, NULL);
417                 g_list_free(list);
418         }
419
420         return formattedlist;
421 }
422
423 /**
424  * This is a helper function to commit a EContact to Address_Book application.
425  *
426  * @param  contact  Contact of type #EContact
427  * @return void
428  */
429 static void 
430 commit_contact(EContact * contact, gboolean is_new)
431 {
432         g_return_if_fail (contact);
433         g_return_if_fail (book);
434
435         if (!contact || !book)
436                 return;
437
438 #if MODEST_ABOOK_API < 4
439         osso_abook_contact_commit(contact, is_new, book);
440 #else
441         if (OSSO_ABOOK_IS_CONTACT (contact)) {
442                 osso_abook_contact_commit(OSSO_ABOOK_CONTACT(contact), is_new, book, NULL);
443         } else {
444                 if (is_new)
445                         e_book_add_contact (book, contact, NULL);
446                 else
447                         e_book_commit_contact (book, contact, NULL);
448         }
449 #endif /* MODEST_ABOOK_API < 2 */
450 }
451
452 /**
453  * This is a helper function used to launch 'Add e-mail address to contact' dialog
454  * after showing appropriate notification, when there is no e-mail address defined
455  * for a selected contact.
456  *
457  * @param  given_name  Given name of the contact
458  * @param  family_name  Family name of the contact
459  * @return E-mail address string entered by user, to be freed by calling function.
460  */
461 static gchar *
462 get_email_addr_from_user(const gchar * given_name)
463 {
464         gchar *notification = NULL;
465         gchar *email_addr = NULL;
466         GtkWidget *note;
467         gboolean note_response;
468
469
470         notification = g_strdup_printf(_("mcen_nc_email_address_not_defined"), given_name);
471
472         note = hildon_note_new_confirmation (NULL, notification);
473         note_response = gtk_dialog_run (GTK_DIALOG(note));
474         gtk_widget_destroy (note);
475         g_free(notification);
476
477         if (note_response == GTK_RESPONSE_OK) {
478                 email_addr = run_add_email_addr_to_contact_dlg(given_name);
479         }
480
481         return email_addr;
482 }
483
484 /**
485 This function is used to get the formated email id with given name and sur name
486 in the format "GIVENNAME SURNAME <EMAIL ADDRESS>".
487 @param current_given_name    to hold the given name
488 @param current_sur_name      to hold the sur name
489 @param current_email_id      to hold the email id. 
490 @return gchar* string to be freed by calling function
491 */
492 static gchar *
493 ui_get_formatted_email_id(gchar * current_given_name,
494                           gchar * current_sur_name, gchar * current_email_id)
495 {
496         GString *email_id_str = NULL;
497
498         email_id_str = g_string_new(NULL);
499
500         if ((current_given_name != NULL) && ((strlen(current_given_name) != 0))
501             && (current_sur_name != NULL) && ((strlen(current_sur_name) != 0))) {
502                 g_string_append_printf(email_id_str, "%s %s", current_given_name, current_sur_name);
503         } else if ((current_given_name != NULL) && (strlen(current_given_name) != 0)) {
504                 g_string_append_printf(email_id_str, "%s", current_given_name);
505         } else if ((current_sur_name != NULL) && (strlen(current_sur_name) != 0)) {
506                 g_string_append_printf(email_id_str, "%s", current_sur_name);
507         }
508         if (g_utf8_strchr (email_id_str->str, -1, ' ')) {
509                 g_string_prepend_c (email_id_str, '\"');
510                 g_string_append_c (email_id_str, '\"');
511         }
512         g_string_append_printf (email_id_str, " %c%s%c", '<', current_email_id, '>');
513         return g_string_free (email_id_str, FALSE);
514 }
515
516 /**
517  * This is a helper function used to create & run 'Add e-mail address to contact' dialog.
518  * It allows user to enter an e-mail address, and shows appropriate infonote if the
519  * entered string is not a valid e-mail address.
520  *
521  * @param  contact_name  Full name of the contact
522  * @return E-mail address string entered by user, to be freed by calling function.
523  */
524 static gchar *
525 run_add_email_addr_to_contact_dlg(const gchar * contact_name)
526 {
527         GtkWidget *add_email_addr_to_contact_dlg = NULL;
528         GtkSizeGroup *size_group = NULL;
529         GtkWidget *cptn_cntrl = NULL;
530         GtkWidget *name_label = NULL;
531         GtkWidget *email_entry = NULL;
532         gint result = -1;
533         gchar *new_email_addr = NULL;
534         gboolean run_dialog = TRUE;
535
536         add_email_addr_to_contact_dlg =
537             gtk_dialog_new_with_buttons(_AB("addr_ti_sel_contact"), NULL,
538                                         GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
539                                         _HL("wdgt_bd_done"), GTK_RESPONSE_ACCEPT, NULL);
540         gtk_dialog_set_has_separator(GTK_DIALOG(add_email_addr_to_contact_dlg), FALSE);
541 #ifdef MODEST_TOOLKIT_HILDON2
542         gtk_container_set_border_width (GTK_CONTAINER (GTK_DIALOG (add_email_addr_to_contact_dlg)->vbox), 
543                                         HILDON_MARGIN_DOUBLE);
544 #endif
545         /*Set app_name & state_save related tags to the window */
546
547         size_group = gtk_size_group_new(GTK_SIZE_GROUP_HORIZONTAL);
548         name_label = gtk_label_new(contact_name);
549         gtk_misc_set_alignment(GTK_MISC(name_label), 0, 0);
550         cptn_cntrl =
551             hildon_caption_new(size_group, _("mcen_ia_add_email_name"), name_label, NULL,
552                                HILDON_CAPTION_OPTIONAL);
553         gtk_box_pack_start(GTK_BOX(GTK_DIALOG(add_email_addr_to_contact_dlg)->vbox), cptn_cntrl,
554                            FALSE, FALSE, 0);
555
556         email_entry = gtk_entry_new();
557         cptn_cntrl =
558             hildon_caption_new(size_group, _("mcen_fi_add_email_name"), email_entry, NULL,
559                                HILDON_CAPTION_OPTIONAL);
560         hildon_gtk_entry_set_input_mode(GTK_ENTRY(email_entry), HILDON_GTK_INPUT_MODE_FULL);
561         gtk_box_pack_start(GTK_BOX(GTK_DIALOG(add_email_addr_to_contact_dlg)->vbox), cptn_cntrl,
562                            TRUE, TRUE, 0);
563
564         gtk_widget_show_all(add_email_addr_to_contact_dlg);
565
566         while (run_dialog) {
567                 run_dialog = FALSE;
568                 gtk_widget_grab_focus(email_entry);
569                 result = gtk_dialog_run(GTK_DIALOG(add_email_addr_to_contact_dlg));
570
571                 if (result == GTK_RESPONSE_ACCEPT) {
572                         const gchar *invalid_char_offset = NULL;
573                         new_email_addr = g_strdup(gtk_entry_get_text(GTK_ENTRY(email_entry)));
574                         new_email_addr = g_strstrip(new_email_addr);
575                         if (!modest_text_utils_validate_email_address (new_email_addr, &invalid_char_offset)) {
576                                 gtk_widget_grab_focus(email_entry);
577                                 if ((invalid_char_offset != NULL)&&(*invalid_char_offset != '\0')) {
578                                         gchar *char_in_string = g_strdup_printf ("%c", *invalid_char_offset);
579                                         gchar *message = g_strdup_printf(
580                                                 _CS("ckdg_ib_illegal_characters_entered"), 
581                                                 char_in_string);
582                                         hildon_banner_show_information (
583                                                 add_email_addr_to_contact_dlg, NULL, message );
584                                         g_free (message);
585                                 } else {
586                                         hildon_banner_show_information (add_email_addr_to_contact_dlg, NULL, _("mcen_ib_invalid_email"));
587                                         run_dialog = TRUE;
588                                 }
589                                 gtk_editable_select_region((GtkEditable *) email_entry, 0, -1);
590                                 g_free(new_email_addr);
591                                 new_email_addr = NULL;
592                         }
593                 }
594         }
595
596         gtk_widget_destroy(add_email_addr_to_contact_dlg);
597
598         return new_email_addr;
599 }
600
601 /**
602  * This is helper function to create & run 'Select e-mail address' dialog, used when
603  * multiple e-mail addresses are found for a selected contact. It allows user to select
604  * one or more e-mail addresses for that contact.
605  *
606  * @param  email_addr_list  List of e-mail addresses for that contact
607  * @return List of user selected e-mail addresses, to be freed by calling function.
608  */
609 static GSList *
610 select_email_addrs_for_contact(GList * email_addr_list)
611 {
612         GtkWidget *select_email_addr_dlg = NULL;
613         GSList *selected_email_addr_list = NULL;
614         GList *node;
615         GtkWidget *selector;
616         gint result = -1;
617
618         if (!email_addr_list)
619                 return NULL;
620
621         select_email_addr_dlg = hildon_picker_dialog_new (NULL);
622         gtk_window_set_title (GTK_WINDOW (select_email_addr_dlg), _("mcen_ti_select_email_title"));
623
624         selector = hildon_touch_selector_new_text ();
625         for (node = email_addr_list; node != NULL && node->data != NULL; node = node->next) {
626                 gchar *email_addr;
627                 email_addr = g_strstrip(g_strdup(node->data));
628                 hildon_touch_selector_append_text (HILDON_TOUCH_SELECTOR (selector), email_addr);
629                 g_free(email_addr);
630         }
631
632         hildon_picker_dialog_set_selector (HILDON_PICKER_DIALOG (select_email_addr_dlg),
633                                            HILDON_TOUCH_SELECTOR (selector));
634         gtk_window_set_default_size (GTK_WINDOW (select_email_addr_dlg), MODEST_DIALOG_WINDOW_MAX_HEIGHT, -1);
635         
636         gtk_widget_show_all(select_email_addr_dlg);
637         result = gtk_dialog_run(GTK_DIALOG(select_email_addr_dlg));
638
639         if (result == GTK_RESPONSE_OK) {
640                 gchar *current_text;
641
642                 current_text = hildon_touch_selector_get_current_text (HILDON_TOUCH_SELECTOR (selector));
643                 selected_email_addr_list = g_slist_append (selected_email_addr_list, current_text);
644                 
645         }
646
647         gtk_widget_destroy(select_email_addr_dlg);
648         return selected_email_addr_list;
649 }
650
651
652 static gboolean /* make this public? */
653 add_to_address_book (const gchar* address)
654 {
655         EBookQuery *query;
656         GList *contacts = NULL;
657         GError *err = NULL;
658         gchar *email;
659         
660         g_return_val_if_fail (address, FALSE);
661         
662         if (!book) {
663                 if (!open_addressbook ()) {
664                         g_return_val_if_reached (FALSE);
665                 }
666         }
667         
668         g_return_val_if_fail (book, FALSE);
669
670         email = modest_text_utils_get_email_address (address);
671         
672         query = e_book_query_field_test (E_CONTACT_EMAIL, E_BOOK_QUERY_IS, email);
673         if (!e_book_get_contacts (book, query, &contacts, &err)) {
674                 g_printerr ("modest: failed to get contacts: %s",
675                             err ? err->message : "<unknown>");
676                 if (err)
677                         g_error_free (err);
678                 return FALSE;
679         }
680         e_book_query_unref (query);
681         
682         /*  we need to 'commit' it, even if we already found the email
683          * address in the addressbook; thus, it will show up in the 'recent list' */
684         if (contacts)  {                
685                 g_debug ("%s already in the address book", address);
686                 commit_contact ((EContact*)contacts->data, FALSE);
687                 
688                 g_list_foreach (contacts, (GFunc)unref_gobject, NULL);
689                 g_list_free (contacts);
690
691         } else {
692                 /* it's not yet in the addressbook, add it now! */
693                 EContact *new_contact = e_contact_new ();
694                 gchar *display_address;
695                 display_address = g_strdup (address);
696                 if (display_address) {
697                         modest_text_utils_get_display_address (display_address);
698                         if ((display_address[0] != '\0') && (strlen (display_address) != strlen (address)))
699                                 e_contact_set (new_contact, E_CONTACT_FULL_NAME, (const gpointer)display_address);
700                 }
701                 e_contact_set (new_contact, E_CONTACT_EMAIL_1, (const gpointer)email);
702                 g_free (display_address);
703                 commit_contact (new_contact, TRUE);
704                 g_debug ("%s added to address book", address);
705                 g_object_unref (new_contact);
706         }
707
708         g_free (email);
709
710         return TRUE;
711 }
712
713 static gboolean
714 show_check_names_banner (gpointer userdata)
715 {
716         GtkWidget **banner = (GtkWidget **) userdata;
717
718         gdk_threads_enter ();
719         *banner = hildon_banner_show_animation (NULL, NULL, _("mail_ib_checking_names"));
720         gdk_threads_leave ();
721
722         return FALSE;
723 }
724
725 static void
726 hide_check_names_banner (GtkWidget **banner, guint banner_timeout)
727 {
728         if (*banner != NULL) {
729                 gtk_widget_destroy (*banner);
730                 *banner = NULL;
731         } else {
732                 g_source_remove (banner_timeout);
733         }
734
735 }
736
737 gboolean
738 modest_address_book_check_names (ModestRecptEditor *recpt_editor, gboolean update_addressbook)
739 {
740         const gchar *recipients = NULL;
741         GSList *start_indexes = NULL, *end_indexes = NULL;
742         GSList *current_start, *current_end;
743         gboolean result = TRUE;
744         GtkTextBuffer *buffer;
745         gint offset_delta = 0;
746         gint last_length;
747         GtkTextIter start_iter, end_iter;
748
749         g_return_val_if_fail (MODEST_IS_RECPT_EDITOR (recpt_editor), FALSE);
750
751         recipients = modest_recpt_editor_get_recipients (recpt_editor);
752         last_length = g_utf8_strlen (recipients, -1);
753         modest_text_utils_get_addresses_indexes (recipients, &start_indexes, &end_indexes);
754
755         if (start_indexes == NULL) {
756                 if (last_length != 0) {
757                         hildon_banner_show_information (NULL, NULL, _("mcen_nc_no_matching_contacts"));
758                         return FALSE;
759                 } else {
760                         return TRUE;
761                 }
762         }
763
764         current_start = start_indexes;
765         current_end = end_indexes;
766         buffer = modest_recpt_editor_get_buffer (recpt_editor);
767
768         while (current_start != NULL) {
769                 gchar *address;
770                 gchar *start_ptr, *end_ptr;
771                 gint start_pos, end_pos;
772                 const gchar *invalid_char_position = NULL;
773                 gboolean store_address = FALSE;
774
775                 start_pos = (*((gint*) current_start->data)) + offset_delta;
776                 end_pos = (*((gint*) current_end->data)) + offset_delta;
777                
778                 start_ptr = g_utf8_offset_to_pointer (recipients, start_pos);
779                 end_ptr = g_utf8_offset_to_pointer (recipients, end_pos);
780
781                 address = g_strstrip (g_strndup (start_ptr, end_ptr - start_ptr));
782                 gtk_text_buffer_get_iter_at_offset (buffer, &start_iter, start_pos);
783                 gtk_text_buffer_get_iter_at_offset (buffer, &end_iter, end_pos);
784                 gtk_text_buffer_select_range (buffer, &start_iter, &end_iter);
785
786                 if (!modest_text_utils_validate_recipient (address, &invalid_char_position)) {
787                         if ((invalid_char_position != NULL) && (*invalid_char_position != '\0')) {
788                                 gchar *char_in_string = g_strdup_printf("%c", *invalid_char_position);
789                                 gchar *message = 
790                                         g_strdup_printf(_CS("ckdg_ib_illegal_characters_entered"), 
791                                                         char_in_string);
792                                 g_free (char_in_string);
793                                 hildon_banner_show_information (NULL, NULL, message );
794                                 g_free (message);                               
795                                 result = FALSE;
796                         } else if (strstr (address, "@") == NULL) {
797                                 /* here goes searching in addressbook */
798                                 gchar *contact_id = NULL;
799                                 GSList *resolved_addresses = NULL;
800
801                                 result = resolve_address (address, &resolved_addresses, &contact_id);
802
803                                 if (result) {
804                                         gint new_length;
805                                         /* replace string */
806                                         modest_recpt_editor_replace_with_resolved_recipient (recpt_editor,
807                                                                                              &start_iter, &end_iter,
808                                                                                              resolved_addresses, 
809                                                                                              contact_id);
810                                         g_free (contact_id);
811                                         g_slist_foreach (resolved_addresses, (GFunc) g_free, NULL);
812                                         g_slist_free (resolved_addresses);
813
814                                         /* update offset delta */
815                                         recipients = modest_recpt_editor_get_recipients (recpt_editor);
816                                         new_length = g_utf8_strlen (recipients, -1);
817                                         offset_delta = offset_delta + new_length - last_length;
818                                         last_length = new_length;                                       
819                                 }
820                         } else {
821                                 /* this address is not valid, select it and return control to user showing banner */
822                                 hildon_banner_show_information (NULL, NULL, _("mcen_ib_invalid_email"));
823                                 result = FALSE;
824                         }
825                 } else {
826                         GSList *tags, *node;
827                         gboolean has_recipient = FALSE;
828
829                         tags = gtk_text_iter_get_tags (&start_iter);
830                         for (node = tags; node != NULL; node = g_slist_next (node)) {
831                                 GtkTextTag *tag = GTK_TEXT_TAG (node->data);
832                                 if (g_object_get_data (G_OBJECT (tag), "recipient-tag-id") != NULL) {
833                                         has_recipient = TRUE;
834                                         break;
835                                 }
836                         }
837                         g_slist_free (tags);
838                         if (!has_recipient) {
839                                 GSList * address_list = NULL;
840
841                                 address_list = g_slist_prepend (address_list, address);
842                                 modest_recpt_editor_replace_with_resolved_recipient (recpt_editor,
843                                                                                      &start_iter, &end_iter,
844                                                                                      address_list, 
845                                                                                      "");
846                                 g_slist_free (address_list);
847                                 store_address = TRUE;
848                         }
849                 }
850
851                 /* so, it seems a valid address */
852                 /* note: adding it the to the addressbook if it did not exist yet,
853                  * and adding it to the recent_list */
854                 if (result && update_addressbook && store_address)
855                         add_to_address_book (address);
856
857                 g_free (address);
858                 if (result == FALSE)
859                         break;
860
861                 current_start = g_slist_next (current_start);
862                 current_end = g_slist_next (current_end);
863         }
864
865         if (current_start == NULL) {
866                 gtk_text_buffer_get_end_iter (buffer, &end_iter);
867                 gtk_text_buffer_place_cursor (buffer, &end_iter);
868         }
869
870         g_slist_foreach (start_indexes, (GFunc) g_free, NULL);
871         g_slist_foreach (end_indexes, (GFunc) g_free, NULL);
872         g_slist_free (start_indexes);
873         g_slist_free (end_indexes);
874
875         return result;
876
877 }
878
879 typedef struct _GetContactsInfo {
880         GMainLoop *mainloop;
881         GList *result;
882 } GetContactsInfo;
883
884 static void 
885 get_contacts_for_name_cb (EBook *book, 
886                           EBookStatus status, 
887                           GList *list, 
888                           gpointer userdata)
889 {
890         GetContactsInfo *info = (GetContactsInfo *) userdata;
891
892         if (status == E_BOOK_ERROR_OK)
893                 info->result = list;
894
895         g_main_loop_quit (info->mainloop);
896 }
897
898 static GList *
899 get_contacts_for_name (const gchar *name)
900 {
901         EBookQuery *full_name_book_query = NULL;
902         GList *result;
903         gchar *unquoted;
904         GetContactsInfo *info;
905
906         if (name == NULL)
907                 return NULL;
908
909         unquoted = unquote_string (name);
910         full_name_book_query = e_book_query_field_test (E_CONTACT_FULL_NAME, E_BOOK_QUERY_CONTAINS, unquoted);
911         g_free (unquoted);
912
913         /* TODO: Make it launch a mainloop */
914         info = g_slice_new (GetContactsInfo);
915         info->mainloop = g_main_loop_new (NULL, FALSE);
916         info->result = NULL;
917         if (e_book_async_get_contacts (book, full_name_book_query, get_contacts_for_name_cb, info) == 0) {
918                 GDK_THREADS_LEAVE ();
919                 g_main_loop_run (info->mainloop);
920                 GDK_THREADS_ENTER ();
921         } 
922         result = info->result;
923         e_book_query_unref (full_name_book_query);
924         g_main_loop_unref (info->mainloop);
925         g_slice_free (GetContactsInfo, info);
926
927         return result;
928 }
929
930 static GList *
931 select_contacts_for_name_dialog (const gchar *name)
932 {
933         EBookQuery *full_name_book_query = NULL;
934         EBookView *book_view = NULL;
935         GList *result = NULL;
936         gchar *unquoted;
937
938         unquoted = unquote_string (name);
939         full_name_book_query = e_book_query_field_test (E_CONTACT_FULL_NAME, E_BOOK_QUERY_CONTAINS, unquoted);
940         g_free (unquoted);
941         e_book_get_book_view (book, full_name_book_query, NULL, -1, &book_view, NULL);
942         e_book_query_unref (full_name_book_query);
943
944         if (book_view) {
945                 GtkWidget *contact_dialog = NULL;
946 #if MODEST_ABOOK_API < 4
947                 GtkWidget *contact_view = NULL;
948                 osso_abook_tree_model_set_book_view (OSSO_ABOOK_TREE_MODEL (contact_model), book_view);
949                 e_book_view_start (book_view);
950
951                 contact_view = osso_abook_contact_selector_new_basic (contact_model);
952                 contact_dialog = osso_abook_select_dialog_new (OSSO_ABOOK_TREE_VIEW (contact_view));
953
954                 if (gtk_dialog_run (GTK_DIALOG (contact_dialog)) == GTK_RESPONSE_OK) {
955                         result = osso_abook_contact_view_get_selection (OSSO_ABOOK_CONTACT_VIEW (contact_view));
956                 }
957                 e_book_view_stop (book_view);
958                 g_object_unref (book_view);
959                 gtk_widget_destroy (contact_dialog);
960 #else /* MODEST_ABOOK_API < 4 */
961                 osso_abook_list_store_set_book_view (OSSO_ABOOK_LIST_STORE (contact_model), book_view);
962                 e_book_view_start (book_view);
963
964                 /* TODO: figure out how to make the contact chooser modal */
965                 contact_dialog = osso_abook_contact_chooser_new_with_capabilities (NULL,
966                                                                                    _AB("addr_ti_dia_select_contacts"),
967                                                                                    OSSO_ABOOK_CAPS_EMAIL,
968                                                                                    OSSO_ABOOK_CONTACT_ORDER_NAME);
969                 osso_abook_contact_chooser_set_model (OSSO_ABOOK_CONTACT_CHOOSER (contact_dialog),
970                                                       contact_model);
971
972                 if (gtk_dialog_run (GTK_DIALOG (contact_dialog)) == GTK_RESPONSE_OK)
973                         result = osso_abook_contact_chooser_get_selection (OSSO_ABOOK_CONTACT_CHOOSER (contact_dialog));
974                 e_book_view_stop (book_view);
975                 g_object_unref (book_view);
976                 gtk_widget_destroy (contact_dialog);
977 #endif /* MODEST_ABOOK_API < 4 */
978         }
979
980         return result;
981 }
982
983 static gboolean
984 resolve_address (const gchar *address, GSList **resolved_addresses, gchar **contact_id)
985 {
986         GList *resolved_contacts;
987         guint banner_timeout;
988         GtkWidget *banner = NULL;
989
990         banner_timeout = g_timeout_add (500, show_check_names_banner, &banner);
991
992         contact_model = osso_abook_contact_model_new ();
993         if (!open_addressbook_sync ()) {
994                 if (contact_model) {
995                         g_object_unref (contact_model);
996                         contact_model = NULL;
997                 }
998                 return FALSE;
999         }
1000
1001         resolved_contacts = get_contacts_for_name (address);
1002
1003         if (resolved_contacts == NULL) {
1004                 /* no matching contacts for the search string */
1005                 modest_platform_run_information_dialog (NULL, _("mcen_nc_no_matching_contacts"), FALSE);
1006                 hide_check_names_banner (&banner, banner_timeout);
1007      
1008                 return FALSE;
1009         }
1010
1011         if (g_list_length (resolved_contacts) > 1) {
1012                 /* show a dialog to select the contact from the resolved ones */
1013                 g_list_free (resolved_contacts);
1014
1015                 hide_check_names_banner (&banner, banner_timeout);     
1016                 resolved_contacts = select_contacts_for_name_dialog (address);
1017                 banner_timeout = g_timeout_add (500, show_check_names_banner, &banner);
1018
1019         }
1020         
1021         /* get the resolved contacts (can be no contact) */
1022         if (resolved_contacts) {
1023                 gboolean found;
1024                 EContact *contact = (EContact *) resolved_contacts->data;
1025
1026                 *resolved_addresses = get_recipients_for_given_contact (contact);
1027                 hide_check_names_banner (&banner, banner_timeout);     
1028                 if (*resolved_addresses) {
1029                         *contact_id = g_strdup (e_contact_get_const (contact, E_CONTACT_UID));
1030                         found = TRUE;
1031                 } else {
1032                         found = FALSE;
1033                 }
1034
1035                 g_list_foreach (resolved_contacts, (GFunc)unref_gobject, NULL);
1036                 g_list_free (resolved_contacts);
1037
1038                 return found;
1039         } else {
1040                 /* cancelled dialog to select more than one contact or
1041                  * selected no contact */
1042                 hide_check_names_banner (&banner, banner_timeout);     
1043                 return FALSE;
1044         }
1045
1046 }
1047
1048 static gchar *
1049 unquote_string (const gchar *str)
1050 {
1051         GString *buffer;
1052         gchar *p;
1053
1054         if (str == NULL)
1055                 return NULL;
1056
1057         buffer = g_string_new_len (NULL, strlen (str));
1058         for (p = (gchar *) str; *p != '\0'; p = g_utf8_next_char (p)) {
1059                 if (*p == '"') {
1060                         p = g_utf8_next_char (p);
1061                         while ((*p != '\0')&&(*p != '"')) {
1062                                 if (*p == '\\') {
1063                                         g_string_append_unichar (buffer, g_utf8_get_char (p));
1064                                         p = g_utf8_next_char (p);
1065                                         
1066                                 }
1067                                 g_string_append_unichar (buffer, g_utf8_get_char (p));
1068                                 p = g_utf8_next_char (p);
1069                         }
1070                 } else {
1071                         g_string_append_unichar (buffer, g_utf8_get_char (p));
1072                 }
1073         }
1074
1075         return g_string_free (buffer, FALSE);
1076
1077 }
1078
1079 gboolean
1080 modest_address_book_has_address (const gchar *address)
1081 {
1082         EBookQuery *query;
1083         GList *contacts = NULL;
1084         GError *err = NULL;
1085         gchar *email;
1086         gboolean result;
1087
1088         g_return_val_if_fail (address, FALSE);
1089         
1090         if (!book) {
1091                 if (!open_addressbook ()) {
1092                         g_return_val_if_reached (FALSE);
1093                 }
1094         }
1095         
1096         g_return_val_if_fail (book, FALSE);
1097
1098         email = modest_text_utils_get_email_address (address);
1099         
1100         query = e_book_query_field_test (E_CONTACT_EMAIL, E_BOOK_QUERY_IS, email);
1101         if (!e_book_get_contacts (book, query, &contacts, &err)) {
1102                 g_printerr ("modest: failed to get contacts: %s",
1103                             err ? err->message : "<unknown>");
1104                 if (err)
1105                         g_error_free (err);
1106                 return FALSE;
1107         }
1108         e_book_query_unref (query);
1109
1110         result = (contacts != NULL);
1111         if (contacts) {
1112                 g_list_foreach (contacts, (GFunc)unref_gobject, NULL);
1113                 g_list_free (contacts);
1114         }
1115         
1116         g_free (email);
1117
1118         return result;
1119 }