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