Removed commit_contact helper function, replaced by the abook call
[modest] / src / hildon2 / modest-address-book.c
1 /* Copyright (c) 2007, Nokia Corporation
2  * All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
8  * * Redistributions of source code must retain the above copyright
9  *   notice, this list of conditions and the following disclaimer.
10  * * Redistributions in binary form must reproduce the above copyright
11  *   notice, this list of conditions and the following disclaimer in the
12  *   documentation and/or other materials provided with the distribution.
13  * * Neither the name of the Nokia Corporation nor the names of its
14  *   contributors may be used to endorse or promote products derived from
15  *   this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
18  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
19  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
20  * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
21  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 /* modest-address-book.c */
31
32 #include <config.h>
33 #include <glib/gi18n.h>
34 #include <modest-address-book.h>
35 #include <modest-text-utils.h>
36 #include <libebook/e-book.h>
37 #include <libebook/e-book-view.h>
38 #include <libebook/e-vcard.h>
39 #include "modest-hildon-includes.h"
40 #include <libosso-abook/osso-abook.h>
41 #include "modest-platform.h"
42 #include "modest-runtime.h"
43 #include "widgets/modest-window-mgr.h"
44 #include "widgets/modest-ui-constants.h"
45 #include <string.h>
46 #include <gtk/gtksizegroup.h>
47 #include <gtk/gtkbox.h>
48 #include <gtk/gtklabel.h>
49 #include <gtk/gtkcellrenderertext.h>
50 #include <gtk/gtktreeselection.h>
51 #include <gtk/gtkentry.h>
52 #include <modest-maemo-utils.h>
53
54 static OssoABookContactModel *contact_model =  NULL;
55 static EBook *book = NULL;
56 static EBookView * book_view = NULL;
57
58 static GSList *get_recipients_for_given_contact (EContact * contact, gboolean *canceled);
59 static gchar *get_email_addr_from_user(const gchar * given_name, gboolean *canceled);
60 static gchar *ui_get_formatted_email_id(gchar * current_given_name,
61                                         gchar * current_sur_name, gchar * current_email_id);
62 static gchar *run_add_email_addr_to_contact_dlg(const gchar * contact_name, gboolean *canceled);
63 static GSList *select_email_addrs_for_contact(GList * email_addr_list);
64 static gboolean resolve_address (const gchar *address, GSList **resolved_addresses, GSList **contact_id, gboolean *canceled);
65 static gchar *unquote_string (const gchar *str);
66
67
68 static void
69 unref_gobject (GObject *obj)
70 {
71         if (obj)
72                 g_object_unref (obj);
73 }
74         
75
76 static void
77 get_book_view_cb (EBook *book, EBookStatus status, EBookView *bookview, gpointer data)
78 {
79         if (status != E_BOOK_ERROR_OK) {
80                 g_object_unref (book);
81                 book = NULL;
82                 return;
83         }
84         book_view = bookview;
85
86         if (contact_model)
87                 osso_abook_list_store_set_book_view (OSSO_ABOOK_LIST_STORE (contact_model),
88                                                      book_view);
89
90         e_book_view_start (book_view);
91 }
92
93 static void
94 book_open_cb (EBook *view, EBookStatus status, gpointer data)
95 {
96         EBookQuery *query = NULL;
97
98         if (status != E_BOOK_ERROR_OK) {
99                 g_object_unref (book);
100                 book = NULL;
101                 return;
102         }
103         query = e_book_query_any_field_contains ("");
104         e_book_async_get_book_view (book, query, NULL, -1, get_book_view_cb, NULL);
105         e_book_query_unref (query);
106 }
107
108 static gboolean 
109 open_addressbook ()
110 {
111         book = e_book_new_system_addressbook (NULL);
112         if (!book)
113                 return FALSE;
114
115         if (e_book_async_open (book, FALSE, book_open_cb, NULL) != E_BOOK_ERROR_OK)
116                 return FALSE;
117
118         return TRUE; /* FIXME */        
119 }
120
121 typedef struct _OpenAddressbookSyncInfo {
122         gboolean retval;
123         GMainLoop *mainloop;
124 } OpenAddressbookSyncInfo;
125
126 static void
127 get_book_view_sync_cb (EBook *book, EBookStatus status, EBookView *bookview, gpointer data)
128 {
129         OpenAddressbookSyncInfo *info = (OpenAddressbookSyncInfo *) data;
130
131         if (status != E_BOOK_ERROR_OK) {
132                 g_object_unref (book);
133                 book = NULL;
134                 info->retval = FALSE;
135                 g_main_loop_quit (info->mainloop);
136                 return;
137         }
138         book_view = bookview;
139
140         if (contact_model)
141                 osso_abook_list_store_set_book_view (OSSO_ABOOK_LIST_STORE (contact_model),
142                                                      book_view);
143
144         e_book_view_start (book_view);
145         info->retval = TRUE;
146         g_main_loop_quit (info->mainloop);
147 }
148
149 static void
150 book_open_sync_cb (EBook *view, EBookStatus status, gpointer data)
151 {
152         EBookQuery *query = NULL;
153         OpenAddressbookSyncInfo *info = (OpenAddressbookSyncInfo *) data;
154
155         if (status != E_BOOK_ERROR_OK) {
156                 g_object_unref (book);
157                 book = NULL;
158                 info->retval = FALSE;
159                 g_main_loop_quit (info->mainloop);
160                 return;
161         }
162         query = e_book_query_any_field_contains ("");
163         e_book_async_get_book_view (book, query, NULL, -1, get_book_view_sync_cb, info);
164         e_book_query_unref (query);
165 }
166
167 static gboolean
168 open_addressbook_sync ()
169 {
170         OpenAddressbookSyncInfo *info;
171         gboolean retval;
172
173         book = e_book_new_system_addressbook (NULL);
174         if (!book)
175                 return FALSE;
176
177         info = g_slice_new (OpenAddressbookSyncInfo);
178         info->mainloop = g_main_loop_new (NULL, FALSE);
179         info->retval = FALSE;
180         if (e_book_async_open (book, FALSE, book_open_sync_cb, info) == E_BOOK_ERROR_OK) {
181                 GDK_THREADS_LEAVE ();
182                 g_main_loop_run (info->mainloop);
183                 GDK_THREADS_ENTER ();
184         }
185         retval = info->retval;
186         g_main_loop_unref (info->mainloop);
187         g_slice_free (OpenAddressbookSyncInfo, info);
188         /* Make it launch a main loop */
189         return e_book_open (book, FALSE, NULL);
190 }
191
192 void
193 modest_address_book_add_address (const gchar *address)
194 {
195         GtkWidget *dialog = NULL;
196         gchar *email_address;
197         EVCardAttribute *attribute;
198
199         if (!open_addressbook ()) {
200                 return;
201         }
202
203         email_address = modest_text_utils_get_email_address (address);
204         
205         attribute = e_vcard_attribute_new (NULL, EVC_EMAIL);
206         e_vcard_attribute_add_value (attribute, email_address);
207         dialog = osso_abook_temporary_contact_dialog_new (NULL, book, attribute, NULL);
208         gtk_dialog_run (GTK_DIALOG (dialog));
209
210         gtk_widget_destroy (dialog);
211
212         e_vcard_attribute_free (attribute);
213         g_free (email_address);
214
215 }
216
217 void
218 modest_address_book_select_addresses (ModestRecptEditor *recpt_editor,
219                                       GtkWindow *parent_window)
220 {
221         GtkWidget *contact_chooser = NULL;
222         GList *contacts_list = NULL;
223         GSList *email_addrs_per_contact = NULL;
224         gchar *econtact_id;
225         gboolean focus_recpt_editor = FALSE;
226
227         g_return_if_fail (MODEST_IS_RECPT_EDITOR (recpt_editor));
228
229         /* TODO: figure out how to make the contact chooser modal */
230         contact_chooser = osso_abook_contact_chooser_new_with_capabilities (parent_window,
231                                                                             _AB("addr_ti_dia_select_contacts"),
232                                                                             OSSO_ABOOK_CAPS_EMAIL, 
233                                                                             OSSO_ABOOK_CONTACT_ORDER_NAME);
234         /* Enable multiselection */
235         osso_abook_contact_chooser_set_maximum_selection (OSSO_ABOOK_CONTACT_CHOOSER (contact_chooser),
236                                                           G_MAXUINT);
237
238         if (gtk_dialog_run (GTK_DIALOG (contact_chooser)) == GTK_RESPONSE_OK)
239                 contacts_list = osso_abook_contact_chooser_get_selection (OSSO_ABOOK_CONTACT_CHOOSER (contact_chooser));
240         gtk_widget_destroy (contact_chooser);
241
242         if (contacts_list) {
243                 GList *node;
244
245                 for (node = contacts_list; node != NULL; node = g_list_next (node)) {
246                         EContact *contact = (EContact *) node->data;
247                         gboolean canceled;
248
249                         email_addrs_per_contact = get_recipients_for_given_contact (contact, &canceled);
250                         if (email_addrs_per_contact) {
251                                 econtact_id = (gchar *) e_contact_get_const (contact, E_CONTACT_UID);
252                                 modest_recpt_editor_add_resolved_recipient (MODEST_RECPT_EDITOR (recpt_editor), 
253                                                                             email_addrs_per_contact, econtact_id);
254                                 g_slist_foreach (email_addrs_per_contact, (GFunc) g_free, NULL);
255                                 g_slist_free (email_addrs_per_contact);
256                                 email_addrs_per_contact = NULL;
257                                 focus_recpt_editor = TRUE;
258                         }
259                 }
260                 g_list_free (contacts_list);
261         }
262
263         if (focus_recpt_editor)
264                 modest_recpt_editor_grab_focus (MODEST_RECPT_EDITOR (recpt_editor));
265
266 }
267
268 /**
269  * This function returns the resolved recipients for a given EContact.
270  * If no e-mail address is defined, it launches 'Add e-mail address to contact'
271  * dialog to obtain one. If multiple e-mail addresses are found, it launches
272  * 'Select e-mail address' dialog to allow user to select one or more e-mail
273  * addresses for that contact.
274  *
275  * @param  Contact of type #EContact
276  * @return List of resolved recipient strings, to be freed by calling function.
277  */
278 static GSList *
279 get_recipients_for_given_contact (EContact * contact,
280                                   gboolean *canceled)
281 {
282         gchar *givenname = NULL;
283         gchar *familyname = NULL;
284         gchar *nickname = NULL;
285         gchar *emailid = NULL;
286         const gchar *display_name = NULL;
287         GList *list = NULL;
288         gchar *formatted_string = NULL;
289         gboolean email_not_present = FALSE;
290         GSList *formattedlist = NULL, *selected_email_addr_list = NULL, *node = NULL;
291
292         if (!contact) {
293                 return NULL;
294         }
295
296         givenname = (gchar *) e_contact_get_const(contact, E_CONTACT_GIVEN_NAME);
297         familyname = (gchar *) e_contact_get_const(contact, E_CONTACT_FAMILY_NAME);
298         nickname = (gchar *) e_contact_get_const(contact, E_CONTACT_NICKNAME);
299         if (!nickname)
300                 nickname = "";
301         list = (GList *) e_contact_get(contact, E_CONTACT_EMAIL);
302
303         if (!list) {
304                 email_not_present = TRUE;
305         }
306
307         if (list && g_list_length(list) == 1) {
308                 if (list->data == NULL || g_utf8_strlen(list->data, -1) == 0) {
309                         email_not_present = TRUE;
310                 } else {
311                         emailid = g_strstrip(g_strdup(list->data));
312                         if (g_utf8_strlen(emailid, -1) == 0) {
313                                 g_free(emailid);
314                                 email_not_present = TRUE;
315                         }
316                 }
317         }
318
319         /*Launch the 'Add e-mail addr to contact' dialog if required */
320         if (email_not_present) {
321                 OssoABookContact *abook_contact;
322
323                 abook_contact = osso_abook_contact_new_from_template (contact);
324                 display_name = osso_abook_contact_get_display_name(abook_contact);
325
326                 emailid = get_email_addr_from_user(display_name, canceled);
327                 if (emailid) {
328                         e_contact_set(contact, E_CONTACT_EMAIL_1, emailid);
329                         osso_abook_contact_commit (abook_contact, FALSE, NULL, NULL);
330                 }
331                 g_object_unref (abook_contact);
332         }
333
334         if (emailid) {
335                 if (givenname || familyname)
336                         formatted_string =
337                             ui_get_formatted_email_id(givenname, familyname, emailid);
338                 else
339                         formatted_string = g_strdup(emailid);
340                 formattedlist = g_slist_append(formattedlist, formatted_string);
341                 g_free(emailid);
342         }
343
344         /*Launch the 'Select e-mail address' dialog if required */
345         if (g_list_length(list) > 1) {
346                 selected_email_addr_list = select_email_addrs_for_contact(list);
347                 for (node = selected_email_addr_list; node != NULL; node = node->next) {
348                         if (givenname || familyname)
349                                 formatted_string =
350                                     ui_get_formatted_email_id(givenname, familyname, node->data);
351                         else
352                                 formatted_string = g_strdup(node->data);
353                         formattedlist = g_slist_append(formattedlist, formatted_string);
354                 }
355                 if (selected_email_addr_list) {
356                         g_slist_foreach(selected_email_addr_list, (GFunc) g_free, NULL);
357                         g_slist_free(selected_email_addr_list);
358                 }
359         }
360
361         if (list) {
362                 g_list_foreach(list, (GFunc) g_free, NULL);
363                 g_list_free(list);
364         }
365
366         return formattedlist;
367 }
368
369 /**
370  * This is a helper function used to launch 'Add e-mail address to contact' dialog
371  * after showing appropriate notification, when there is no e-mail address defined
372  * for a selected contact.
373  *
374  * @param  given_name  Given name of the contact
375  * @param  family_name  Family name of the contact
376  * @return E-mail address string entered by user, to be freed by calling function.
377  */
378 static gchar *
379 get_email_addr_from_user(const gchar * given_name, gboolean *canceled)
380 {
381         gchar *notification = NULL;
382         gchar *email_addr = NULL;
383         GtkWidget *note;
384         gboolean note_response;
385
386
387         notification = g_strdup_printf(_("mcen_nc_email_address_not_defined"), given_name);
388
389         note = hildon_note_new_confirmation (NULL, notification);
390         note_response = gtk_dialog_run (GTK_DIALOG(note));
391         gtk_widget_destroy (note);
392         g_free(notification);
393
394         if (note_response == GTK_RESPONSE_OK) {
395                 email_addr = run_add_email_addr_to_contact_dlg (given_name, canceled);
396         }
397
398         return email_addr;
399 }
400
401 /**
402 This function is used to get the formated email id with given name and sur name
403 in the format "GIVENNAME SURNAME <EMAIL ADDRESS>".
404 @param current_given_name    to hold the given name
405 @param current_sur_name      to hold the sur name
406 @param current_email_id      to hold the email id. 
407 @return gchar* string to be freed by calling function
408 */
409 static gchar *
410 ui_get_formatted_email_id(gchar * current_given_name,
411                           gchar * current_sur_name, gchar * current_email_id)
412 {
413         GString *email_id_str = NULL;
414
415         email_id_str = g_string_new(NULL);
416
417         if ((current_given_name != NULL) && ((strlen(current_given_name) != 0))
418             && (current_sur_name != NULL) && ((strlen(current_sur_name) != 0))) {
419                 g_string_append_printf(email_id_str, "%s %s", current_given_name, current_sur_name);
420         } else if ((current_given_name != NULL) && (strlen(current_given_name) != 0)) {
421                 g_string_append_printf(email_id_str, "%s", current_given_name);
422         } else if ((current_sur_name != NULL) && (strlen(current_sur_name) != 0)) {
423                 g_string_append_printf(email_id_str, "%s", current_sur_name);
424         }
425         if (g_utf8_strchr (email_id_str->str, -1, ' ')) {
426                 g_string_prepend_c (email_id_str, '\"');
427                 g_string_append_c (email_id_str, '\"');
428         }
429         g_string_append_printf (email_id_str, " %c%s%c", '<', current_email_id, '>');
430         return g_string_free (email_id_str, FALSE);
431 }
432
433 /**
434  * This is a helper function used to create & run 'Add e-mail address to contact' dialog.
435  * It allows user to enter an e-mail address, and shows appropriate infonote if the
436  * entered string is not a valid e-mail address.
437  *
438  * It must return TRUE in canceled if the dialog was canceled by the user
439  *
440  * @param  contact_name  Full name of the contact
441  * @return E-mail address string entered by user, to be freed by calling function.
442  */
443 static gchar *
444 run_add_email_addr_to_contact_dlg(const gchar * contact_name,
445                                   gboolean *canceled)
446 {
447         GtkWidget *add_email_addr_to_contact_dlg = NULL;
448         GtkSizeGroup *size_group = NULL;
449         GtkWidget *cptn_cntrl = NULL;
450         GtkWidget *name_label = NULL;
451         GtkWidget *email_entry = NULL;
452         gint result = -1;
453         gchar *new_email_addr = NULL;
454         gboolean run_dialog = TRUE;
455
456         g_return_val_if_fail (canceled, NULL);
457
458         *canceled = FALSE;
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                                         _HL("wdgt_bd_save"), GTK_RESPONSE_ACCEPT, NULL);
464         gtk_dialog_set_has_separator(GTK_DIALOG(add_email_addr_to_contact_dlg), FALSE);
465 #ifdef MODEST_TOOLKIT_HILDON2
466         gtk_container_set_border_width (GTK_CONTAINER (GTK_DIALOG (add_email_addr_to_contact_dlg)->vbox), 
467                                         HILDON_MARGIN_DOUBLE);
468 #endif
469         /*Set app_name & state_save related tags to the window */
470
471         size_group = gtk_size_group_new(GTK_SIZE_GROUP_HORIZONTAL);
472         name_label = gtk_label_new(contact_name);
473         gtk_misc_set_alignment(GTK_MISC(name_label), 0.0, 0.5);
474         cptn_cntrl =
475                 modest_maemo_utils_create_captioned (size_group, NULL,
476                                                      _("mcen_ia_add_email_name"), FALSE,
477                                                      name_label);
478         gtk_box_pack_start(GTK_BOX(GTK_DIALOG(add_email_addr_to_contact_dlg)->vbox), cptn_cntrl,
479                            FALSE, FALSE, 0);
480
481         email_entry = hildon_entry_new (HILDON_SIZE_FINGER_HEIGHT | HILDON_SIZE_AUTO_WIDTH);
482         cptn_cntrl = modest_maemo_utils_create_captioned (size_group, NULL, 
483                                                           _("mcen_fi_add_email_name"), FALSE,
484                                                           email_entry);
485         hildon_gtk_entry_set_input_mode(GTK_ENTRY(email_entry), HILDON_GTK_INPUT_MODE_FULL);
486         gtk_box_pack_start(GTK_BOX(GTK_DIALOG(add_email_addr_to_contact_dlg)->vbox), cptn_cntrl,
487                            TRUE, TRUE, 0);
488
489         gtk_widget_show_all(add_email_addr_to_contact_dlg);
490
491         while (run_dialog) {
492                 run_dialog = FALSE;
493                 gtk_widget_grab_focus(email_entry);
494                 result = gtk_dialog_run(GTK_DIALOG(add_email_addr_to_contact_dlg));
495
496                 if (result == GTK_RESPONSE_ACCEPT) {
497                         const gchar *invalid_char_offset = NULL;
498                         new_email_addr = g_strdup(hildon_entry_get_text(HILDON_ENTRY(email_entry)));
499                         new_email_addr = g_strstrip(new_email_addr);
500                         if (!modest_text_utils_validate_email_address (new_email_addr, &invalid_char_offset)) {
501                                 gtk_widget_grab_focus(email_entry);
502                                 if ((invalid_char_offset != NULL)&&(*invalid_char_offset != '\0')) {
503                                         gchar *char_in_string = g_strdup_printf ("%c", *invalid_char_offset);
504                                         gchar *message = g_strdup_printf(
505                                                 _CS("ckdg_ib_illegal_characters_entered"), 
506                                                 char_in_string);
507                                         g_free (char_in_string);
508                                         hildon_banner_show_information (
509                                                 add_email_addr_to_contact_dlg, NULL, message );
510                                         g_free (message);
511                                 } else {
512                                         hildon_banner_show_information (add_email_addr_to_contact_dlg, NULL, _("mcen_ib_invalid_email"));
513                                         run_dialog = TRUE;
514                                 }
515                                 gtk_editable_select_region((GtkEditable *) email_entry, 0, -1);
516                                 g_free(new_email_addr);
517                                 new_email_addr = NULL;
518                         }
519                 } else {
520                         *canceled = TRUE;
521                 }
522         }
523
524         gtk_widget_destroy(add_email_addr_to_contact_dlg);
525
526         return new_email_addr;
527 }
528
529 /**
530  * This is helper function to create & run 'Select e-mail address' dialog, used when
531  * multiple e-mail addresses are found for a selected contact. It allows user to select
532  * one or more e-mail addresses for that contact.
533  *
534  * @param  email_addr_list  List of e-mail addresses for that contact
535  * @return List of user selected e-mail addresses, to be freed by calling function.
536  */
537 static GSList *
538 select_email_addrs_for_contact(GList * email_addr_list)
539 {
540         GtkWidget *select_email_addr_dlg = NULL;
541         GSList *selected_email_addr_list = NULL;
542         GList *node;
543         GtkWidget *selector;
544         gint result = -1;
545
546         if (!email_addr_list)
547                 return NULL;
548
549         select_email_addr_dlg = hildon_picker_dialog_new (NULL);
550         gtk_window_set_title (GTK_WINDOW (select_email_addr_dlg), _("mcen_ti_select_email_title"));
551
552         selector = hildon_touch_selector_new_text ();
553         for (node = email_addr_list; node != NULL && node->data != NULL; node = node->next) {
554                 gchar *email_addr;
555                 email_addr = g_strstrip(g_strdup(node->data));
556                 hildon_touch_selector_append_text (HILDON_TOUCH_SELECTOR (selector), email_addr);
557                 g_free(email_addr);
558         }
559
560         hildon_picker_dialog_set_selector (HILDON_PICKER_DIALOG (select_email_addr_dlg),
561                                            HILDON_TOUCH_SELECTOR (selector));
562         gtk_window_set_default_size (GTK_WINDOW (select_email_addr_dlg), MODEST_DIALOG_WINDOW_MAX_HEIGHT, -1);
563
564         gtk_widget_show_all(select_email_addr_dlg);
565         result = gtk_dialog_run(GTK_DIALOG(select_email_addr_dlg));
566
567         if (result == GTK_RESPONSE_OK) {
568                 gchar *current_text;
569
570                 current_text = hildon_touch_selector_get_current_text (HILDON_TOUCH_SELECTOR (selector));
571                 selected_email_addr_list = g_slist_append (selected_email_addr_list, current_text);
572         }
573
574         gtk_widget_destroy(select_email_addr_dlg);
575         return selected_email_addr_list;
576 }
577
578 /* Assumes that the second argument (the user provided one) is a pure
579    email address without name */
580 static gint
581 compare_addresses (const gchar *address1,
582                    const gchar *mail2)
583 {
584         gint retval;
585         gchar *mail1;
586
587         mail1 = modest_text_utils_get_email_address (address1);
588         retval = g_strcmp0 (mail1, mail2);
589         g_free (mail1);
590
591         return retval;
592 }
593
594 static EContact *
595 get_contact_for_address (GList *contacts,
596                          const gchar *address)
597 {
598         EContact *retval = NULL, *contact;
599         GList *iter;
600         gchar *email;
601
602         email = modest_text_utils_get_email_address (address);
603         iter = contacts;
604         while (iter && !retval) {
605                 GList *emails = NULL;
606
607                 contact = E_CONTACT (iter->data);
608                 emails = e_contact_get (contact, E_CONTACT_EMAIL);
609                 if (emails) {
610                         /* Look for the email address */
611                         if (g_list_find_custom (emails, email, (GCompareFunc) compare_addresses))
612                                 retval = contact;
613
614                         /* Free the list */
615                         g_list_foreach (emails, (GFunc) g_free, NULL);
616                         g_list_free (emails);
617                 }
618                 iter = g_list_next (iter);
619         }
620         g_free (email);
621
622         return retval;
623 }
624
625 static void
626 async_get_contacts_cb (EBook *book,
627                        EBookStatus status,
628                        GList *contacts,
629                        gpointer closure)
630 {
631         GSList *addresses, *iter;
632         GList *to_commit_contacts, *to_add_contacts;
633         EContact *self_contact;
634
635         addresses = (GSList *) closure;
636
637         /* Check errors */
638         if (status != E_BOOK_ERROR_OK)
639                 goto frees;
640
641         self_contact = (EContact *) osso_abook_self_contact_get_default ();
642         if (self_contact) {
643                 contacts = g_list_prepend (contacts, self_contact);
644         }
645
646         iter = addresses;
647         to_commit_contacts = NULL;
648         to_add_contacts = NULL;
649         while (iter) {
650                 EContact *contact;
651                 const gchar *address;
652
653                 /* Look for a contact with such address. We perform
654                    this kind of search because we assume that users
655                    don't usually send emails to tons of addresses */
656                 address = (const gchar *) iter->data;
657                 contact = get_contact_for_address (contacts, address);
658
659                 /* Add new or commit existing contact */
660                 if (contact) {
661                         to_commit_contacts = g_list_prepend (to_commit_contacts, contact);
662                         g_debug ("----Preparing to commit contact %s", address);
663                 } else {
664                         gchar *email_address, *display_address;
665
666                         /* Create new contact and add it to the list */
667                         contact = e_contact_new ();
668                         email_address = modest_text_utils_get_email_address (address);
669                         e_contact_set (contact, E_CONTACT_EMAIL_1, email_address);
670                         g_free (email_address);
671
672                         display_address = g_strdup (address);
673                         if (display_address) {
674                                 modest_text_utils_get_display_address (display_address);
675                                 if ((display_address[0] != '\0') && (strlen (display_address) != strlen (address)))
676                                         e_contact_set (contact, E_CONTACT_FULL_NAME, (const gpointer)display_address);
677                                 g_free (display_address);
678                         }
679
680                         to_add_contacts = g_list_prepend (to_add_contacts, contact);
681                         g_debug ("----Preparing to add contact %s", address);
682                 }
683
684                 iter = g_slist_next (iter);
685         }
686
687         /* Asynchronously add contacts */
688         if (to_add_contacts)
689                 e_book_async_add_contacts (book, to_add_contacts, NULL, NULL);
690
691         /* Asynchronously commit contacts */
692         if (to_commit_contacts)
693                 e_book_async_commit_contacts (book, to_commit_contacts, NULL, NULL);
694
695         /* Free lists */
696         g_list_free (to_add_contacts);
697         g_list_free (to_commit_contacts);
698
699  frees:
700         if (addresses) {
701                 g_slist_foreach (addresses, (GFunc) g_free, NULL);
702                 g_slist_free (addresses);
703         }
704         if (contacts) {
705                 g_list_foreach (contacts, (GFunc) g_object_unref, NULL);
706                 g_list_free (contacts);
707         }
708 }
709
710
711 static void
712 add_to_address_book (GSList *addresses)
713 {
714         EBookQuery **queries, *composite_query;
715         gint num_add, i;
716
717         g_return_if_fail (addresses);
718
719         if (!book)
720                 if (!open_addressbook ())
721                         g_return_if_reached ();
722
723         /* Create the list of queries */
724         num_add = g_slist_length (addresses);
725         queries = g_malloc0 (sizeof (EBookQuery *) * num_add);
726         for (i = 0; i < num_add; i++) {
727                 gchar *email;
728
729                 email = modest_text_utils_get_email_address (g_slist_nth_data (addresses, i));
730                 queries[i] = e_book_query_field_test (E_CONTACT_EMAIL, E_BOOK_QUERY_IS, email);
731                 g_free (email);
732         }
733
734         /* Create the query */
735         composite_query = e_book_query_or (num_add, queries, TRUE);
736
737         /* Asynchronously retrieve contacts */
738         e_book_async_get_contacts (book, composite_query, async_get_contacts_cb, addresses);
739
740         /* Frees. This will unref the subqueries as well */
741         e_book_query_unref (composite_query);
742 }
743
744 typedef struct _CheckNamesInfo {
745         GtkWidget *banner;
746         guint show_banner_timeout;
747         guint hide_banner_timeout;
748         gboolean hide;
749         gboolean free_info;
750 } CheckNamesInfo;
751
752 static void
753 hide_check_names_banner (CheckNamesInfo *info)
754 {
755         if (info->show_banner_timeout > 0) {
756                 g_source_remove (info->show_banner_timeout);
757                 info->show_banner_timeout = 0;
758         }
759         if (info->hide_banner_timeout > 0) {
760                 info->hide = TRUE;
761                 return;
762         }
763
764         if (info->banner) {
765                 gtk_widget_destroy (info->banner);
766                 info->banner = NULL;
767                 info->hide = FALSE;
768         }
769
770         if (info->free_info) {
771                 g_slice_free (CheckNamesInfo, info);
772         }
773 }
774
775 static gboolean hide_banner_timeout_handler (CheckNamesInfo *info)
776 {
777         info->hide_banner_timeout = 0;
778         if (info->hide) {
779                 gtk_widget_destroy (info->banner);
780                 info->banner = NULL;
781         }
782         if (info->free_info) {
783                 g_slice_free (CheckNamesInfo, info);
784         }
785         return FALSE;
786 }
787
788 static gboolean show_banner_timeout_handler (CheckNamesInfo *info)
789 {
790         info->show_banner_timeout = 0;
791         info->banner = hildon_banner_show_animation (NULL, NULL, _("mail_ib_checking_names"));
792         info->hide_banner_timeout = g_timeout_add (1000, (GSourceFunc) hide_banner_timeout_handler, (gpointer) info);
793         return FALSE;
794 }
795
796 static void show_check_names_banner (CheckNamesInfo *info)
797 {
798         if (info->hide_banner_timeout > 0) {
799                 g_source_remove (info->hide_banner_timeout);
800                 info->hide_banner_timeout = 0;
801         }
802
803         info->hide = FALSE;
804         if (info->show_banner_timeout > 0)
805                 return;
806
807         if (info->banner == NULL) {
808                 info->show_banner_timeout = g_timeout_add (500, (GSourceFunc) show_banner_timeout_handler, (gpointer) info);
809         }
810 }
811
812 static void clean_check_names_banner (CheckNamesInfo *info)
813 {
814         if (info->hide_banner_timeout) {
815                 info->free_info = TRUE;
816         } else {
817                 if (info->show_banner_timeout) {
818                         g_source_remove (info->show_banner_timeout);
819                 }
820                 if (info->banner)
821                         gtk_widget_destroy (info->banner);
822                 g_slice_free (CheckNamesInfo, info);
823         }
824 }
825
826 void free_resolved_addresses_list (gpointer data,
827                                    gpointer ignored)
828 {
829         GSList *list = (GSList *)data;
830         g_slist_foreach (list, (GFunc) g_free, NULL);
831         g_slist_free (list);
832 }
833
834 gboolean
835 modest_address_book_check_names (ModestRecptEditor *recpt_editor, gboolean update_addressbook)
836 {
837         const gchar *recipients = NULL;
838         GSList *start_indexes = NULL, *end_indexes = NULL;
839         GSList *current_start, *current_end, *to_commit_addresses;
840         gboolean result = TRUE;
841         GtkTextBuffer *buffer;
842         gint offset_delta = 0;
843         gint last_length;
844         GtkTextIter start_iter, end_iter;
845
846         g_return_val_if_fail (MODEST_IS_RECPT_EDITOR (recpt_editor), FALSE);
847
848         recipients = modest_recpt_editor_get_recipients (recpt_editor);
849         last_length = g_utf8_strlen (recipients, -1);
850         modest_text_utils_get_addresses_indexes (recipients, &start_indexes, &end_indexes);
851
852         if (start_indexes == NULL) {
853                 if (last_length != 0) {
854                         hildon_banner_show_information (NULL, NULL, _("mcen_nc_no_matching_contacts"));
855                         return FALSE;
856                 } else {
857                         return TRUE;
858                 }
859         }
860
861         current_start = start_indexes;
862         current_end = end_indexes;
863         buffer = modest_recpt_editor_get_buffer (recpt_editor);
864         to_commit_addresses = NULL;
865
866         while (current_start != NULL) {
867                 gchar *address;
868                 gchar *start_ptr, *end_ptr;
869                 gint start_pos, end_pos;
870                 const gchar *invalid_char_position = NULL;
871                 gboolean store_address = FALSE;
872
873                 start_pos = (*((gint*) current_start->data)) + offset_delta;
874                 end_pos = (*((gint*) current_end->data)) + offset_delta;
875                
876                 start_ptr = g_utf8_offset_to_pointer (recipients, start_pos);
877                 end_ptr = g_utf8_offset_to_pointer (recipients, end_pos);
878
879                 address = g_strstrip (g_strndup (start_ptr, end_ptr - start_ptr));
880                 gtk_text_buffer_get_iter_at_offset (buffer, &start_iter, start_pos);
881                 gtk_text_buffer_get_iter_at_offset (buffer, &end_iter, end_pos);
882                 gtk_text_buffer_select_range (buffer, &start_iter, &end_iter);
883
884                 if (!modest_text_utils_validate_recipient (address, &invalid_char_position)) {
885                         if ((invalid_char_position != NULL) && (*invalid_char_position != '\0')) {
886                                 gchar *char_in_string = g_strdup_printf("%c", *invalid_char_position);
887                                 gchar *message = 
888                                         g_strdup_printf(_CS("ckdg_ib_illegal_characters_entered"), 
889                                                         char_in_string);
890                                 g_free (char_in_string);
891                                 hildon_banner_show_information (NULL, NULL, message );
892                                 g_free (message);
893                                 result = FALSE;
894                         } else if (strstr (address, "@") == NULL) {
895                                 /* here goes searching in addressbook */
896                                 gboolean canceled;
897                                 GSList *contact_ids = NULL;
898                                 GSList *resolved_addresses = NULL;
899
900                                 result = resolve_address (address, &resolved_addresses, &contact_ids, &canceled);
901
902                                 if (result) {
903                                         gint new_length;
904
905                                         modest_recpt_editor_replace_with_resolved_recipients (recpt_editor,
906                                                                                               &start_iter, &end_iter,
907                                                                                               resolved_addresses,
908                                                                                               contact_ids);
909                                         g_slist_foreach (contact_ids, (GFunc) g_free, NULL);
910                                         g_slist_foreach (resolved_addresses, free_resolved_addresses_list, NULL);
911                                         g_slist_free (contact_ids);
912                                         g_slist_free (resolved_addresses);
913
914                                         /* update offset delta */
915                                         recipients = modest_recpt_editor_get_recipients (recpt_editor);
916                                         new_length = g_utf8_strlen (recipients, -1);
917                                         offset_delta = offset_delta + new_length - last_length;
918                                         last_length = new_length;
919                                 } else {
920                                         if (canceled) {
921                                                 /* We have to remove the recipient if not resolved */
922                                                 modest_recpt_editor_replace_with_resolved_recipient (recpt_editor,
923                                                                                                      &start_iter, 
924                                                                                                      &end_iter,
925                                                                                                      NULL,
926                                                                                                      NULL);
927                                         } else {
928                                                 /* There is no contact with that name so it's not
929                                                    valid. Don't show any error because it'll be done
930                                                    later */
931                                                 result = FALSE;
932                                         }
933                                 }
934                         } else {
935                                 /* this address is not valid, select it and return control to user showing banner */
936                                 hildon_banner_show_information (NULL, NULL, _("mcen_ib_invalid_email"));
937                                 result = FALSE;
938                         }
939                 } else {
940                         GSList *tags, *node;
941                         gboolean has_recipient = FALSE;
942
943                         tags = gtk_text_iter_get_tags (&start_iter);
944                         for (node = tags; node != NULL; node = g_slist_next (node)) {
945                                 GtkTextTag *tag = GTK_TEXT_TAG (node->data);
946                                 if (g_object_get_data (G_OBJECT (tag), "recipient-tag-id") != NULL) {
947                                         has_recipient = TRUE;
948                                         break;
949                                 }
950                         }
951                         g_slist_free (tags);
952                         if (!has_recipient) {
953                                 GSList * address_list = NULL;
954
955                                 address_list = g_slist_prepend (address_list, address);
956                                 modest_recpt_editor_replace_with_resolved_recipient (recpt_editor,
957                                                                                      &start_iter, &end_iter,
958                                                                                      address_list, 
959                                                                                      "");
960                                 g_slist_free (address_list);
961                                 store_address = TRUE;
962                         }
963                 }
964
965                 /* so, it seems a valid address */
966                 /* note: adding it the to the addressbook if it did not exist yet,
967                  * and adding it to the recent_list */
968                 if (result && update_addressbook && store_address)
969                         to_commit_addresses = g_slist_prepend (to_commit_addresses, address);
970                 else
971                         g_free (address);
972
973                 if (result == FALSE)
974                         break;
975
976                 current_start = g_slist_next (current_start);
977                 current_end = g_slist_next (current_end);
978         }
979
980         /* Add addresses to address-book */
981         if (to_commit_addresses)
982                 add_to_address_book (to_commit_addresses);
983
984         if (current_start == NULL) {
985                 gtk_text_buffer_get_end_iter (buffer, &end_iter);
986                 gtk_text_buffer_place_cursor (buffer, &end_iter);
987         }
988
989         g_slist_foreach (start_indexes, (GFunc) g_free, NULL);
990         g_slist_foreach (end_indexes, (GFunc) g_free, NULL);
991         g_slist_free (start_indexes);
992         g_slist_free (end_indexes);
993
994         return result;
995
996 }
997
998 typedef struct _GetContactsInfo {
999         GMainLoop *mainloop;
1000         GList *result;
1001 } GetContactsInfo;
1002
1003 static void 
1004 get_contacts_for_name_cb (EBook *book, 
1005                           EBookStatus status, 
1006                           GList *list, 
1007                           gpointer userdata)
1008 {
1009         GetContactsInfo *info = (GetContactsInfo *) userdata;
1010
1011         if (status == E_BOOK_ERROR_OK)
1012                 info->result = list;
1013
1014         g_main_loop_quit (info->mainloop);
1015 }
1016
1017 static GList *
1018 get_contacts_for_name (const gchar *name)
1019 {
1020         EBookQuery *full_name_book_query = NULL;
1021         GList *result;
1022         gchar *unquoted;
1023         GetContactsInfo *info;
1024
1025         if (name == NULL)
1026                 return NULL;
1027
1028         unquoted = unquote_string (name);
1029         full_name_book_query = e_book_query_field_test (E_CONTACT_FULL_NAME, E_BOOK_QUERY_CONTAINS, unquoted);
1030         g_free (unquoted);
1031
1032         /* TODO: Make it launch a mainloop */
1033         info = g_slice_new (GetContactsInfo);
1034         info->mainloop = g_main_loop_new (NULL, FALSE);
1035         info->result = NULL;
1036         if (e_book_async_get_contacts (book, full_name_book_query, get_contacts_for_name_cb, info) == 0) {
1037                 GDK_THREADS_LEAVE ();
1038                 g_main_loop_run (info->mainloop);
1039                 GDK_THREADS_ENTER ();
1040         } 
1041         result = info->result;
1042         e_book_query_unref (full_name_book_query);
1043         g_main_loop_unref (info->mainloop);
1044         g_slice_free (GetContactsInfo, info);
1045
1046         return result;
1047 }
1048
1049 static GList *
1050 select_contacts_for_name_dialog (const gchar *name)
1051 {
1052         EBookQuery *full_name_book_query = NULL;
1053         EBookView *book_view = NULL;
1054         GList *result = NULL;
1055         gchar *unquoted;
1056
1057         unquoted = unquote_string (name);
1058         full_name_book_query = e_book_query_field_test (E_CONTACT_FULL_NAME, E_BOOK_QUERY_CONTAINS, unquoted);
1059         g_free (unquoted);
1060         e_book_get_book_view (book, full_name_book_query, NULL, -1, &book_view, NULL);
1061         e_book_query_unref (full_name_book_query);
1062
1063         if (book_view) {
1064                 GtkWidget *contact_dialog = NULL;
1065                 osso_abook_list_store_set_book_view (OSSO_ABOOK_LIST_STORE (contact_model), book_view);
1066                 e_book_view_start (book_view);
1067
1068                 /* TODO: figure out how to make the contact chooser modal */
1069                 contact_dialog = osso_abook_contact_chooser_new_with_capabilities (NULL,
1070                                                                                    _AB("addr_ti_dia_select_contacts"),
1071                                                                                    OSSO_ABOOK_CAPS_EMAIL,
1072                                                                                    OSSO_ABOOK_CONTACT_ORDER_NAME);
1073                 /* Enable multiselection */
1074                 osso_abook_contact_chooser_set_maximum_selection (OSSO_ABOOK_CONTACT_CHOOSER (contact_dialog),
1075                                                                   G_MAXUINT);
1076                 osso_abook_contact_chooser_set_model (OSSO_ABOOK_CONTACT_CHOOSER (contact_dialog),
1077                                                       contact_model);
1078
1079                 if (gtk_dialog_run (GTK_DIALOG (contact_dialog)) == GTK_RESPONSE_OK)
1080                         result = osso_abook_contact_chooser_get_selection (OSSO_ABOOK_CONTACT_CHOOSER (contact_dialog));
1081                 e_book_view_stop (book_view);
1082                 g_object_unref (book_view);
1083                 gtk_widget_destroy (contact_dialog);
1084         }
1085
1086         return result;
1087 }
1088
1089 static gboolean
1090 resolve_address (const gchar *address, 
1091                  GSList **resolved_addresses, 
1092                  GSList **contact_ids,
1093                  gboolean *canceled)
1094 {
1095         GList *resolved_contacts;
1096         CheckNamesInfo *info;;
1097
1098         g_return_val_if_fail (canceled, FALSE);
1099
1100         *resolved_addresses = NULL;
1101         *contact_ids = NULL;
1102         *canceled = FALSE;
1103         info = g_slice_new0 (CheckNamesInfo);
1104         show_check_names_banner (info);
1105         
1106         contact_model = osso_abook_contact_model_new ();
1107         if (!open_addressbook_sync ()) {
1108                 hide_check_names_banner (info);
1109                 if (contact_model) {
1110                         g_object_unref (contact_model);
1111                         contact_model = NULL;
1112                 }
1113                 clean_check_names_banner (info);
1114                 return FALSE;
1115         }
1116
1117         resolved_contacts = get_contacts_for_name (address);
1118         hide_check_names_banner (info);
1119
1120         if (resolved_contacts == NULL) {
1121                 /* no matching contacts for the search string */
1122                 modest_platform_run_information_dialog (NULL, _("mcen_nc_no_matching_contacts"), FALSE);
1123                 clean_check_names_banner (info);
1124                 return FALSE;
1125         }
1126
1127         if (g_list_length (resolved_contacts) > 1) {
1128                 /* show a dialog to select the contact from the resolved ones */
1129                 g_list_free (resolved_contacts);
1130
1131                 resolved_contacts = select_contacts_for_name_dialog (address);
1132         }
1133
1134         /* get the resolved contacts (can be no contact) */
1135         if (resolved_contacts) {
1136                 GList *node;
1137                 gboolean found = FALSE;
1138
1139                 for (node = resolved_contacts; node != NULL; node = g_list_next (node)) {
1140                         EContact *contact = (EContact *) node->data;
1141                         GSList *resolved;
1142                         gchar *contact_id;
1143
1144                         resolved = get_recipients_for_given_contact (contact, canceled);
1145                         if (resolved) {
1146                                 contact_id = g_strdup (e_contact_get_const (contact, E_CONTACT_UID));
1147                                 *contact_ids = g_slist_append (*contact_ids, contact_id);
1148                                 found = TRUE;
1149                                 *resolved_addresses = g_slist_append (*resolved_addresses, resolved);
1150                         }
1151                 }
1152
1153                 g_list_foreach (resolved_contacts, (GFunc)unref_gobject, NULL);
1154                 g_list_free (resolved_contacts);
1155                 clean_check_names_banner (info);
1156
1157                 return found;
1158         } else {
1159                 /* cancelled dialog to select more than one contact or
1160                  * selected no contact */
1161                 clean_check_names_banner (info);
1162                 return FALSE;
1163         }
1164
1165 }
1166
1167 static gchar *
1168 unquote_string (const gchar *str)
1169 {
1170         GString *buffer;
1171         gchar *p;
1172
1173         if (str == NULL)
1174                 return NULL;
1175
1176         buffer = g_string_new_len (NULL, strlen (str));
1177         for (p = (gchar *) str; *p != '\0'; p = g_utf8_next_char (p)) {
1178                 if (*p == '"') {
1179                         p = g_utf8_next_char (p);
1180                         while ((*p != '\0')&&(*p != '"')) {
1181                                 if (*p == '\\') {
1182                                         g_string_append_unichar (buffer, g_utf8_get_char (p));
1183                                         p = g_utf8_next_char (p);
1184
1185                                 }
1186                                 g_string_append_unichar (buffer, g_utf8_get_char (p));
1187                                 p = g_utf8_next_char (p);
1188                         }
1189                 } else {
1190                         g_string_append_unichar (buffer, g_utf8_get_char (p));
1191                 }
1192         }
1193
1194         return g_string_free (buffer, FALSE);
1195
1196 }
1197
1198 gboolean
1199 modest_address_book_has_address (const gchar *address)
1200 {
1201         EBookQuery *query;
1202         GList *contacts = NULL;
1203         GError *err = NULL;
1204         gchar *email;
1205         gboolean result;
1206
1207         g_return_val_if_fail (address, FALSE);
1208         
1209         if (!book) {
1210                 if (!open_addressbook ()) {
1211                         g_return_val_if_reached (FALSE);
1212                 }
1213         }
1214         
1215         g_return_val_if_fail (book, FALSE);
1216
1217         email = modest_text_utils_get_email_address (address);
1218         
1219         query = e_book_query_field_test (E_CONTACT_EMAIL, E_BOOK_QUERY_IS, email);
1220         if (!e_book_get_contacts (book, query, &contacts, &err)) {
1221                 g_printerr ("modest: failed to get contacts: %s",
1222                             err ? err->message : "<unknown>");
1223                 if (err)
1224                         g_error_free (err);
1225                 g_free (email);
1226                 e_book_query_unref (query);
1227                 return FALSE;
1228         }
1229         e_book_query_unref (query);
1230
1231         result = (contacts != NULL);
1232         if (contacts) {
1233                 g_list_foreach (contacts, (GFunc)unref_gobject, NULL);
1234                 g_list_free (contacts);
1235         }
1236         
1237         g_free (email);
1238
1239         return result;
1240 }
1241
1242 const gchar *
1243 modest_address_book_get_my_name ()
1244 {
1245         OssoABookSelfContact *self_contact = osso_abook_self_contact_get_default ();
1246
1247         /* We are not using osso_abook_contact_get_display_name
1248            because that method fallbacks to another fields if the name
1249            is not defined */
1250         if (self_contact)
1251                 return e_contact_get ((EContact *) self_contact, E_CONTACT_FULL_NAME);
1252         else
1253                 return NULL;
1254 }