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