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