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