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