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