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