2012-07-07 [colin] 3.8.1cvs7
[claws.git] / src / addr_compl.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  *
4  * Copyright (C) 2000-2012 by Alfons Hoogervorst & The Claws Mail Team.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program. If not, see <http://www.gnu.org/licenses/>.
18  * 
19  */
20
21 #ifdef HAVE_CONFIG_H
22 #  include "config.h"
23 #include "claws-features.h"
24 #endif
25 #include "defs.h"
26
27 #include <glib.h>
28 #include <glib/gi18n.h>
29 #include <gdk/gdkkeysyms.h>
30 #include <gtk/gtk.h>
31
32 #include <string.h>
33 #include <ctype.h>
34 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
35 #  include <wchar.h>
36 #  include <wctype.h>
37 #endif
38
39 #include "addr_compl.h"
40 #include "addritem.h"
41 #include "utils.h"
42 #include "prefs_common.h"
43 #include "claws.h"
44 #include "hooks.h"
45 #include "gtkutils.h"
46 #include <pthread.h>
47
48 #ifndef USE_NEW_ADDRBOOK
49         #include "addrindex.h"
50 #else
51         #include "addressbook-dbus.h"
52 #endif
53
54 /*!
55  *\brief        For the GtkListStore
56  */
57 enum {
58         ADDR_COMPL_ICON,
59         ADDR_COMPL_ADDRESS,
60         ADDR_COMPL_ISGROUP,
61         ADDR_COMPL_GROUPLIST,
62         N_ADDR_COMPL_COLUMNS
63 };
64
65 /*
66  * How it works:
67  *
68  * The address book is read into memory. We set up an address list
69  * containing all address book entries. Next we make the completion
70  * list, which contains all the completable strings, and store a
71  * reference to the address entry it belongs to.
72  * After calling the g_completion_complete(), we get a reference
73  * to a valid email address.  
74  *
75  * Completion is very simplified. We never complete on another prefix,
76  * i.e. we neglect the next smallest possible prefix for the current
77  * completion cache. This is simply done so we might break up the
78  * addresses a little more (e.g. break up alfons@proteus.demon.nl into
79  * something like alfons, proteus, demon, nl; and then completing on
80  * any of those words).
81  */
82
83 /**
84  * completion_entry - structure used to complete addresses, with a reference
85  * the the real address information.
86  */
87 typedef struct
88 {
89         gchar           *string; /* string to complete */
90         address_entry   *ref;    /* address the string belongs to  */
91 } completion_entry;
92
93 /*******************************************************************************/
94
95 static gint         g_ref_count;        /* list ref count */
96 static GList       *g_completion_list = NULL;   /* list of strings to be checked */
97 static GList       *g_address_list = NULL;      /* address storage */
98 static GCompletion *g_completion;       /* completion object */
99
100 static GHashTable *_groupAddresses_ = NULL;
101 static gboolean _allowCommas_ = TRUE;
102
103 /* To allow for continuing completion we have to keep track of the state
104  * using the following variables. No need to create a context object. */
105
106 static gint         g_completion_count;         /* nr of addresses incl. the prefix */
107 static gint         g_completion_next;          /* next prev address */
108 static GSList      *g_completion_addresses;     /* unique addresses found in the
109                                                    completion cache. */
110 static gchar       *g_completion_prefix;        /* last prefix. (this is cached here
111                                                  * because the prefix passed to g_completion
112                                                  * is g_utf8_strdown()'ed */
113
114 static gchar *completion_folder_path = NULL;
115
116 /*******************************************************************************/
117
118 /*
119  * Define the structure of the completion window.
120  */
121 typedef struct _CompletionWindow CompletionWindow;
122 struct _CompletionWindow {
123         gint      listCount;
124         gchar     *searchTerm;
125         GtkWidget *window;
126         GtkWidget *entry;
127         GtkWidget *list_view;
128
129         gboolean   in_mouse;    /*!< mouse press pending... */
130         gboolean   destroying;  /*!< destruction in progress */
131 };
132
133 static GtkListStore *addr_compl_create_store    (void);
134
135 static GtkWidget *addr_compl_list_view_create   (CompletionWindow *window);
136
137 static void addr_compl_create_list_view_columns (GtkWidget *list_view);
138
139 static gboolean list_view_button_press          (GtkWidget *widget, 
140                                                  GdkEventButton *event,
141                                                  CompletionWindow *window);
142
143 static gboolean list_view_button_release        (GtkWidget *widget, 
144                                                  GdkEventButton *event,
145                                                  CompletionWindow *window);
146
147 static gboolean addr_compl_selected             (GtkTreeSelection *selector,
148                                                  GtkTreeModel *model, 
149                                                  GtkTreePath *path,
150                                                  gboolean currently_selected,
151                                                  gpointer data);
152                                                  
153 static gboolean addr_compl_defer_select_destruct(CompletionWindow *window);
154
155 /**
156  * Function used by GTK to find the string data to be used for completion.
157  * \param data Pointer to data being processed.
158  */
159 static gchar *completion_func(gpointer data)
160 {
161         cm_return_val_if_fail(data != NULL, NULL);
162
163         return ((completion_entry *)data)->string;
164
165
166 /**
167  * Initialize all completion index data.
168  */
169 static void init_all(void)
170 {
171         g_completion = g_completion_new(completion_func);
172         cm_return_if_fail(g_completion != NULL);
173 }
174
175 static void free_all_addresses(void)
176 {
177         GList *walk;
178         if (!g_address_list)
179                 return;
180         walk = g_address_list;
181         for (; walk != NULL; walk = g_list_next(walk)) {
182                 address_entry *ae = (address_entry *) walk->data;
183                 g_free(ae->name);
184                 g_free(ae->address);
185                 g_list_free(ae->grp_emails);
186                 g_free(walk->data);
187         }
188         g_list_free(g_address_list);
189         g_address_list = NULL;
190         if (_groupAddresses_)
191                 g_hash_table_destroy(_groupAddresses_);
192         _groupAddresses_ = NULL;
193 }
194
195 static void clear_completion_cache(void);
196 static void free_completion_list(void)
197 {
198         GList *walk;
199         if (!g_completion_list)
200                 return;
201         
202         clear_completion_cache();
203         if (g_completion)
204                 g_completion_clear_items(g_completion);
205
206         walk = g_list_first(g_completion_list);
207         for (; walk != NULL; walk = g_list_next(walk)) {
208                 completion_entry *ce = (completion_entry *) walk->data;
209                 g_free(ce->string);
210                 g_free(walk->data);
211         }
212         g_list_free(g_completion_list);
213         g_completion_list = NULL;
214 }
215 /**
216  * Free up all completion index data.
217  */
218 static void free_all(void)
219 {
220         free_completion_list(); 
221         free_all_addresses();   
222         g_completion_free(g_completion);
223         g_completion = NULL;
224 }
225
226 /**
227  * Append specified address entry to the index.
228  * \param str Index string value.
229  * \param ae  Entry containing address data.
230  */
231 void addr_compl_add_address1(const char *str, address_entry *ae)
232 {
233         completion_entry *ce1;
234         ce1 = g_new0(completion_entry, 1),
235         /* GCompletion list is case sensitive */
236         ce1->string = g_utf8_strdown(str, -1);
237         ce1->ref = ae;
238
239         g_completion_list = g_list_prepend(g_completion_list, ce1);
240 }
241
242 /**
243  * Adds address to the completion list. This function looks complicated, but
244  * it's only allocation checks. Each value will be included in the index.
245  * \param name    Recipient name.
246  * \param address EMail address.
247  * \param alias   Alias to append.
248  * \param grp_emails the emails in case of a group. List should be freed later, 
249  * but not its strings
250  * \return <code>0</code> if entry appended successfully, or <code>-1</code>
251  *         if failure.
252  */
253 static gint add_address(const gchar *name, const gchar *address, 
254                         const gchar *nick, const gchar *alias, GList *grp_emails)
255 {
256         address_entry    *ae;
257         gboolean is_group = FALSE;
258
259         if (!name || !address) {
260                 if (!address && !nick && !alias && grp_emails) {
261                         is_group = TRUE;
262                 } else
263                         return -1;
264         }
265
266         ae = g_new0(address_entry, 1);
267
268         cm_return_val_if_fail(ae != NULL, -1);
269
270         ae->name    = g_strdup(name);
271         ae->address = g_strdup(address);
272         ae->grp_emails = grp_emails;
273         g_address_list = g_list_prepend(g_address_list, ae);
274
275         addr_compl_add_address1(name, ae);
276         if (address != NULL && *address != '\0')
277                 addr_compl_add_address1(address, ae);
278
279         if (nick != NULL && *nick != '\0')
280                 addr_compl_add_address1(nick, ae);
281
282         if ( alias != NULL && *alias != '\0') {
283                 addr_compl_add_address1(alias, ae);
284         }
285
286         return 0;
287 }
288
289 /**
290  * Read address book, creating all entries in the completion index.
291  */ 
292 static void read_address_book(gchar *folderpath) {
293         free_all_addresses();
294         free_completion_list();
295
296 #ifndef USE_NEW_ADDRBOOK
297         addrindex_load_completion( add_address, folderpath );
298 #else
299         GError* error = NULL;
300         
301         addrcompl_initialize();
302         if (! addrindex_dbus_load_completion(add_address, &error)) {
303                 g_warning("Failed to populate address completion list");
304         g_error_free(error);
305                 return;
306         }
307 #endif
308         /* plugins may hook in here to modify/extend the completion list */
309         hooks_invoke(ADDDRESS_COMPLETION_BUILD_ADDRESS_LIST_HOOKLIST, &g_address_list);
310
311         g_address_list = g_list_reverse(g_address_list);
312         g_completion_list = g_list_reverse(g_completion_list);
313         /* merge the completion entry list into g_completion */
314         if (g_completion_list) {
315                 g_completion_add_items(g_completion, g_completion_list);
316                 if (debug_get_mode())
317                         debug_print("read %d items in %s\n",
318                                 g_list_length(g_completion_list),
319                                 folderpath?folderpath:"(null)");
320         }
321 }
322
323 /**
324  * Test whether there is a completion pending.
325  * \return <code>TRUE</code> if pending.
326  */
327 static gboolean is_completion_pending(void)
328 {
329         /* check if completion pending, i.e. we might satisfy a request for the next
330          * or previous address */
331          return g_completion_count;
332 }
333
334 /**
335  * Clear the completion cache.
336  */
337 static void clear_completion_cache(void)
338 {
339         if (is_completion_pending()) {
340                 g_free(g_completion_prefix);
341
342                 if (g_completion_addresses) {
343                         g_slist_free(g_completion_addresses);
344                         g_completion_addresses = NULL;
345                 }
346
347                 g_completion_count = g_completion_next = 0;
348         }
349 }
350
351 /**
352  * Prepare completion index. This function should be called prior to attempting
353  * address completion.
354  * \return The number of addresses in the completion list.
355  */
356 gint start_address_completion(gchar *folderpath)
357 {
358         gboolean different_book = FALSE;
359         clear_completion_cache();
360
361         if (strcmp2(completion_folder_path,folderpath))
362                 different_book = TRUE;
363
364         g_free(completion_folder_path);
365         if (folderpath != NULL)
366                 completion_folder_path = g_strdup(folderpath);
367         else
368                 completion_folder_path = NULL;
369
370         if (!g_ref_count) {
371                 init_all();
372                 /* open the address book */
373                 read_address_book(folderpath);
374         } else if (different_book)
375                 read_address_book(folderpath);
376
377         g_ref_count++;
378         debug_print("start_address_completion(%s) ref count %d\n",
379                                 folderpath?folderpath:"(null)", g_ref_count);
380
381         return g_list_length(g_completion_list);
382 }
383
384 /**
385  * Retrieve a possible address (or a part) from an entry box. To make life
386  * easier, we only look at the last valid address component; address
387  * completion only works at the last string component in the entry box.
388  *
389  * \param entry Address entry field.
390  * \param start_pos Address of start position of address.
391  * \return Possible address.
392  */
393 static gchar *get_address_from_edit(GtkEntry *entry, gint *start_pos)
394 {
395         const gchar *edit_text, *p;
396         gint cur_pos;
397         gboolean in_quote = FALSE;
398         gboolean in_bracket = FALSE;
399         gchar *str;
400
401         edit_text = gtk_entry_get_text(entry);
402         if (edit_text == NULL) return NULL;
403
404         cur_pos = gtk_editable_get_position(GTK_EDITABLE(entry));
405
406         /* scan for a separator. doesn't matter if walk points at null byte. */
407         for (p = g_utf8_offset_to_pointer(edit_text, cur_pos);
408              p > edit_text;
409              p = g_utf8_prev_char(p)) {
410                 if (*p == '"') {
411                         in_quote = TRUE;
412                 } else if (!in_quote) {
413                         if (!in_bracket && *p == ',') {
414                                 break;
415                         } else if (*p == '<')
416                                 in_bracket = TRUE;
417                         else if (*p == '>')
418                                 in_bracket = FALSE;
419                 }
420         }
421
422         /* have something valid */
423         if (g_utf8_strlen(p, -1) == 0)
424                 return NULL;
425
426 #define IS_VALID_CHAR(x) \
427         (g_ascii_isalnum(x) || (x) == '"' || (x) == '<' || (((unsigned char)(x)) > 0x7f))
428
429         /* now scan back until we hit a valid character */
430         for (; *p && !IS_VALID_CHAR(*p); p = g_utf8_next_char(p))
431                 ;
432
433 #undef IS_VALID_CHAR
434
435         if (g_utf8_strlen(p, -1) == 0)
436                 return NULL;
437
438         if (start_pos) *start_pos = g_utf8_pointer_to_offset(edit_text, p);
439
440         str = g_strdup(p);
441
442         return str;
443
444
445 static gchar *get_complete_address_from_name_email(const gchar *name, const gchar *email)
446 {
447         gchar *address = NULL;
448         if (!name || name[0] == '\0')
449                 address = g_strdup_printf("<%s>", email);
450         else if (strchr_with_skip_quote(name, '"', ','))
451                 address = g_strdup_printf
452                         ("\"%s\" <%s>", name, email);
453         else
454                 address = g_strdup_printf
455                         ("%s <%s>", name, email);
456         return address;
457 }
458
459 /**
460  * Replace an incompleted address with a completed one.
461  * \param entry     Address entry field.
462  * \param newtext   New text.
463  * \param start_pos Insertion point in entry field.
464  */
465 static void replace_address_in_edit(GtkEntry *entry, const gchar *newtext,
466                              gint start_pos, gboolean is_group, GList *grp_emails)
467 {
468         if (!newtext) return;
469         gtk_editable_delete_text(GTK_EDITABLE(entry), start_pos, -1);
470         if (!is_group) {
471                 gtk_editable_insert_text(GTK_EDITABLE(entry), newtext, strlen(newtext),
472                                  &start_pos);
473         } else {
474                 gchar *addresses = NULL;
475                 GList *cur = grp_emails;
476                 for (; cur; cur = cur->next) {
477                         gchar *tmp;
478                         ItemEMail *email = (ItemEMail *)cur->data;
479                         ItemPerson *person = ( ItemPerson * ) ADDRITEM_PARENT(email);
480                         
481                         gchar *addr = get_complete_address_from_name_email(
482                                 ADDRITEM_NAME(person), email->address);
483                         if (addresses)
484                                 tmp = g_strdup_printf("%s, %s", addresses, addr);
485                         else
486                                 tmp = g_strdup_printf("%s", addr);
487                         g_free(addr);
488                         g_free(addresses);
489                         addresses = tmp;
490                 }
491                 gtk_editable_insert_text(GTK_EDITABLE(entry), addresses, strlen(addresses),
492                                  &start_pos);
493                 g_free(addresses);
494         }
495         gtk_editable_set_position(GTK_EDITABLE(entry), -1);
496 }
497
498 /**
499  * Attempt to complete an address, and returns the number of addresses found.
500  * Use <code>get_complete_address()</code> to get an entry from the index.
501  *
502  * \param  str Search string to find.
503  * \return Zero if no match was found, otherwise the number of addresses; the
504  *         original prefix (search string) will appear at index 0. 
505  */
506 guint complete_address(const gchar *str)
507 {
508         GList *result = NULL;
509         gchar *d = NULL;
510         guint  count = 0;
511         guint  cpl = 0;
512         completion_entry *ce = NULL;
513
514         cm_return_val_if_fail(str != NULL, 0);
515
516         /* g_completion is case sensitive */
517         d = g_utf8_strdown(str, -1);
518
519         clear_completion_cache();
520         g_completion_prefix = g_strdup(str);
521
522         result = g_completion_complete(g_completion, d, NULL);
523
524         count = g_list_length(result);
525         if (count) {
526                 /* create list with unique addresses  */
527                 for (cpl = 0, result = g_list_first(result);
528                      result != NULL;
529                      result = g_list_next(result)) {
530                         ce = (completion_entry *)(result->data);
531                         if (NULL == g_slist_find(g_completion_addresses,
532                                                  ce->ref)) {
533                                 cpl++;
534                                 g_completion_addresses =
535                                         g_slist_append(g_completion_addresses,
536                                                        ce->ref);
537                         }
538                 }
539                 count = cpl + 1;        /* index 0 is the original prefix */
540                 g_completion_next = 1;  /* we start at the first completed one */
541         } else {
542                 g_free(g_completion_prefix);
543                 g_completion_prefix = NULL;
544         }
545
546         g_completion_count = count;
547
548         g_free(d);
549
550         return count;
551 }
552
553 /**
554  * complete_matches_found() returns the number of matched addresses according
555  * to the completion mechanism. Unlike complete_address(), the returned value
556  * doesn't count str itself. If there's no match, it returns 0.
557  * To get a list of completion matches, see complete_address() instead.
558  */
559 guint complete_matches_found(const gchar *str)
560 {
561         GList *result = NULL;
562         gchar *d = NULL;
563
564         cm_return_val_if_fail(str != NULL, 0);
565
566         /* g_completion is case sensitive */
567         d = g_utf8_strdown(str, -1);
568
569         clear_completion_cache();
570         g_completion_prefix = g_strdup(str);
571
572         result = g_completion_complete(g_completion, d, NULL);
573
574         g_free(g_completion_prefix);
575         g_free(d);
576
577         return g_list_length(result);
578 }
579
580 /**
581  * Return a complete address from the index.
582  * \param index Index of entry that was found (by the previous call to
583  *              <code>complete_address()</code>
584  * \return Completed address string; this should be freed when done.
585  */
586 gchar *get_complete_address(gint index)
587 {
588         const address_entry *p;
589         gchar *address = NULL;
590
591         if (index < g_completion_count) {
592                 if (index == 0)
593                         address = g_strdup(g_completion_prefix);
594                 else {
595                         /* get something from the unique addresses */
596                         p = (address_entry *)g_slist_nth_data
597                                 (g_completion_addresses, index - 1);
598                         if (p != NULL && p->address != NULL) {
599                                 address = get_complete_address_from_name_email(p->name, p->address);
600                         } else if (p != NULL && p->address == NULL && p->name != NULL) {
601                                 /* that's a group */
602                                 address = g_strdup_printf("%s (%s) <!--___group___-->", p->name, _("Group"));
603                                 if (!_groupAddresses_) {
604                                         _groupAddresses_ = g_hash_table_new(NULL, g_direct_equal);
605                                 }
606                                 if (!g_hash_table_lookup(_groupAddresses_, GINT_TO_POINTER(g_str_hash(address)))) {
607                                         g_hash_table_insert(_groupAddresses_, GINT_TO_POINTER(g_str_hash(address)), p->grp_emails);
608
609                                 }
610                         }
611                 }
612         }
613
614         return address;
615 }
616
617 /**
618  * Return the next complete address match from the completion index.
619  * \return Completed address string; this should be freed when done.
620  */
621 static gchar *get_next_complete_address(void)
622 {
623         if (is_completion_pending()) {
624                 gchar *res;
625
626                 res = get_complete_address(g_completion_next);
627                 g_completion_next += 1;
628                 if (g_completion_next >= g_completion_count)
629                         g_completion_next = 0;
630
631                 return res;
632         } else
633                 return NULL;
634 }
635
636 /**
637  * Return a count of the completed matches in the completion index.
638  * \return Number of matched entries.
639  */
640 static guint get_completion_count(void)
641 {
642         if (is_completion_pending())
643                 return g_completion_count;
644         else
645                 return 0;
646 }
647
648 /**
649  * Invalidate address completion index. This function should be called whenever
650  * the address book changes. This forces data to be read into the completion
651  * data.
652  * \return Number of entries in index.
653  */
654 gint invalidate_address_completion(void)
655 {
656         if (g_ref_count) {
657                 /* simply the same as start_address_completion() */
658                 debug_print("Invalidation request for address completion\n");
659                 read_address_book(completion_folder_path);
660                 clear_completion_cache();
661         }
662
663         return g_list_length(g_completion_list);
664 }
665
666 /**
667  * Finished with completion index. This function should be called after
668  * matching addresses.
669  * \return Reference count.
670  */
671 gint end_address_completion(void)
672 {
673         gboolean different_folder = FALSE;
674         clear_completion_cache();
675
676         /* reset the folderpath to NULL */
677         if (completion_folder_path) {
678                 g_free(completion_folder_path);
679                 completion_folder_path = NULL;
680                 different_folder = TRUE;
681         }
682         if (0 == --g_ref_count)
683                 free_all();
684
685         debug_print("end_address_completion ref count %d\n", g_ref_count);
686         if (g_ref_count && different_folder) {
687                 debug_print("still ref'd, different folder\n");
688                 invalidate_address_completion();
689         }
690
691         return g_ref_count; 
692 }
693
694 /**
695  * Completion window.
696  */
697 static CompletionWindow *_compWindow_ = NULL;
698
699 /**
700  * Mutex to protect callback from multiple threads.
701  */
702 static pthread_mutex_t _completionMutex_ = PTHREAD_MUTEX_INITIALIZER;
703
704 /**
705  * Completion queue list.
706  */
707 static GList *_displayQueue_ = NULL;
708 /**
709  * Current query ID.
710  */
711 static gint _queryID_ = 0;
712
713 /**
714  * Completion idle ID.
715  */
716 static guint _completionIdleID_ = 0;
717
718 /*
719  * address completion entry ui. the ui (completion list was inspired by galeon's
720  * auto completion list). remaining things powered by claws's completion engine.
721  */
722
723 #define ENTRY_DATA_TAB_HOOK     "tab_hook"      /* used to lookup entry */
724 #define ENTRY_DATA_ALLOW_COMMAS "allowcommas"   /* used to know whether to present groups */
725
726 static void address_completion_mainwindow_set_focus     (GtkWindow   *window,
727                                                          GtkWidget   *widget,
728                                                          gpointer     data);
729 static gboolean address_completion_entry_key_pressed    (GtkEntry    *entry,
730                                                          GdkEventKey *ev,
731                                                          gpointer     data);
732 static gboolean address_completion_complete_address_in_entry
733                                                         (GtkEntry    *entry,
734                                                          gboolean     next);
735 static void address_completion_create_completion_window (GtkEntry    *entry);
736
737 static gboolean completion_window_button_press
738                                         (GtkWidget       *widget,
739                                          GdkEventButton  *event,
740                                          CompletionWindow *compWin );
741
742 static gboolean completion_window_key_press
743                                         (GtkWidget       *widget,
744                                          GdkEventKey     *event,
745                                          CompletionWindow *compWin );
746 static void address_completion_create_completion_window( GtkEntry *entry_ );
747
748 /**
749  * Create a completion window object.
750  * \return Initialized completion window.
751  */
752 static CompletionWindow *addrcompl_create_window( void ) {
753         CompletionWindow *cw;
754
755         cw = g_new0( CompletionWindow, 1 );
756         cw->listCount = 0;
757         cw->searchTerm = NULL;
758         cw->window = NULL;
759         cw->entry = NULL;
760         cw->list_view = NULL;
761         cw->in_mouse = FALSE;
762         cw->destroying = FALSE;
763
764         return cw;      
765 }
766
767 /**
768  * Destroy completion window.
769  * \param cw Window to destroy.
770  */
771 static void addrcompl_destroy_window( CompletionWindow *cw ) {
772         /* Stop all searches currently in progress */
773 #ifndef USE_NEW_ADDRBOOK
774         addrindex_stop_search( _queryID_ );
775 #endif
776         /* Remove idler function... or application may not terminate */
777         if( _completionIdleID_ != 0 ) {
778                 g_source_remove( _completionIdleID_ );
779                 _completionIdleID_ = 0;
780         }
781
782         /* Now destroy window */        
783         if( cw ) {
784                 /* Clear references to widgets */
785                 cw->entry = NULL;
786                 cw->list_view = NULL;
787
788                 /* Free objects */
789                 if( cw->window ) {
790                         gtk_widget_hide( cw->window );
791                         gtk_widget_destroy( cw->window );
792                 }
793                 cw->window = NULL;
794                 cw->destroying = FALSE;
795                 cw->in_mouse = FALSE;
796         }
797         
798 }
799
800 /**
801  * Free up completion window.
802  * \param cw Window to free.
803  */
804 static void addrcompl_free_window( CompletionWindow *cw ) {
805         if( cw ) {
806                 addrcompl_destroy_window( cw );
807
808                 g_free( cw->searchTerm );
809                 cw->searchTerm = NULL;
810
811                 /* Clear references */          
812                 cw->listCount = 0;
813
814                 /* Free object */               
815                 g_free( cw );
816         }
817 }
818
819 /**
820  * Advance selection to previous/next item in list.
821  * \param list_view List to process.
822  * \param forward Set to <i>TRUE</i> to select next or <i>FALSE</i> for
823  *                previous entry.
824  */
825 static void completion_window_advance_selection(GtkTreeView *list_view, gboolean forward)
826 {
827         GtkTreeSelection *selection;
828         GtkTreeIter iter;
829         GtkTreeModel *model;
830
831         cm_return_if_fail(list_view != NULL);
832
833         selection = gtk_tree_view_get_selection(list_view);
834         if (!gtk_tree_selection_get_selected(selection, &model, &iter))
835                 return;
836
837         if (forward) { 
838                 forward = gtk_tree_model_iter_next(model, &iter);
839                 if (forward) 
840                         gtk_tree_selection_select_iter(selection, &iter);
841         } else {
842                 GtkTreePath *prev;
843
844                 prev = gtk_tree_model_get_path(model, &iter);
845                 if (!prev) 
846                         return;
847
848                 if (gtk_tree_path_prev(prev))
849                         gtk_tree_selection_select_path(selection, prev);
850                 
851                 gtk_tree_path_free(prev);
852         }
853 }
854
855 /**
856  * Resize window to accommodate maximum number of address entries.
857  * \param cw Completion window.
858  */
859 static void addrcompl_resize_window( CompletionWindow *cw ) {
860         GtkRequisition r;
861         gint x, y, width, height, depth;
862
863         /* Get current geometry of window */
864         gdk_window_get_geometry( gtk_widget_get_window( cw->window ), &x, &y, &width, &height, &depth );
865
866         /* simple _hide breaks size requisition !? */
867         gtk_widget_hide_all( cw->window );
868         gtk_widget_show_all( cw->window );
869         gtk_widget_size_request( cw->list_view, &r );
870
871         /* Adjust window height to available screen space */
872         if( y + r.height > gdk_screen_height())
873                 r.height = gdk_screen_height() - y;
874
875         gtk_widget_set_size_request(cw->window, width, r.height);
876
877         gdk_pointer_grab(gtk_widget_get_window(cw->window), TRUE,
878                          GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK |
879                          GDK_BUTTON_RELEASE_MASK,
880                          NULL, NULL, GDK_CURRENT_TIME);
881         gdk_keyboard_grab(gtk_widget_get_window(cw->window), FALSE, GDK_CURRENT_TIME);
882         gtk_grab_add(cw->window);
883
884 }
885
886 static GdkPixbuf *group_pixbuf = NULL;
887 static GdkPixbuf *email_pixbuf = NULL;
888
889 /**
890  * Add an address the completion window address list.
891  * \param cw      Completion window.
892  * \param address Address to add.
893  */
894 static void addrcompl_add_entry( CompletionWindow *cw, gchar *address ) {
895         GtkListStore *store;
896         GtkTreeIter iter;
897         GtkTreeSelection *selection;
898         gboolean is_group = FALSE;
899         GList *grp_emails = NULL;
900         store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(cw->list_view)));
901         GdkPixbuf *pixbuf;
902         
903         if (!group_pixbuf) {
904                 stock_pixbuf_gdk(cw->list_view, STOCK_PIXMAP_ADDR_TWO, &group_pixbuf);
905                 g_object_ref(G_OBJECT(group_pixbuf));
906         }
907         if (!email_pixbuf) {
908                 stock_pixbuf_gdk(cw->list_view, STOCK_PIXMAP_ADDR_ONE, &email_pixbuf);
909                 g_object_ref(G_OBJECT(email_pixbuf));
910         }
911         /* g_print( "\t\tAdding :%s\n", address ); */
912         if (strstr(address, " <!--___group___-->")) {
913                 is_group = TRUE;
914                 if (_groupAddresses_)
915                         grp_emails = g_hash_table_lookup(_groupAddresses_, GINT_TO_POINTER(g_str_hash(address)));
916                 *(strstr(address, " <!--___group___-->")) = '\0';
917                 pixbuf = group_pixbuf;
918         } else if (strchr(address, '@') && strchr(address, '<') &&
919                    strchr(address, '>')) {
920                 pixbuf = email_pixbuf;
921         } else
922                 pixbuf = NULL;
923         
924         if (is_group && !_allowCommas_)
925                 return;
926         gtk_list_store_append(store, &iter);
927         gtk_list_store_set(store, &iter, 
928                                 ADDR_COMPL_ICON, pixbuf,
929                                 ADDR_COMPL_ADDRESS, address, 
930                                 ADDR_COMPL_ISGROUP, is_group, 
931                                 ADDR_COMPL_GROUPLIST, grp_emails,
932                                 -1);
933         cw->listCount++;
934
935         /* Resize window */
936         addrcompl_resize_window( cw );
937         gtk_grab_add( cw->window );
938
939         selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(cw->list_view));
940         gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store), &iter);
941
942         if( cw->listCount == 1 ) {
943                 /* Select first row for now */
944                 gtk_tree_selection_select_iter(selection, &iter);
945         }
946 #ifndef GENERIC_UMPC
947         else if( cw->listCount == 2 ) {
948                 gtk_tree_model_iter_next(GTK_TREE_MODEL(store), &iter);
949                 /* Move off first row */
950                 gtk_tree_selection_select_iter(selection, &iter);
951         }
952 #endif
953 }
954
955 /**
956  * Completion idle function. This function is called by the main (UI) thread
957  * during UI idle time while an address search is in progress. Items from the
958  * display queue are processed and appended to the address list.
959  *
960  * \param data Target completion window to receive email addresses.
961  * \return <i>TRUE</i> to ensure that idle event do not get ignored.
962  */
963 static gboolean addrcompl_idle( gpointer data ) {
964         GList *node;
965         gchar *address;
966
967         /* Process all entries in display queue */
968         pthread_mutex_lock( & _completionMutex_ );
969         if( _displayQueue_ ) {
970                 node = _displayQueue_;
971                 while( node ) {
972                         address = node->data;
973                         /* g_print( "address ::: %s :::\n", address ); */
974                         addrcompl_add_entry( _compWindow_, address );
975                         g_free( address );
976                         node = g_list_next( node );
977                 }
978                 g_list_free( _displayQueue_ );
979                 _displayQueue_ = NULL;
980         }
981         pthread_mutex_unlock( & _completionMutex_ );
982         claws_do_idle();
983
984         return TRUE;
985 }
986
987 /**
988  * Callback entry point. The background thread (if any) appends the address
989  * list to the display queue.
990  * \param sender     Sender of query.
991  * \param queryID    Query ID of search request.
992  * \param listEMail  List of zero of more email objects that met search
993  *                   criteria.
994  * \param data       Query data.
995  */
996 #ifndef USE_NEW_ADDRBOOK
997 static gint addrcompl_callback_entry(
998         gpointer sender, gint queryID, GList *listEMail, gpointer data )
999 {
1000         GList *node;
1001         gchar *address;
1002
1003         /* g_print( "addrcompl_callback_entry::queryID=%d\n", queryID ); */
1004         pthread_mutex_lock( & _completionMutex_ );
1005         if( queryID == _queryID_ ) {
1006                 /* Append contents to end of display queue */
1007                 node = listEMail;
1008                 while( node ) {
1009                         ItemEMail *email = node->data;
1010
1011                         address = addritem_format_email( email );
1012                         /* g_print( "\temail/address ::%s::\n", address ); */
1013                         _displayQueue_ = g_list_append( _displayQueue_, address );
1014                         node = g_list_next( node );
1015                 }
1016         }
1017         g_list_free( listEMail );
1018         pthread_mutex_unlock( & _completionMutex_ );
1019
1020         return 0;
1021 }
1022 #endif
1023
1024 /**
1025  * Clear the display queue.
1026  */
1027 static void addrcompl_clear_queue( void ) {
1028         /* Clear out display queue */
1029         pthread_mutex_lock( & _completionMutex_ );
1030
1031         g_list_free( _displayQueue_ );
1032         _displayQueue_ = NULL;
1033
1034         pthread_mutex_unlock( & _completionMutex_ );
1035 }
1036
1037 /**
1038  * Add a single address entry into the display queue.
1039  * \param address Address to append.
1040  */
1041 static void addrcompl_add_queue( gchar *address ) {
1042         pthread_mutex_lock( & _completionMutex_ );
1043         _displayQueue_ = g_list_append( _displayQueue_, address );
1044         pthread_mutex_unlock( & _completionMutex_ );
1045 }
1046
1047 /**
1048  * Load list with entries from local completion index.
1049  */
1050 static void addrcompl_load_local( void ) {
1051         guint count = 0;
1052
1053         for (count = 0; count < get_completion_count(); count++) {
1054                 gchar *address;
1055
1056                 address = get_complete_address( count );
1057                 /* g_print( "\taddress ::%s::\n", address ); */
1058
1059                 /* Append contents to end of display queue */
1060                 addrcompl_add_queue( address );
1061         }
1062 }
1063
1064 /**
1065  * Start the search.
1066  */
1067 static void addrcompl_start_search( void ) {
1068 #ifndef USE_NEW_ADDRBOOK
1069         gchar *searchTerm;
1070
1071         searchTerm = g_strdup( _compWindow_->searchTerm );
1072
1073         /* Setup the search */
1074         _queryID_ = addrindex_setup_search(
1075                 searchTerm, NULL, addrcompl_callback_entry );
1076         g_free( searchTerm );
1077 #endif
1078         /* g_print( "addrcompl_start_search::queryID=%d\n", _queryID_ ); */
1079
1080         /* Load local stuff */
1081         addrcompl_load_local();
1082
1083         /* Sit back and wait until something happens */
1084         _completionIdleID_ =
1085                 g_idle_add( (GSourceFunc) addrcompl_idle, NULL );
1086         /* g_print( "addrindex_start_search::queryID=%d\n", _queryID_ ); */
1087
1088 #ifndef USE_NEW_ADDRBOOK
1089         addrindex_start_search( _queryID_ );
1090 #else
1091         
1092 #endif
1093 }
1094
1095 /**
1096  * Apply the current selection in the list to the entry field. Focus is also
1097  * moved to the next widget so that Tab key works correctly.
1098  * \param list_view List to process.
1099  * \param entry Address entry field.
1100  * \param move_focus Move focus to the next widget ?
1101  */
1102 static void completion_window_apply_selection(GtkTreeView *list_view,
1103                                                 GtkEntry *entry,
1104                                                 gboolean move_focus)
1105 {
1106         gchar *address = NULL, *text = NULL;
1107         gint   cursor_pos;
1108         GtkWidget *parent;
1109         GtkTreeSelection *selection;
1110         GtkTreeModel *model;
1111         GtkTreeIter iter;
1112         gboolean is_group = FALSE;
1113         cm_return_if_fail(list_view != NULL);
1114         cm_return_if_fail(entry != NULL);
1115         GList *grp_emails = NULL;
1116
1117         selection = gtk_tree_view_get_selection(list_view);
1118         if (! gtk_tree_selection_get_selected(selection, &model, &iter))
1119                 return;
1120
1121         /* First remove the idler */
1122         if( _completionIdleID_ != 0 ) {
1123                 g_source_remove( _completionIdleID_ );
1124                 _completionIdleID_ = 0;
1125         }
1126
1127         /* Process selected item */
1128         gtk_tree_model_get(model, &iter, ADDR_COMPL_ADDRESS, &text, 
1129                                 ADDR_COMPL_ISGROUP, &is_group, 
1130                                 ADDR_COMPL_GROUPLIST, &grp_emails,
1131                                 -1);
1132
1133         address = get_address_from_edit(entry, &cursor_pos);
1134         g_free(address);
1135         replace_address_in_edit(entry, text, cursor_pos, is_group, grp_emails);
1136         g_free(text);
1137
1138         /* Move focus to next widget */
1139         parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1140         if( parent && move_focus) {
1141                 gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1142         }
1143 }
1144
1145 /**
1146  * Start address completion. Should be called when creating the main window
1147  * containing address completion entries.
1148  * \param mainwindow Main window.
1149  */
1150 void address_completion_start(GtkWidget *mainwindow)
1151 {
1152         start_address_completion(NULL);
1153
1154         /* register focus change hook */
1155         g_signal_connect(G_OBJECT(mainwindow), "set_focus",
1156                          G_CALLBACK(address_completion_mainwindow_set_focus),
1157                          mainwindow);
1158 }
1159
1160 /**
1161  * Need unique data to make unregistering signal handler possible for the auto
1162  * completed entry.
1163  */
1164 #define COMPLETION_UNIQUE_DATA (GINT_TO_POINTER(0xfeefaa))
1165
1166 /**
1167  * Register specified entry widget for address completion.
1168  * \param entry Address entry field.
1169  */
1170 void address_completion_register_entry(GtkEntry *entry, gboolean allow_commas)
1171 {
1172         cm_return_if_fail(entry != NULL);
1173         cm_return_if_fail(GTK_IS_ENTRY(entry));
1174
1175         /* add hooked property */
1176         g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, entry);
1177         g_object_set_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS, GINT_TO_POINTER(allow_commas));
1178
1179         /* add keypress event */
1180         g_signal_connect_closure
1181                 (G_OBJECT(entry), "key_press_event",
1182                  g_cclosure_new(G_CALLBACK(address_completion_entry_key_pressed),
1183                                 COMPLETION_UNIQUE_DATA,
1184                                 NULL),
1185                  FALSE); /* magic */
1186 }
1187
1188 /**
1189  * Unregister specified entry widget from address completion operations.
1190  * \param entry Address entry field.
1191  */
1192 void address_completion_unregister_entry(GtkEntry *entry)
1193 {
1194         GObject *entry_obj;
1195
1196         cm_return_if_fail(entry != NULL);
1197         cm_return_if_fail(GTK_IS_ENTRY(entry));
1198
1199         entry_obj = g_object_get_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK);
1200         cm_return_if_fail(entry_obj);
1201         cm_return_if_fail(G_OBJECT(entry_obj) == G_OBJECT(entry));
1202
1203         /* has the hooked property? */
1204         g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, NULL);
1205
1206         /* remove the hook */
1207         g_signal_handlers_disconnect_by_func(G_OBJECT(entry), 
1208                         G_CALLBACK(address_completion_entry_key_pressed),
1209                         COMPLETION_UNIQUE_DATA);
1210 }
1211
1212 /**
1213  * End address completion. Should be called when main window with address
1214  * completion entries terminates. NOTE: this function assumes that it is
1215  * called upon destruction of the window.
1216  * \param mainwindow Main window.
1217  */
1218 void address_completion_end(GtkWidget *mainwindow)
1219 {
1220         /* if address_completion_end() is really called on closing the window,
1221          * we don't need to unregister the set_focus_cb */
1222         end_address_completion();
1223 }
1224
1225 /* if focus changes to another entry, then clear completion cache */
1226 static void address_completion_mainwindow_set_focus(GtkWindow *window,
1227                                                     GtkWidget *widget,
1228                                                     gpointer   data)
1229 {
1230         
1231         if (widget && GTK_IS_ENTRY(widget) &&
1232             g_object_get_data(G_OBJECT(widget), ENTRY_DATA_TAB_HOOK)) {
1233                 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), ENTRY_DATA_ALLOW_COMMAS));
1234                 clear_completion_cache();
1235         }
1236 }
1237
1238 /**
1239  * Listener that watches for tab or other keystroke in address entry field.
1240  * \param entry Address entry field.
1241  * \param ev    Event object.
1242  * \param data  User data.
1243  * \return <i>TRUE</i>.
1244  */
1245 static gboolean address_completion_entry_key_pressed(GtkEntry    *entry,
1246                                                      GdkEventKey *ev,
1247                                                      gpointer     data)
1248 {
1249         if (ev->keyval == GDK_KEY_Tab) {
1250                 addrcompl_clear_queue();
1251                 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS));
1252                 if( address_completion_complete_address_in_entry( entry, TRUE ) ) {
1253                         /* route a void character to the default handler */
1254                         /* this is a dirty hack; we're actually changing a key
1255                          * reported by the system. */
1256                         ev->keyval = GDK_KEY_AudibleBell_Enable;
1257                         ev->state &= ~GDK_SHIFT_MASK;
1258
1259                         /* Create window */                     
1260                         address_completion_create_completion_window(entry);
1261
1262                         /* Start remote queries */
1263                         addrcompl_start_search();
1264
1265                         return TRUE;
1266                 }
1267                 else {
1268                         /* old behaviour */
1269                 }
1270         } else if (ev->keyval == GDK_KEY_Shift_L
1271                 || ev->keyval == GDK_KEY_Shift_R
1272                 || ev->keyval == GDK_KEY_Control_L
1273                 || ev->keyval == GDK_KEY_Control_R
1274                 || ev->keyval == GDK_KEY_Caps_Lock
1275                 || ev->keyval == GDK_KEY_Shift_Lock
1276                 || ev->keyval == GDK_KEY_Meta_L
1277                 || ev->keyval == GDK_KEY_Meta_R
1278                 || ev->keyval == GDK_KEY_Alt_L
1279                 || ev->keyval == GDK_KEY_Alt_R) {
1280                 /* these buttons should not clear the cache... */
1281         } else
1282                 clear_completion_cache();
1283
1284         return FALSE;
1285 }
1286 /**
1287  * Initialize search term for address completion.
1288  * \param entry Address entry field.
1289  */
1290 static gboolean address_completion_complete_address_in_entry(GtkEntry *entry,
1291                                                              gboolean  next)
1292 {
1293         gint ncount, cursor_pos;
1294         gchar *searchTerm, *new = NULL;
1295
1296         cm_return_val_if_fail(entry != NULL, FALSE);
1297
1298         if (!gtk_widget_has_focus(GTK_WIDGET(entry))) return FALSE;
1299
1300         /* get an address component from the cursor */
1301         searchTerm = get_address_from_edit( entry, &cursor_pos );
1302         if( ! searchTerm ) return FALSE;
1303         /* g_print( "search for :::%s:::\n", searchTerm ); */
1304
1305         /* Clear any existing search */
1306         g_free( _compWindow_->searchTerm );
1307         _compWindow_->searchTerm = g_strdup( searchTerm );
1308
1309         /* Perform search on local completion index */
1310         ncount = complete_address( searchTerm );
1311         if( 0 < ncount ) {
1312                 new = get_next_complete_address();
1313                 g_free( new );
1314         }
1315 #if (!defined(USE_LDAP) && !defined(GENERIC_UMPC))
1316         /* Select the address if there is only one match */
1317         if (ncount == 2) {
1318                 /* Display selected address in entry field */           
1319                 gchar *addr = get_complete_address(1);
1320                 if (addr && !strstr(addr, " <!--___group___-->")) {
1321                         replace_address_in_edit(entry, addr, cursor_pos, FALSE, NULL);
1322                         /* Discard the window */
1323                         clear_completion_cache();
1324                 } 
1325                 g_free(addr);
1326         }
1327         /* Make sure that drop-down appears uniform! */
1328         else 
1329 #endif
1330         if( ncount == 0 ) {
1331                 addrcompl_add_queue( g_strdup( searchTerm ) );
1332         }
1333         g_free( searchTerm );
1334
1335         return TRUE;
1336 }
1337
1338 /**
1339  * Create new address completion window for specified entry.
1340  * \param entry_ Entry widget to associate with window.
1341  */
1342 static void address_completion_create_completion_window( GtkEntry *entry_ )
1343 {
1344         gint x, y, height, width, depth;
1345         GtkWidget *scroll, *list_view;
1346         GtkRequisition r;
1347         GtkWidget *window;
1348         GtkWidget *entry = GTK_WIDGET(entry_);
1349         GdkWindow *gdkwin;
1350
1351         /* Create new window and list */
1352         window = gtk_window_new(GTK_WINDOW_POPUP);
1353         list_view  = addr_compl_list_view_create(_compWindow_);
1354
1355         /* Destroy any existing window */
1356         addrcompl_destroy_window( _compWindow_ );
1357
1358         /* Create new object */
1359         _compWindow_->window    = window;
1360         _compWindow_->entry     = entry;
1361         _compWindow_->list_view = list_view;
1362         _compWindow_->listCount = 0;
1363         _compWindow_->in_mouse  = FALSE;
1364
1365         scroll = gtk_scrolled_window_new(NULL, NULL);
1366         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
1367                                        GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
1368         gtk_container_add(GTK_CONTAINER(window), scroll);
1369         gtk_container_add(GTK_CONTAINER(scroll), list_view);
1370         gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll),
1371                 GTK_SHADOW_OUT);
1372         /* Use entry widget to create initial window */
1373         gdkwin = gtk_widget_get_window(entry),
1374         gdk_window_get_geometry(gdkwin, &x, &y, &width, &height, &depth);
1375         gdk_window_get_origin (gdkwin, &x, &y);
1376         y += height;
1377         gtk_window_move(GTK_WINDOW(window), x, y);
1378
1379         /* Resize window to fit initial (empty) address list */
1380         gtk_widget_size_request( list_view, &r );
1381         gtk_widget_set_size_request( window, width, r.height );
1382         gtk_widget_show_all( window );
1383         gtk_widget_size_request( list_view, &r );
1384
1385         /* Setup handlers */
1386         g_signal_connect(G_OBJECT(list_view), "button_press_event",
1387                          G_CALLBACK(list_view_button_press),
1388                          _compWindow_);
1389                          
1390         g_signal_connect(G_OBJECT(list_view), "button_release_event",
1391                          G_CALLBACK(list_view_button_release),
1392                          _compWindow_);
1393         
1394         g_signal_connect(G_OBJECT(window),
1395                          "button-press-event",
1396                          G_CALLBACK(completion_window_button_press),
1397                          _compWindow_ );
1398         g_signal_connect(G_OBJECT(window),
1399                          "key-press-event",
1400                          G_CALLBACK(completion_window_key_press),
1401                          _compWindow_ );
1402         gdk_pointer_grab(gtk_widget_get_window(window), TRUE,
1403                          GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK |
1404                          GDK_BUTTON_RELEASE_MASK,
1405                          NULL, NULL, GDK_CURRENT_TIME);
1406         gdk_keyboard_grab(gtk_widget_get_window(window), FALSE, GDK_CURRENT_TIME);
1407         gtk_grab_add( window );
1408 }
1409
1410 /**
1411  * Respond to button press in completion window. Check if mouse click is
1412  * anywhere outside the completion window. In that case the completion
1413  * window is destroyed, and the original searchTerm is restored.
1414  *
1415  * \param widget   Window object.
1416  * \param event    Event.
1417  * \param compWin  Reference to completion window.
1418  */
1419 static gboolean completion_window_button_press(GtkWidget *widget,
1420                                                GdkEventButton *event,
1421                                                CompletionWindow *compWin )
1422 {
1423         GtkWidget *event_widget, *entry;
1424         gchar *searchTerm;
1425         gint cursor_pos;
1426         gboolean restore = TRUE;
1427
1428         cm_return_val_if_fail(compWin != NULL, FALSE);
1429
1430         entry = compWin->entry;
1431         cm_return_val_if_fail(entry != NULL, FALSE);
1432
1433         /* Test where mouse was clicked */
1434         event_widget = gtk_get_event_widget((GdkEvent *)event);
1435         if (event_widget != widget) {
1436                 while (event_widget) {
1437                         if (event_widget == widget)
1438                                 return FALSE;
1439                         else if (event_widget == entry) {
1440                                 restore = FALSE;
1441                                 break;
1442                         }
1443                         event_widget = gtk_widget_get_parent(event_widget);
1444                 }
1445         }
1446
1447         if (restore) {
1448                 /* Clicked outside of completion window - restore */
1449                 searchTerm = _compWindow_->searchTerm;
1450                 g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1451                 replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos, FALSE, NULL);
1452         }
1453
1454         clear_completion_cache();
1455         addrcompl_destroy_window( _compWindow_ );
1456
1457         return TRUE;
1458 }
1459
1460 /**
1461  * Respond to key press in completion window.
1462  * \param widget   Window object.
1463  * \param event    Event.
1464  * \param compWind Reference to completion window.
1465  */
1466 static gboolean completion_window_key_press(GtkWidget *widget,
1467                                             GdkEventKey *event,
1468                                             CompletionWindow *compWin )
1469 {
1470         GdkEventKey tmp_event;
1471         GtkWidget *entry;
1472         gchar *searchTerm;
1473         gint cursor_pos;
1474         GtkWidget *list_view;
1475         GtkWidget *parent;
1476         cm_return_val_if_fail(compWin != NULL, FALSE);
1477
1478         entry = compWin->entry;
1479         list_view = compWin->list_view;
1480         cm_return_val_if_fail(entry != NULL, FALSE);
1481
1482         /* allow keyboard navigation in the alternatives tree view */
1483         if (event->keyval == GDK_KEY_Up || event->keyval == GDK_KEY_Down ||
1484             event->keyval == GDK_KEY_Page_Up || event->keyval == GDK_KEY_Page_Down) {
1485                 completion_window_advance_selection
1486                         (GTK_TREE_VIEW(list_view),
1487                          event->keyval == GDK_KEY_Down ||
1488                          event->keyval == GDK_KEY_Page_Down ? TRUE : FALSE);
1489                 return FALSE;
1490         }               
1491
1492         /* make tab move to next field */
1493         if( event->keyval == GDK_KEY_Tab ) {
1494                 /* Reference to parent */
1495                 parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1496
1497                 /* Discard the window */
1498                 clear_completion_cache();
1499                 addrcompl_destroy_window( _compWindow_ );
1500
1501                 /* Move focus to next widget */
1502                 if( parent ) {
1503                         gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1504                 }
1505                 return FALSE;
1506         }
1507
1508         /* make backtab move to previous field */
1509         if( event->keyval == GDK_KEY_ISO_Left_Tab ) {
1510                 /* Reference to parent */
1511                 parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1512
1513                 /* Discard the window */
1514                 clear_completion_cache();
1515                 addrcompl_destroy_window( _compWindow_ );
1516
1517                 /* Move focus to previous widget */
1518                 if( parent ) {
1519                         gtk_widget_child_focus( parent, GTK_DIR_TAB_BACKWARD );
1520                 }
1521                 return FALSE;
1522         }
1523         _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS));
1524
1525         /* look for presses that accept the selection */
1526         if (event->keyval == GDK_KEY_Return || event->keyval == GDK_KEY_space ||
1527                         event->keyval == GDK_KEY_KP_Enter ||
1528                         (_allowCommas_ && event->keyval == GDK_KEY_comma)) {
1529                 /* User selected address with a key press */
1530
1531                 /* Display selected address in entry field */           
1532                 completion_window_apply_selection(
1533                         GTK_TREE_VIEW(list_view), GTK_ENTRY(entry),
1534                         event->keyval != GDK_KEY_comma);
1535
1536                 if (event->keyval == GDK_KEY_comma) {
1537                         gint pos = gtk_editable_get_position(GTK_EDITABLE(entry));
1538                         gtk_editable_insert_text(GTK_EDITABLE(entry), ", ", 2, &pos);
1539                         gtk_editable_set_position(GTK_EDITABLE(entry), pos + 1);
1540                 }
1541
1542                 /* Discard the window */
1543                 clear_completion_cache();
1544                 addrcompl_destroy_window( _compWindow_ );
1545                 return FALSE;
1546         }
1547
1548         /* key state keys should never be handled */
1549         if (event->keyval == GDK_KEY_Shift_L
1550                  || event->keyval == GDK_KEY_Shift_R
1551                  || event->keyval == GDK_KEY_Control_L
1552                  || event->keyval == GDK_KEY_Control_R
1553                  || event->keyval == GDK_KEY_Caps_Lock
1554                  || event->keyval == GDK_KEY_Shift_Lock
1555                  || event->keyval == GDK_KEY_Meta_L
1556                  || event->keyval == GDK_KEY_Meta_R
1557                  || event->keyval == GDK_KEY_Alt_L
1558                  || event->keyval == GDK_KEY_Alt_R) {
1559                 return FALSE;
1560         }
1561
1562         /* some other key, let's restore the searchTerm (orignal text) */
1563         searchTerm = _compWindow_->searchTerm;
1564         g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1565         replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos, FALSE, NULL);
1566
1567         /* make sure anything we typed comes in the edit box */
1568         tmp_event.type       = event->type;
1569         tmp_event.window     = gtk_widget_get_window(GTK_WIDGET(entry));
1570         tmp_event.send_event = TRUE;
1571         tmp_event.time       = event->time;
1572         tmp_event.state      = event->state;
1573         tmp_event.keyval     = event->keyval;
1574         tmp_event.length     = event->length;
1575         tmp_event.string     = event->string;
1576         gtk_widget_event(entry, (GdkEvent *)&tmp_event);
1577
1578         /* and close the completion window */
1579         clear_completion_cache();
1580         addrcompl_destroy_window( _compWindow_ );
1581
1582         return TRUE;
1583 }
1584
1585 /*
1586  * ============================================================================
1587  * Publically accessible functions.
1588  * ============================================================================
1589  */
1590
1591 /**
1592  * Setup completion object.
1593  */
1594 void addrcompl_initialize( void ) {
1595         /* g_print( "addrcompl_initialize...\n" ); */
1596         if( ! _compWindow_ ) {
1597                 _compWindow_ = addrcompl_create_window();
1598         }
1599         _queryID_ = 0;
1600         _completionIdleID_ = 0;
1601         /* g_print( "addrcompl_initialize...done\n" ); */
1602 }
1603
1604 /**
1605  * Teardown completion object.
1606  */
1607 void addrcompl_teardown( void ) {
1608         /* g_print( "addrcompl_teardown...\n" ); */
1609         addrcompl_free_window( _compWindow_ );
1610         _compWindow_ = NULL;
1611         if( _displayQueue_ ) {
1612                 g_list_free( _displayQueue_ );
1613         }
1614         _displayQueue_ = NULL;
1615         _completionIdleID_ = 0;
1616         /* g_print( "addrcompl_teardown...done\n" ); */
1617 }
1618
1619 /*
1620  * tree view functions
1621  */
1622
1623 static GtkListStore *addr_compl_create_store(void)
1624 {
1625         return gtk_list_store_new(N_ADDR_COMPL_COLUMNS,
1626                                   GDK_TYPE_PIXBUF,
1627                                   G_TYPE_STRING,
1628                                   G_TYPE_BOOLEAN,
1629                                   G_TYPE_POINTER,
1630                                   -1);
1631 }
1632                                              
1633 static GtkWidget *addr_compl_list_view_create(CompletionWindow *window)
1634 {
1635         GtkTreeView *list_view;
1636         GtkTreeSelection *selector;
1637         GtkTreeModel *model;
1638
1639         model = GTK_TREE_MODEL(addr_compl_create_store());
1640         list_view = GTK_TREE_VIEW(gtk_tree_view_new_with_model(model));
1641         g_object_unref(model);  
1642         
1643         gtk_tree_view_set_rules_hint(list_view, prefs_common.use_stripes_everywhere);
1644         gtk_tree_view_set_headers_visible(list_view, FALSE);
1645         
1646         selector = gtk_tree_view_get_selection(list_view);
1647         gtk_tree_selection_set_mode(selector, GTK_SELECTION_BROWSE);
1648         gtk_tree_selection_set_select_function(selector, addr_compl_selected,
1649                                                window, NULL);
1650
1651         /* create the columns */
1652         addr_compl_create_list_view_columns(GTK_WIDGET(list_view));
1653
1654         return GTK_WIDGET(list_view);
1655 }
1656
1657 static void addr_compl_create_list_view_columns(GtkWidget *list_view)
1658 {
1659         GtkTreeViewColumn *column;
1660         GtkCellRenderer *renderer;
1661
1662         renderer = gtk_cell_renderer_pixbuf_new();
1663         column = gtk_tree_view_column_new_with_attributes
1664                 ("", renderer,
1665                  "pixbuf", ADDR_COMPL_ICON, NULL);
1666         gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);          
1667         renderer = gtk_cell_renderer_text_new();
1668         column = gtk_tree_view_column_new_with_attributes
1669                 ("", renderer, "text", ADDR_COMPL_ADDRESS, NULL);
1670         gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);          
1671 }
1672
1673 static gboolean list_view_button_press(GtkWidget *widget, GdkEventButton *event,
1674                                        CompletionWindow *window)
1675 {
1676         if (window && event && event->type == GDK_BUTTON_PRESS) {
1677                 window->in_mouse = TRUE;
1678         }
1679         return FALSE;
1680 }
1681
1682 static gboolean list_view_button_release(GtkWidget *widget, GdkEventButton *event,
1683                                          CompletionWindow *window)
1684 {
1685         if (window && event && event->type == GDK_BUTTON_RELEASE) {
1686                 window->in_mouse = FALSE;
1687         }
1688         return FALSE;
1689 }
1690
1691 static gboolean addr_compl_selected(GtkTreeSelection *selector,
1692                                     GtkTreeModel *model, 
1693                                     GtkTreePath *path,
1694                                     gboolean currently_selected,
1695                                     gpointer data)
1696 {
1697         CompletionWindow *window = data;
1698
1699         if (currently_selected)
1700                 return TRUE;
1701         
1702         if (!window->in_mouse)
1703                 return TRUE;
1704
1705         /* XXX: select the entry and kill window later... select is called before
1706          * any other mouse events handlers including the tree view internal one;
1707          * not using a time out would result in a crash. if this doesn't work
1708          * safely, maybe we should set variables when receiving button presses
1709          * in the tree view. */
1710         if (!window->destroying) {
1711                 window->destroying = TRUE;
1712                 g_idle_add((GSourceFunc) addr_compl_defer_select_destruct, data);
1713         }
1714
1715         return TRUE;
1716 }
1717
1718 static gboolean addr_compl_defer_select_destruct(CompletionWindow *window)
1719 {
1720         GtkEntry *entry = GTK_ENTRY(window->entry);
1721
1722         completion_window_apply_selection(GTK_TREE_VIEW(window->list_view), 
1723                                           entry, TRUE);
1724
1725         clear_completion_cache();
1726
1727         addrcompl_destroy_window(window);
1728         return FALSE;
1729 }
1730
1731
1732 /*
1733  * End of Source.
1734  */
1735