2005-09-10 [colin] 1.9.14cvs14
[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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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 <pthread.h>
50
51 /*!
52  *\brief        For the GtkListStore
53  */
54 enum {
55         ADDR_COMPL_ADDRESS,
56         N_ADDR_COMPL_COLUMNS
57 };
58
59 /*
60  * How it works:
61  *
62  * The address book is read into memory. We set up an address list
63  * containing all address book entries. Next we make the completion
64  * list, which contains all the completable strings, and store a
65  * reference to the address entry it belongs to.
66  * After calling the g_completion_complete(), we get a reference
67  * to a valid email address.  
68  *
69  * Completion is very simplified. We never complete on another prefix,
70  * i.e. we neglect the next smallest possible prefix for the current
71  * completion cache. This is simply done so we might break up the
72  * addresses a little more (e.g. break up alfons@proteus.demon.nl into
73  * something like alfons, proteus, demon, nl; and then completing on
74  * any of those words).
75  */ 
76         
77 /**
78  * address_entry - structure which refers to the original address entry in the
79  * address book .
80  */
81 typedef struct
82 {
83         gchar *name;
84         gchar *address;
85 } address_entry;
86
87 /**
88  * completion_entry - structure used to complete addresses, with a reference
89  * the the real address information.
90  */
91 typedef struct
92 {
93         gchar           *string; /* string to complete */
94         address_entry   *ref;    /* address the string belongs to  */
95 } completion_entry;
96
97 /*******************************************************************************/
98
99 static gint         g_ref_count;        /* list ref count */
100 static GList       *g_completion_list;  /* list of strings to be checked */
101 static GList       *g_address_list;     /* address storage */
102 static GCompletion *g_completion;       /* completion object */
103
104 /* To allow for continuing completion we have to keep track of the state
105  * using the following variables. No need to create a context object. */
106
107 static gint         g_completion_count;         /* nr of addresses incl. the prefix */
108 static gint         g_completion_next;          /* next prev address */
109 static GSList      *g_completion_addresses;     /* unique addresses found in the
110                                                    completion cache. */
111 static gchar       *g_completion_prefix;        /* last prefix. (this is cached here
112                                                  * because the prefix passed to g_completion
113                                                  * is g_strdown()'ed */
114
115 /*******************************************************************************/
116
117 /*
118  * Define the structure of the completion window.
119  */
120 typedef struct _CompletionWindow CompletionWindow;
121 struct _CompletionWindow {
122         gint      listCount;
123         gchar     *searchTerm;
124         GtkWidget *window;
125         GtkWidget *entry;
126         GtkWidget *list_view;
127
128         gboolean   in_mouse;    /*!< mouse press pending... */
129         gboolean   destroying;  /*!< destruction in progress */
130 };
131
132 static GtkListStore *addr_compl_create_store    (void);
133
134 static GtkWidget *addr_compl_list_view_create   (CompletionWindow *window);
135
136 static void addr_compl_create_list_view_columns (GtkWidget *list_view);
137
138 static gboolean list_view_button_press          (GtkWidget *widget, 
139                                                  GdkEventButton *event,
140                                                  CompletionWindow *window);
141
142 static gboolean list_view_button_release        (GtkWidget *widget, 
143                                                  GdkEventButton *event,
144                                                  CompletionWindow *window);
145
146 static gboolean addr_compl_selected             (GtkTreeSelection *selector,
147                                                  GtkTreeModel *model, 
148                                                  GtkTreePath *path,
149                                                  gboolean currently_selected,
150                                                  gpointer data);
151                                                  
152 static gboolean addr_compl_defer_select_destruct(CompletionWindow *window);
153
154 /**
155  * Function used by GTK to find the string data to be used for completion.
156  * \param data Pointer to data being processed.
157  */
158 static gchar *completion_func(gpointer data)
159 {
160         g_return_val_if_fail(data != NULL, NULL);
161
162         return ((completion_entry *)data)->string;
163
164
165 /**
166  * Initialize all completion index data.
167  */
168 static void init_all(void)
169 {
170         g_completion = g_completion_new(completion_func);
171         g_return_if_fail(g_completion != NULL);
172 }
173
174 /**
175  * Free up all completion index data.
176  */
177 static void free_all(void)
178 {
179         GList *walk;
180         
181         walk = g_list_first(g_completion_list);
182         for (; walk != NULL; walk = g_list_next(walk)) {
183                 completion_entry *ce = (completion_entry *) walk->data;
184                 g_free(ce->string);
185                 g_free(walk->data);
186         }
187         g_list_free(g_completion_list);
188         g_completion_list = NULL;
189         
190         walk = g_address_list;
191         for (; walk != NULL; walk = g_list_next(walk)) {
192                 address_entry *ae = (address_entry *) walk->data;
193                 g_free(ae->name);
194                 g_free(ae->address);
195                 g_free(walk->data);
196         }
197         g_list_free(g_address_list);
198         g_address_list = NULL;
199         
200         g_completion_free(g_completion);
201         g_completion = NULL;
202 }
203
204 /**
205  * Append specified address entry to the index.
206  * \param str Index string value.
207  * \param ae  Entry containing address data.
208  */
209 static void add_address1(const char *str, address_entry *ae)
210 {
211         completion_entry *ce1;
212         ce1 = g_new0(completion_entry, 1),
213         ce1->string = g_utf8_strdown(str, -1);
214         /* GCompletion list is case sensitive */
215         g_strdown(ce1->string);
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 #if 0
714 /* completion_window_accept_selection() - accepts the current selection in the
715  * clist, and destroys the window */
716 static void completion_window_accept_selection(GtkWidget **window,
717                                                GtkCList *clist,
718                                                GtkEntry *entry)
719 {
720         gchar *address = NULL, *text = NULL;
721         gint   cursor_pos, row;
722
723         g_return_if_fail(window != NULL);
724         g_return_if_fail(*window != NULL);
725         g_return_if_fail(clist != NULL);
726         g_return_if_fail(entry != NULL);
727         g_return_if_fail(clist->selection != NULL);
728
729         /* FIXME: I believe it's acceptable to access the selection member directly  */
730         row = GPOINTER_TO_INT(clist->selection->data);
731
732         /* we just need the cursor position */
733         address = get_address_from_edit(entry, &cursor_pos);
734         g_free(address);
735         gtk_clist_get_text(clist, row, 0, &text);
736         replace_address_in_edit(entry, text, cursor_pos);
737
738         clear_completion_cache();
739         gtk_widget_destroy(*window);
740         *window = NULL;
741 }
742 #endif
743
744 /**
745  * Resize window to accommodate maximum number of address entries.
746  * \param cw Completion window.
747  */
748 static void addrcompl_resize_window( CompletionWindow *cw ) {
749         GtkRequisition r;
750         gint x, y, width, height, depth;
751
752         /* Get current geometry of window */
753         gdk_window_get_geometry( cw->window->window, &x, &y, &width, &height, &depth );
754
755         gtk_widget_hide_all( cw->window );
756         gtk_widget_show_all( cw->window );
757         gtk_widget_size_request( cw->list_view, &r );
758
759         /* Adjust window height to available screen space */
760         if( ( y + r.height ) > gdk_screen_height() ) {
761                 gtk_window_set_resizable(GTK_WINDOW(cw->window), FALSE);
762                 gtk_widget_set_size_request( cw->window, width, gdk_screen_height() - y );
763         } else
764                 gtk_widget_set_size_request(cw->window, width, r.height);
765 }
766
767 /**
768  * Add an address the completion window address list.
769  * \param cw      Completion window.
770  * \param address Address to add.
771  */
772 static void addrcompl_add_entry( CompletionWindow *cw, gchar *address ) {
773         GtkListStore *store;
774         GtkTreeIter iter;
775         GtkTreeSelection *selection;
776
777         store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(cw->list_view)));
778         gtk_list_store_append(store, &iter);
779
780         /* printf( "\t\tAdding :%s\n", address ); */
781         gtk_list_store_set(store, &iter, ADDR_COMPL_ADDRESS, address, -1);
782         cw->listCount++;
783
784         /* Resize window */
785         addrcompl_resize_window( cw );
786         gtk_grab_add( cw->window );
787
788         selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(cw->list_view));
789         gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store), &iter);
790
791         if( cw->listCount == 1 ) {
792                 /* Select first row for now */
793                 gtk_tree_selection_select_iter(selection, &iter);
794         }
795         else if( cw->listCount == 2 ) {
796                 gtk_tree_model_iter_next(GTK_TREE_MODEL(store), &iter);
797                 /* Move off first row */
798                 gtk_tree_selection_select_iter(selection, &iter);
799         }
800 }
801
802 /**
803  * Completion idle function. This function is called by the main (UI) thread
804  * during UI idle time while an address search is in progress. Items from the
805  * display queue are processed and appended to the address list.
806  *
807  * \param data Target completion window to receive email addresses.
808  * \return <i>TRUE</i> to ensure that idle event do not get ignored.
809  */
810 static gboolean addrcompl_idle( gpointer data ) {
811         GList *node;
812         gchar *address;
813
814         /* Process all entries in display queue */
815         pthread_mutex_lock( & _completionMutex_ );
816         if( _displayQueue_ ) {
817                 node = _displayQueue_;
818                 while( node ) {
819                         address = node->data;
820                         /* printf( "address ::: %s :::\n", address ); */
821                         addrcompl_add_entry( _compWindow_, address );
822                         g_free( address );
823                         node = g_list_next( node );
824                 }
825                 g_list_free( _displayQueue_ );
826                 _displayQueue_ = NULL;
827         }
828         pthread_mutex_unlock( & _completionMutex_ );
829
830         return TRUE;
831 }
832
833 /**
834  * Callback entry point. The background thread (if any) appends the address
835  * list to the display queue.
836  * \param sender     Sender of query.
837  * \param queryID    Query ID of search request.
838  * \param listEMail  List of zero of more email objects that met search
839  *                   criteria.
840  * \param data       Query data.
841  */
842 static gint addrcompl_callback_entry(
843         gpointer sender, gint queryID, GList *listEMail, gpointer data )
844 {
845         GList *node;
846         gchar *address;
847
848         /* printf( "addrcompl_callback_entry::queryID=%d\n", queryID ); */
849         pthread_mutex_lock( & _completionMutex_ );
850         if( queryID == _queryID_ ) {
851                 /* Append contents to end of display queue */
852                 node = listEMail;
853                 while( node ) {
854                         ItemEMail *email = node->data;
855
856                         address = addritem_format_email( email );
857                         /* printf( "\temail/address ::%s::\n", address ); */
858                         _displayQueue_ = g_list_append( _displayQueue_, address );
859                         node = g_list_next( node );
860                 }
861         }
862         g_list_free( listEMail );
863         pthread_mutex_unlock( & _completionMutex_ );
864
865         return 0;
866 }
867
868 /**
869  * Clear the display queue.
870  */
871 static void addrcompl_clear_queue( void ) {
872         /* Clear out display queue */
873         pthread_mutex_lock( & _completionMutex_ );
874
875         g_list_free( _displayQueue_ );
876         _displayQueue_ = NULL;
877
878         pthread_mutex_unlock( & _completionMutex_ );
879 }
880
881 /**
882  * Add a single address entry into the display queue.
883  * \param address Address to append.
884  */
885 static void addrcompl_add_queue( gchar *address ) {
886         pthread_mutex_lock( & _completionMutex_ );
887         _displayQueue_ = g_list_append( _displayQueue_, address );
888         pthread_mutex_unlock( & _completionMutex_ );
889 }
890
891 /**
892  * Load list with entries from local completion index.
893  */
894 static void addrcompl_load_local( void ) {
895         guint count = 0;
896
897         for (count = 0; count < get_completion_count(); count++) {
898                 gchar *address;
899
900                 address = get_complete_address( count );
901                 /* printf( "\taddress ::%s::\n", address ); */
902
903                 /* Append contents to end of display queue */
904                 addrcompl_add_queue( address );
905         }
906 }
907
908 /**
909  * Start the search.
910  */
911 static void addrcompl_start_search( void ) {
912         gchar *searchTerm;
913
914         searchTerm = g_strdup( _compWindow_->searchTerm );
915
916         /* Setup the search */
917         _queryID_ = addrindex_setup_search(
918                 searchTerm, NULL, addrcompl_callback_entry );
919         g_free( searchTerm );
920         /* printf( "addrcompl_start_search::queryID=%d\n", _queryID_ ); */
921
922         /* Load local stuff */
923         addrcompl_load_local();
924
925         /* Sit back and wait until something happens */
926         _completionIdleID_ =
927                 gtk_idle_add( ( GtkFunction ) addrcompl_idle, NULL );
928         /* printf( "addrindex_start_search::queryID=%d\n", _queryID_ ); */
929
930         addrindex_start_search( _queryID_ );
931 }
932
933 /**
934  * Apply the current selection in the list to the entry field. Focus is also
935  * moved to the next widget so that Tab key works correctly.
936  * \param list_view List to process.
937  * \param entry Address entry field.
938  */
939 static void completion_window_apply_selection(GtkTreeView *list_view, GtkEntry *entry)
940 {
941         gchar *address = NULL, *text = NULL;
942         gint   cursor_pos;
943         GtkWidget *parent;
944         GtkTreeSelection *selection;
945         GtkTreeModel *model;
946         GtkTreeIter iter;
947
948         g_return_if_fail(list_view != NULL);
949         g_return_if_fail(entry != NULL);
950
951         selection = gtk_tree_view_get_selection(list_view);
952         if (! gtk_tree_selection_get_selected(selection, &model, &iter))
953                 return;
954
955         /* First remove the idler */
956         if( _completionIdleID_ != 0 ) {
957                 gtk_idle_remove( _completionIdleID_ );
958                 _completionIdleID_ = 0;
959         }
960
961         /* Process selected item */
962         gtk_tree_model_get(model, &iter, ADDR_COMPL_ADDRESS, &text, -1);
963
964         address = get_address_from_edit(entry, &cursor_pos);
965         g_free(address);
966         replace_address_in_edit(entry, text, cursor_pos);
967         g_free(text);
968
969         /* Move focus to next widget */
970         parent = GTK_WIDGET(entry)->parent;
971         if( parent ) {
972                 gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
973         }
974 }
975
976 /**
977  * Start address completion. Should be called when creating the main window
978  * containing address completion entries.
979  * \param mainwindow Main window.
980  */
981 void address_completion_start(GtkWidget *mainwindow)
982 {
983         start_address_completion();
984
985         /* register focus change hook */
986         g_signal_connect(G_OBJECT(mainwindow), "set_focus",
987                          G_CALLBACK(address_completion_mainwindow_set_focus),
988                          mainwindow);
989 }
990
991 /**
992  * Need unique data to make unregistering signal handler possible for the auto
993  * completed entry.
994  */
995 #define COMPLETION_UNIQUE_DATA (GINT_TO_POINTER(0xfeefaa))
996
997 /**
998  * Register specified entry widget for address completion.
999  * \param entry Address entry field.
1000  */
1001 void address_completion_register_entry(GtkEntry *entry)
1002 {
1003         g_return_if_fail(entry != NULL);
1004         g_return_if_fail(GTK_IS_ENTRY(entry));
1005
1006         /* add hooked property */
1007         g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, entry);
1008
1009         /* add keypress event */
1010         g_signal_connect_closure
1011                 (G_OBJECT(entry), "key_press_event",
1012                  g_cclosure_new(G_CALLBACK(address_completion_entry_key_pressed),
1013                                 COMPLETION_UNIQUE_DATA,
1014                                 NULL),
1015                  FALSE); /* magic */
1016 }
1017
1018 /**
1019  * Unregister specified entry widget from address completion operations.
1020  * \param entry Address entry field.
1021  */
1022 void address_completion_unregister_entry(GtkEntry *entry)
1023 {
1024         GtkObject *entry_obj;
1025
1026         g_return_if_fail(entry != NULL);
1027         g_return_if_fail(GTK_IS_ENTRY(entry));
1028
1029         entry_obj = g_object_get_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK);
1030         g_return_if_fail(entry_obj);
1031         g_return_if_fail(G_OBJECT(entry_obj) == G_OBJECT(entry));
1032
1033         /* has the hooked property? */
1034         g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, NULL);
1035
1036         /* remove the hook */
1037         g_signal_handlers_disconnect_by_func(G_OBJECT(entry), 
1038                         G_CALLBACK(address_completion_entry_key_pressed),
1039                         COMPLETION_UNIQUE_DATA);
1040 }
1041
1042 /**
1043  * End address completion. Should be called when main window with address
1044  * completion entries terminates. NOTE: this function assumes that it is
1045  * called upon destruction of the window.
1046  * \param mainwindow Main window.
1047  */
1048 void address_completion_end(GtkWidget *mainwindow)
1049 {
1050         /* if address_completion_end() is really called on closing the window,
1051          * we don't need to unregister the set_focus_cb */
1052         end_address_completion();
1053 }
1054
1055 /* if focus changes to another entry, then clear completion cache */
1056 static void address_completion_mainwindow_set_focus(GtkWindow *window,
1057                                                     GtkWidget *widget,
1058                                                     gpointer   data)
1059 {
1060         
1061         if (widget && GTK_IS_ENTRY(widget) &&
1062             g_object_get_data(G_OBJECT(widget), ENTRY_DATA_TAB_HOOK)) {
1063                 clear_completion_cache();
1064         }
1065 }
1066
1067 /**
1068  * Listener that watches for tab or other keystroke in address entry field.
1069  * \param entry Address entry field.
1070  * \param ev    Event object.
1071  * \param data  User data.
1072  * \return <i>TRUE</i>.
1073  */
1074 static gboolean address_completion_entry_key_pressed(GtkEntry    *entry,
1075                                                      GdkEventKey *ev,
1076                                                      gpointer     data)
1077 {
1078         if (ev->keyval == GDK_Tab) {
1079                 addrcompl_clear_queue();
1080
1081                 if( address_completion_complete_address_in_entry( entry, TRUE ) ) {
1082                         /* route a void character to the default handler */
1083                         /* this is a dirty hack; we're actually changing a key
1084                          * reported by the system. */
1085                         ev->keyval = GDK_AudibleBell_Enable;
1086                         ev->state &= ~GDK_SHIFT_MASK;
1087
1088                         /* Create window */                     
1089                         address_completion_create_completion_window(entry);
1090
1091                         /* Start remote queries */
1092                         addrcompl_start_search();
1093
1094                         return TRUE;
1095                 }
1096                 else {
1097                         /* old behaviour */
1098                 }
1099         } else if (ev->keyval == GDK_Shift_L
1100                 || ev->keyval == GDK_Shift_R
1101                 || ev->keyval == GDK_Control_L
1102                 || ev->keyval == GDK_Control_R
1103                 || ev->keyval == GDK_Caps_Lock
1104                 || ev->keyval == GDK_Shift_Lock
1105                 || ev->keyval == GDK_Meta_L
1106                 || ev->keyval == GDK_Meta_R
1107                 || ev->keyval == GDK_Alt_L
1108                 || ev->keyval == GDK_Alt_R) {
1109                 /* these buttons should not clear the cache... */
1110         } else
1111                 clear_completion_cache();
1112
1113         return FALSE;
1114 }
1115 /**
1116  * Initialize search term for address completion.
1117  * \param entry Address entry field.
1118  */
1119 static gboolean address_completion_complete_address_in_entry(GtkEntry *entry,
1120                                                              gboolean  next)
1121 {
1122         gint ncount, cursor_pos;
1123         gchar *searchTerm, *new = NULL;
1124
1125         g_return_val_if_fail(entry != NULL, FALSE);
1126
1127         if (!GTK_WIDGET_HAS_FOCUS(entry)) return FALSE;
1128
1129         /* get an address component from the cursor */
1130         searchTerm = get_address_from_edit( entry, &cursor_pos );
1131         if( ! searchTerm ) return FALSE;
1132         /* printf( "search for :::%s:::\n", searchTerm ); */
1133
1134         /* Clear any existing search */
1135         if( _compWindow_->searchTerm ) {
1136                 g_free( _compWindow_->searchTerm );
1137         }
1138         _compWindow_->searchTerm = g_strdup( searchTerm );
1139
1140         /* Perform search on local completion index */
1141         ncount = complete_address( searchTerm );
1142         if( 0 < ncount ) {
1143                 new = get_next_complete_address();
1144                 g_free( new );
1145         }
1146
1147         /* Select the address if there is only one match */
1148         if (ncount == 2) {
1149                 /* Display selected address in entry field */           
1150                 gchar *addr = get_complete_address(1);
1151
1152                 if (addr) {
1153                         replace_address_in_edit(entry, addr, cursor_pos);
1154                         g_free(addr);
1155                 }
1156
1157                 /* Discard the window */
1158                 clear_completion_cache();
1159         }
1160         /* Make sure that drop-down appears uniform! */
1161         else if( ncount == 0 ) {
1162                 addrcompl_add_queue( g_strdup( searchTerm ) );
1163         }
1164         g_free( searchTerm );
1165
1166         return TRUE;
1167 }
1168
1169 /**
1170  * Create new address completion window for specified entry.
1171  * \param entry_ Entry widget to associate with window.
1172  */
1173 static void address_completion_create_completion_window( GtkEntry *entry_ )
1174 {
1175         gint x, y, height, width, depth;
1176         GtkWidget *scroll, *list_view;
1177         GtkRequisition r;
1178         GtkWidget *window;
1179         GtkWidget *entry = GTK_WIDGET(entry_);
1180
1181         /* Create new window and list */
1182         window = gtk_window_new(GTK_WINDOW_POPUP);
1183         list_view  = addr_compl_list_view_create(_compWindow_);
1184
1185         /* Destroy any existing window */
1186         addrcompl_destroy_window( _compWindow_ );
1187
1188         /* Create new object */
1189         _compWindow_->window    = window;
1190         _compWindow_->entry     = entry;
1191         _compWindow_->list_view = list_view;
1192         _compWindow_->listCount = 0;
1193         _compWindow_->in_mouse  = FALSE;
1194
1195         scroll = gtk_scrolled_window_new(NULL, NULL);
1196         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
1197                                        GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
1198         gtk_container_add(GTK_CONTAINER(window), scroll);
1199         gtk_container_add(GTK_CONTAINER(scroll), list_view);
1200
1201         /* Use entry widget to create initial window */
1202         gdk_window_get_geometry(entry->window, &x, &y, &width, &height, &depth);
1203         gdk_window_get_deskrelative_origin (entry->window, &x, &y);
1204         y += height;
1205         gtk_window_move(GTK_WINDOW(window), x, y);
1206
1207         /* Resize window to fit initial (empty) address list */
1208         gtk_widget_size_request( list_view, &r );
1209         gtk_widget_set_size_request( window, width, r.height );
1210         gtk_widget_show_all( window );
1211         gtk_widget_size_request( list_view, &r );
1212
1213         /* Setup handlers */
1214         g_signal_connect(G_OBJECT(list_view), "button_press_event",
1215                          G_CALLBACK(list_view_button_press),
1216                          _compWindow_);
1217                          
1218         g_signal_connect(G_OBJECT(list_view), "button_release_event",
1219                          G_CALLBACK(list_view_button_release),
1220                          _compWindow_);
1221         
1222         g_signal_connect(G_OBJECT(window),
1223                          "button-press-event",
1224                          G_CALLBACK(completion_window_button_press),
1225                          _compWindow_ );
1226         g_signal_connect(G_OBJECT(window),
1227                          "key-press-event",
1228                          G_CALLBACK(completion_window_key_press),
1229                          _compWindow_ );
1230         gdk_pointer_grab(window->window, TRUE,
1231                          GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK |
1232                          GDK_BUTTON_RELEASE_MASK,
1233                          NULL, NULL, GDK_CURRENT_TIME);
1234         gtk_grab_add( window );
1235
1236         /* XXX: GTK2 too??? 
1237          *
1238          * GTK1: this gets rid of the irritating focus rectangle that doesn't
1239          * follow the selection */
1240         GTK_WIDGET_UNSET_FLAGS(list_view, GTK_CAN_FOCUS);
1241 }
1242
1243 /**
1244  * Respond to button press in completion window. Check if mouse click is
1245  * anywhere outside the completion window. In that case the completion
1246  * window is destroyed, and the original searchTerm is restored.
1247  *
1248  * \param widget   Window object.
1249  * \param event    Event.
1250  * \param compWin  Reference to completion window.
1251  */
1252 static gboolean completion_window_button_press(GtkWidget *widget,
1253                                                GdkEventButton *event,
1254                                                CompletionWindow *compWin )
1255 {
1256         GtkWidget *event_widget, *entry;
1257         gchar *searchTerm;
1258         gint cursor_pos;
1259         gboolean restore = TRUE;
1260
1261         g_return_val_if_fail(compWin != NULL, FALSE);
1262
1263         entry = compWin->entry;
1264         g_return_val_if_fail(entry != NULL, FALSE);
1265
1266         /* Test where mouse was clicked */
1267         event_widget = gtk_get_event_widget((GdkEvent *)event);
1268         if (event_widget != widget) {
1269                 while (event_widget) {
1270                         if (event_widget == widget)
1271                                 return FALSE;
1272                         else if (event_widget == entry) {
1273                                 restore = FALSE;
1274                                 break;
1275                         }
1276                         event_widget = event_widget->parent;
1277                 }
1278         }
1279
1280         if (restore) {
1281                 /* Clicked outside of completion window - restore */
1282                 searchTerm = _compWindow_->searchTerm;
1283                 g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1284                 replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos);
1285         }
1286
1287         clear_completion_cache();
1288         addrcompl_destroy_window( _compWindow_ );
1289
1290         return TRUE;
1291 }
1292
1293 /**
1294  * Respond to key press in completion window.
1295  * \param widget   Window object.
1296  * \param event    Event.
1297  * \param compWind Reference to completion window.
1298  */
1299 static gboolean completion_window_key_press(GtkWidget *widget,
1300                                             GdkEventKey *event,
1301                                             CompletionWindow *compWin )
1302 {
1303         GdkEventKey tmp_event;
1304         GtkWidget *entry;
1305         gchar *searchTerm;
1306         gint cursor_pos;
1307         GtkWidget *list_view;
1308         GtkWidget *parent;
1309
1310         g_return_val_if_fail(compWin != NULL, FALSE);
1311
1312         entry = compWin->entry;
1313         list_view = compWin->list_view;
1314         g_return_val_if_fail(entry != NULL, FALSE);
1315
1316         /* allow keyboard navigation in the alternatives tree view */
1317         if (event->keyval == GDK_Up || event->keyval == GDK_Down ||
1318             event->keyval == GDK_Page_Up || event->keyval == GDK_Page_Down) {
1319                 completion_window_advance_selection
1320                         (GTK_TREE_VIEW(list_view),
1321                          event->keyval == GDK_Down ||
1322                          event->keyval == GDK_Page_Down ? TRUE : FALSE);
1323                 return FALSE;
1324         }               
1325
1326 #if 0   
1327         /* also make tab / shift tab go to next previous completion entry. we're
1328          * changing the key value */
1329         if (event->keyval == GDK_Tab || event->keyval == GDK_ISO_Left_Tab) {
1330                 event->keyval = (event->state & GDK_SHIFT_MASK)
1331                         ? GDK_Up : GDK_Down;
1332                 /* need to reset shift state if going up */
1333                 if (event->state & GDK_SHIFT_MASK)
1334                         event->state &= ~GDK_SHIFT_MASK;
1335                 completion_window_advance_selection(GTK_CLIST(clist), 
1336                         event->keyval == GDK_Down ? TRUE : FALSE);
1337                 return FALSE;
1338         }
1339 #endif
1340
1341         /* make tab move to next field */
1342         if( event->keyval == GDK_Tab ) {
1343                 /* Reference to parent */
1344                 parent = GTK_WIDGET(entry)->parent;
1345
1346                 /* Discard the window */
1347                 clear_completion_cache();
1348                 addrcompl_destroy_window( _compWindow_ );
1349
1350                 /* Move focus to next widget */
1351                 if( parent ) {
1352                         gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1353                 }
1354                 return FALSE;
1355         }
1356
1357         /* make backtab move to previous field */
1358         if( event->keyval == GDK_ISO_Left_Tab ) {
1359                 /* Reference to parent */
1360                 parent = GTK_WIDGET(entry)->parent;
1361
1362                 /* Discard the window */
1363                 clear_completion_cache();
1364                 addrcompl_destroy_window( _compWindow_ );
1365
1366                 /* Move focus to previous widget */
1367                 if( parent ) {
1368                         gtk_widget_child_focus( parent, GTK_DIR_TAB_BACKWARD );
1369                 }
1370                 return FALSE;
1371         }
1372
1373         /* look for presses that accept the selection */
1374         if (event->keyval == GDK_Return || event->keyval == GDK_space) {
1375                 /* User selected address with a key press */
1376
1377                 /* Display selected address in entry field */           
1378                 completion_window_apply_selection(
1379                         GTK_TREE_VIEW(list_view), GTK_ENTRY(entry) );
1380
1381                 /* Discard the window */
1382                 clear_completion_cache();
1383                 addrcompl_destroy_window( _compWindow_ );
1384                 return FALSE;
1385         }
1386
1387         /* key state keys should never be handled */
1388         if (event->keyval == GDK_Shift_L
1389                  || event->keyval == GDK_Shift_R
1390                  || event->keyval == GDK_Control_L
1391                  || event->keyval == GDK_Control_R
1392                  || event->keyval == GDK_Caps_Lock
1393                  || event->keyval == GDK_Shift_Lock
1394                  || event->keyval == GDK_Meta_L
1395                  || event->keyval == GDK_Meta_R
1396                  || event->keyval == GDK_Alt_L
1397                  || event->keyval == GDK_Alt_R) {
1398                 return FALSE;
1399         }
1400
1401         /* some other key, let's restore the searchTerm (orignal text) */
1402         searchTerm = _compWindow_->searchTerm;
1403         g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1404         replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos);
1405
1406         /* make sure anything we typed comes in the edit box */
1407         tmp_event.type       = event->type;
1408         tmp_event.window     = entry->window;
1409         tmp_event.send_event = TRUE;
1410         tmp_event.time       = event->time;
1411         tmp_event.state      = event->state;
1412         tmp_event.keyval     = event->keyval;
1413         tmp_event.length     = event->length;
1414         tmp_event.string     = event->string;
1415         gtk_widget_event(entry, (GdkEvent *)&tmp_event);
1416
1417         /* and close the completion window */
1418         clear_completion_cache();
1419         addrcompl_destroy_window( _compWindow_ );
1420
1421         return TRUE;
1422 }
1423
1424 /*
1425  * ============================================================================
1426  * Publically accessible functions.
1427  * ============================================================================
1428  */
1429
1430 /**
1431  * Setup completion object.
1432  */
1433 void addrcompl_initialize( void ) {
1434         /* printf( "addrcompl_initialize...\n" ); */
1435         if( ! _compWindow_ ) {
1436                 _compWindow_ = addrcompl_create_window();
1437         }
1438         _queryID_ = 0;
1439         _completionIdleID_ = 0;
1440         /* printf( "addrcompl_initialize...done\n" ); */
1441 }
1442
1443 /**
1444  * Teardown completion object.
1445  */
1446 void addrcompl_teardown( void ) {
1447         /* printf( "addrcompl_teardown...\n" ); */
1448         addrcompl_free_window( _compWindow_ );
1449         _compWindow_ = NULL;
1450         if( _displayQueue_ ) {
1451                 g_list_free( _displayQueue_ );
1452         }
1453         _displayQueue_ = NULL;
1454         _completionIdleID_ = 0;
1455         /* printf( "addrcompl_teardown...done\n" ); */
1456 }
1457
1458 /*
1459  * tree view functions
1460  */
1461
1462 static GtkListStore *addr_compl_create_store(void)
1463 {
1464         return gtk_list_store_new(N_ADDR_COMPL_COLUMNS,
1465                                   G_TYPE_STRING,
1466                                   -1);
1467 }
1468                                              
1469 static GtkWidget *addr_compl_list_view_create(CompletionWindow *window)
1470 {
1471         GtkTreeView *list_view;
1472         GtkTreeSelection *selector;
1473         GtkTreeModel *model;
1474
1475         model = GTK_TREE_MODEL(addr_compl_create_store());
1476         list_view = GTK_TREE_VIEW(gtk_tree_view_new_with_model(model));
1477         g_object_unref(model);  
1478         
1479         gtk_tree_view_set_rules_hint(list_view, prefs_common.enable_rules_hint);
1480         gtk_tree_view_set_headers_visible(list_view, FALSE);
1481         
1482         selector = gtk_tree_view_get_selection(list_view);
1483         gtk_tree_selection_set_mode(selector, GTK_SELECTION_BROWSE);
1484         gtk_tree_selection_set_select_function(selector, addr_compl_selected,
1485                                                window, NULL);
1486
1487         /* create the columns */
1488         addr_compl_create_list_view_columns(GTK_WIDGET(list_view));
1489
1490         return GTK_WIDGET(list_view);
1491 }
1492
1493 static void addr_compl_create_list_view_columns(GtkWidget *list_view)
1494 {
1495         GtkTreeViewColumn *column;
1496         GtkCellRenderer *renderer;
1497
1498         renderer = gtk_cell_renderer_text_new();
1499         column = gtk_tree_view_column_new_with_attributes
1500                 ("", renderer, "text", ADDR_COMPL_ADDRESS, NULL);
1501         gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);          
1502 }
1503
1504 static gboolean list_view_button_press(GtkWidget *widget, GdkEventButton *event,
1505                                        CompletionWindow *window)
1506 {
1507         if (window && event && event->type == GDK_BUTTON_PRESS) {
1508                 window->in_mouse = TRUE;
1509         }
1510         return FALSE;
1511 }
1512
1513 static gboolean list_view_button_release(GtkWidget *widget, GdkEventButton *event,
1514                                          CompletionWindow *window)
1515 {
1516         if (window && event && event->type == GDK_BUTTON_RELEASE) {
1517                 window->in_mouse = FALSE;
1518         }
1519         return FALSE;
1520 }
1521
1522 static gboolean addr_compl_selected(GtkTreeSelection *selector,
1523                                     GtkTreeModel *model, 
1524                                     GtkTreePath *path,
1525                                     gboolean currently_selected,
1526                                     gpointer data)
1527 {
1528         CompletionWindow *window = data;
1529
1530         if (currently_selected)
1531                 return TRUE;
1532         
1533         if (!window->in_mouse)
1534                 return TRUE;
1535
1536         /* XXX: select the entry and kill window later... select is called before
1537          * any other mouse events handlers including the tree view internal one;
1538          * not using a time out would result in a crash. if this doesn't work
1539          * safely, maybe we should set variables when receiving button presses
1540          * in the tree view. */
1541         if (!window->destroying) {       
1542                 window->destroying = TRUE;       
1543                 g_idle_add((GSourceFunc) addr_compl_defer_select_destruct, data);
1544         }               
1545         
1546         return TRUE;
1547 }
1548
1549 static gboolean addr_compl_defer_select_destruct(CompletionWindow *window)
1550 {
1551         GtkEntry *entry = GTK_ENTRY(window->entry);
1552
1553         completion_window_apply_selection(GTK_TREE_VIEW(window->list_view), 
1554                                           entry);
1555
1556         clear_completion_cache();
1557
1558         addrcompl_destroy_window(window);
1559         return FALSE;
1560 }
1561
1562
1563 /*
1564  * End of Source.
1565  */
1566