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