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