2005-04-21 [paul] 1.9.6cvs45
[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 <pthread.h>
49
50 /*!
51  *\brief        For the GtkListStore
52  */
53 enum {
54         ADDR_COMPL_ADDRESS,
55         N_ADDR_COMPL_COLUMNS
56 };
57
58 /*
59  * How it works:
60  *
61  * The address book is read into memory. We set up an address list
62  * containing all address book entries. Next we make the completion
63  * list, which contains all the completable strings, and store a
64  * reference to the address entry it belongs to.
65  * After calling the g_completion_complete(), we get a reference
66  * to a valid email address.  
67  *
68  * Completion is very simplified. We never complete on another prefix,
69  * i.e. we neglect the next smallest possible prefix for the current
70  * completion cache. This is simply done so we might break up the
71  * addresses a little more (e.g. break up alfons@proteus.demon.nl into
72  * something like alfons, proteus, demon, nl; and then completing on
73  * any of those words).
74  */ 
75         
76 /**
77  * address_entry - structure which refers to the original address entry in the
78  * address book .
79  */
80 typedef struct
81 {
82         gchar *name;
83         gchar *address;
84 } address_entry;
85
86 /**
87  * completion_entry - structure used to complete addresses, with a reference
88  * the the real address information.
89  */
90 typedef struct
91 {
92         gchar           *string; /* string to complete */
93         address_entry   *ref;    /* address the string belongs to  */
94 } completion_entry;
95
96 /*******************************************************************************/
97
98 static gint         g_ref_count;        /* list ref count */
99 static GList       *g_completion_list;  /* list of strings to be checked */
100 static GList       *g_address_list;     /* address storage */
101 static GCompletion *g_completion;       /* completion object */
102
103 /* To allow for continuing completion we have to keep track of the state
104  * using the following variables. No need to create a context object. */
105
106 static gint         g_completion_count;         /* nr of addresses incl. the prefix */
107 static gint         g_completion_next;          /* next prev address */
108 static GSList      *g_completion_addresses;     /* unique addresses found in the
109                                                    completion cache. */
110 static gchar       *g_completion_prefix;        /* last prefix. (this is cached here
111                                                  * because the prefix passed to g_completion
112                                                  * is g_strdown()'ed */
113
114 /*******************************************************************************/
115
116 /*
117  * Define the structure of the completion window.
118  */
119 typedef struct _CompletionWindow CompletionWindow;
120 struct _CompletionWindow {
121         gint      listCount;
122         gchar     *searchTerm;
123         GtkWidget *window;
124         GtkWidget *entry;
125         GtkWidget *list_view;
126
127         gboolean   in_mouse;    /*!< mouse press pending... */
128         gboolean   destroying;  /*!< destruction in progress */
129 };
130
131 static GtkListStore *addr_compl_create_store    (void);
132
133 static void addr_compl_list_view_add_address    (GtkWidget *list_view,
134                                                  const gchar *address);
135
136 static GtkWidget *addr_compl_list_view_create   (CompletionWindow *window);
137
138 static void addr_compl_create_list_view_columns (GtkWidget *list_view);
139
140 static gboolean list_view_button_press          (GtkWidget *widget, 
141                                                  GdkEventButton *event,
142                                                  CompletionWindow *window);
143
144 static gboolean list_view_button_release        (GtkWidget *widget, 
145                                                  GdkEventButton *event,
146                                                  CompletionWindow *window);
147
148 static gboolean addr_compl_selected             (GtkTreeSelection *selector,
149                                                  GtkTreeModel *model, 
150                                                  GtkTreePath *path,
151                                                  gboolean currently_selected,
152                                                  gpointer data);
153                                                  
154 static gboolean addr_compl_defer_select_destruct(CompletionWindow *window);
155
156 /**
157  * Function used by GTK to find the string data to be used for completion.
158  * \param data Pointer to data being processed.
159  */
160 static gchar *completion_func(gpointer data)
161 {
162         g_return_val_if_fail(data != NULL, NULL);
163
164         return ((completion_entry *)data)->string;
165
166
167 /**
168  * Initialize all completion index data.
169  */
170 static void init_all(void)
171 {
172         g_completion = g_completion_new(completion_func);
173         g_return_if_fail(g_completion != NULL);
174 }
175
176 /**
177  * Free up all completion index data.
178  */
179 static void free_all(void)
180 {
181         GList *walk;
182         
183         walk = g_list_first(g_completion_list);
184         for (; walk != NULL; walk = g_list_next(walk)) {
185                 completion_entry *ce = (completion_entry *) walk->data;
186                 g_free(ce->string);
187                 g_free(walk->data);
188         }
189         g_list_free(g_completion_list);
190         g_completion_list = NULL;
191         
192         walk = g_address_list;
193         for (; walk != NULL; walk = g_list_next(walk)) {
194                 address_entry *ae = (address_entry *) walk->data;
195                 g_free(ae->name);
196                 g_free(ae->address);
197                 g_free(walk->data);
198         }
199         g_list_free(g_address_list);
200         g_address_list = NULL;
201         
202         g_completion_free(g_completion);
203         g_completion = NULL;
204 }
205
206 /**
207  * Append specified address entry to the index.
208  * \param str Index string value.
209  * \param ae  Entry containing address data.
210  */
211 static void add_address1(const char *str, address_entry *ae)
212 {
213         completion_entry *ce1;
214         ce1 = g_new0(completion_entry, 1),
215         ce1->string = g_utf8_strdown(str, -1);
216         /* GCompletion list is case sensitive */
217         g_strdown(ce1->string);
218         ce1->ref = ae;
219
220         g_completion_list = g_list_prepend(g_completion_list, ce1);
221 }
222
223 /**
224  * Adds address to the completion list. This function looks complicated, but
225  * it's only allocation checks. Each value will be included in the index.
226  * \param name    Recipient name.
227  * \param address EMail address.
228  * \param alias   Alias to append.
229  * \return <code>0</code> if entry appended successfully, or <code>-1</code>
230  *         if failure.
231  */
232 static gint add_address(const gchar *name, const gchar *address, 
233                         const gchar *nick, const gchar *alias)
234 {
235         address_entry    *ae;
236
237         if (!name || !address) return -1;
238
239         ae = g_new0(address_entry, 1);
240
241         g_return_val_if_fail(ae != NULL, -1);
242
243         ae->name    = g_strdup(name);
244         ae->address = g_strdup(address);                
245
246         g_address_list = g_list_prepend(g_address_list, ae);
247
248         add_address1(name, ae);
249         add_address1(address, ae);
250         
251         if (nick != NULL)
252                 add_address1(nick, ae);
253         
254         if ( alias != NULL ) {
255                 add_address1(alias, ae);
256         }
257
258         return 0;
259 }
260
261 /**
262  * Read address book, creating all entries in the completion index.
263  */ 
264 static void read_address_book(void) {   
265         addrindex_load_completion( add_address );
266         g_address_list = g_list_reverse(g_address_list);
267         g_completion_list = g_list_reverse(g_completion_list);
268 }
269
270 /**
271  * Test whether there is a completion pending.
272  * \return <code>TRUE</code> if pending.
273  */
274 static gboolean is_completion_pending(void)
275 {
276         /* check if completion pending, i.e. we might satisfy a request for the next
277          * or previous address */
278          return g_completion_count;
279 }
280
281 /**
282  * Clear the completion cache.
283  */
284 static void clear_completion_cache(void)
285 {
286         if (is_completion_pending()) {
287                 if (g_completion_prefix)
288                         g_free(g_completion_prefix);
289
290                 if (g_completion_addresses) {
291                         g_slist_free(g_completion_addresses);
292                         g_completion_addresses = NULL;
293                 }
294
295                 g_completion_count = g_completion_next = 0;
296         }
297 }
298
299 /**
300  * Prepare completion index. This function should be called prior to attempting
301  * address completion.
302  * \return The number of addresses in the completion list.
303  */
304 gint start_address_completion(void)
305 {
306         clear_completion_cache();
307         if (!g_ref_count) {
308                 init_all();
309                 /* open the address book */
310                 read_address_book();
311                 /* merge the completion entry list into g_completion */
312                 if (g_completion_list)
313                         g_completion_add_items(g_completion, g_completion_list);
314         }
315         g_ref_count++;
316         debug_print("start_address_completion ref count %d\n", g_ref_count);
317
318         return g_list_length(g_completion_list);
319 }
320
321 /**
322  * Retrieve a possible address (or a part) from an entry box. To make life
323  * easier, we only look at the last valid address component; address
324  * completion only works at the last string component in the entry box.
325  *
326  * \param entry Address entry field.
327  * \param start_pos Address of start position of address.
328  * \return Possible address.
329  */
330 static gchar *get_address_from_edit(GtkEntry *entry, gint *start_pos)
331 {
332         const gchar *edit_text, *p;
333         gint cur_pos;
334         gboolean in_quote = FALSE;
335         gboolean in_bracket = FALSE;
336         gchar *str;
337
338         edit_text = gtk_entry_get_text(entry);
339         if (edit_text == NULL) return NULL;
340
341         cur_pos = gtk_editable_get_position(GTK_EDITABLE(entry));
342
343         /* scan for a separator. doesn't matter if walk points at null byte. */
344         for (p = g_utf8_offset_to_pointer(edit_text, cur_pos);
345              p > edit_text;
346              p = g_utf8_prev_char(p)) {
347                 if (*p == '"') {
348                         in_quote = TRUE;
349                 } else if (!in_quote) {
350                         if (!in_bracket && *p == ',') {
351                                 break;
352                         } else if (*p == '<')
353                                 in_bracket = TRUE;
354                         else if (*p == '>')
355                                 in_bracket = FALSE;
356                 }
357         }
358
359         /* have something valid */
360         if (g_utf8_strlen(p, -1) == 0)
361                 return NULL;
362
363 #define IS_VALID_CHAR(x) \
364         (isalnum(x) || (x) == '"' || (x) == '<' || (((unsigned char)(x)) > 0x7f))
365
366         /* now scan back until we hit a valid character */
367         for (; *p && !IS_VALID_CHAR(*p); p = g_utf8_next_char(p))
368                 ;
369
370 #undef IS_VALID_CHAR
371
372         if (g_utf8_strlen(p, -1) == 0)
373                 return NULL;
374
375         if (start_pos) *start_pos = g_utf8_pointer_to_offset(edit_text, p);
376
377         str = g_strdup(p);
378
379         return str;
380
381
382 /**
383  * Replace an incompleted address with a completed one.
384  * \param entry     Address entry field.
385  * \param newtext   New text.
386  * \param start_pos Insertion point in entry field.
387  */
388 static void replace_address_in_edit(GtkEntry *entry, const gchar *newtext,
389                              gint start_pos)
390 {
391         if (!newtext) return;
392         gtk_editable_delete_text(GTK_EDITABLE(entry), start_pos, -1);
393         gtk_editable_insert_text(GTK_EDITABLE(entry), newtext, strlen(newtext),
394                                  &start_pos);
395         gtk_editable_set_position(GTK_EDITABLE(entry), -1);
396 }
397
398 /**
399  * Attempt to complete an address, and returns the number of addresses found.
400  * Use <code>get_complete_address()</code> to get an entry from the index.
401  *
402  * \param  str Search string to find.
403  * \return Zero if no match was found, otherwise the number of addresses; the
404  *         original prefix (search string) will appear at index 0. 
405  */
406 guint complete_address(const gchar *str)
407 {
408         GList *result;
409         gchar *d;
410         guint  count, cpl;
411         completion_entry *ce;
412
413         g_return_val_if_fail(str != NULL, 0);
414
415         /* g_completion is case sensitive */
416         d = g_utf8_strdown(str, -1);
417
418         clear_completion_cache();
419         g_completion_prefix = g_strdup(str);
420
421         result = g_completion_complete(g_completion, d, NULL);
422
423         count = g_list_length(result);
424         if (count) {
425                 /* create list with unique addresses  */
426                 for (cpl = 0, result = g_list_first(result);
427                      result != NULL;
428                      result = g_list_next(result)) {
429                         ce = (completion_entry *)(result->data);
430                         if (NULL == g_slist_find(g_completion_addresses,
431                                                  ce->ref)) {
432                                 cpl++;
433                                 g_completion_addresses =
434                                         g_slist_append(g_completion_addresses,
435                                                        ce->ref);
436                         }
437                 }
438                 count = cpl + 1;        /* index 0 is the original prefix */
439                 g_completion_next = 1;  /* we start at the first completed one */
440         } else {
441                 g_free(g_completion_prefix);
442                 g_completion_prefix = NULL;
443         }
444
445         g_completion_count = count;
446
447         g_free(d);
448
449         return count;
450 }
451
452 /**
453  * Return a complete address from the index.
454  * \param index Index of entry that was found (by the previous call to
455  *              <code>complete_address()</code>
456  * \return Completed address string; this should be freed when done.
457  */
458 gchar *get_complete_address(gint index)
459 {
460         const address_entry *p;
461         gchar *address = NULL;
462
463         if (index < g_completion_count) {
464                 if (index == 0)
465                         address = g_strdup(g_completion_prefix);
466                 else {
467                         /* get something from the unique addresses */
468                         p = (address_entry *)g_slist_nth_data
469                                 (g_completion_addresses, index - 1);
470                         if (p != NULL) {
471                                 if (!p->name || p->name[0] == '\0')
472                                         address = g_strdup_printf(p->address);
473                                 else if (strchr_with_skip_quote(p->name, '"', ','))
474                                         address = g_strdup_printf
475                                                 ("\"%s\" <%s>", p->name, p->address);
476                                 else
477                                         address = g_strdup_printf
478                                                 ("%s <%s>", p->name, p->address);
479                         }
480                 }
481         }
482
483         return address;
484 }
485
486 /**
487  * Return the next complete address match from the completion index.
488  * \return Completed address string; this should be freed when done.
489  */
490 static gchar *get_next_complete_address(void)
491 {
492         if (is_completion_pending()) {
493                 gchar *res;
494
495                 res = get_complete_address(g_completion_next);
496                 g_completion_next += 1;
497                 if (g_completion_next >= g_completion_count)
498                         g_completion_next = 0;
499
500                 return res;
501         } else
502                 return NULL;
503 }
504
505 /**
506  * Return a count of the completed matches in the completion index.
507  * \return Number of matched entries.
508  */
509 static guint get_completion_count(void)
510 {
511         if (is_completion_pending())
512                 return g_completion_count;
513         else
514                 return 0;
515 }
516
517 /**
518  * Invalidate address completion index. This function should be called whenever
519  * the address book changes. This forces data to be read into the completion
520  * data.
521  * \return Number of entries in index.
522  */
523 gint invalidate_address_completion(void)
524 {
525         if (g_ref_count) {
526                 /* simply the same as start_address_completion() */
527                 debug_print("Invalidation request for address completion\n");
528                 free_all();
529                 init_all();
530                 read_address_book();
531                 g_completion_add_items(g_completion, g_completion_list);
532                 clear_completion_cache();
533         }
534
535         return g_list_length(g_completion_list);
536 }
537
538 /**
539  * Finished with completion index. This function should be called after
540  * matching addresses.
541  * \return Reference count.
542  */
543 gint end_address_completion(void)
544 {
545         clear_completion_cache();
546
547         if (0 == --g_ref_count)
548                 free_all();
549
550         debug_print("end_address_completion ref count %d\n", g_ref_count);
551
552         return g_ref_count; 
553 }
554
555 /**
556  * Completion window.
557  */
558 static CompletionWindow *_compWindow_ = NULL;
559
560 /**
561  * Mutex to protect callback from multiple threads.
562  */
563 static pthread_mutex_t _completionMutex_ = PTHREAD_MUTEX_INITIALIZER;
564
565 /**
566  * Completion queue list.
567  */
568 static GList *_displayQueue_ = NULL;
569
570 /**
571  * Current query ID.
572  */
573 static gint _queryID_ = 0;
574
575 /**
576  * Completion idle ID.
577  */
578 static guint _completionIdleID_ = 0;
579
580 /*
581  * address completion entry ui. the ui (completion list was inspired by galeon's
582  * auto completion list). remaining things powered by sylpheed's completion engine.
583  */
584
585 #define ENTRY_DATA_TAB_HOOK     "tab_hook"      /* used to lookup entry */
586
587 static void address_completion_mainwindow_set_focus     (GtkWindow   *window,
588                                                          GtkWidget   *widget,
589                                                          gpointer     data);
590 static gboolean address_completion_entry_key_pressed    (GtkEntry    *entry,
591                                                          GdkEventKey *ev,
592                                                          gpointer     data);
593 static gboolean address_completion_complete_address_in_entry
594                                                         (GtkEntry    *entry,
595                                                          gboolean     next);
596 static void address_completion_create_completion_window (GtkEntry    *entry);
597
598 static gboolean completion_window_button_press
599                                         (GtkWidget       *widget,
600                                          GdkEventButton  *event,
601                                          CompletionWindow *compWin );
602
603 static gboolean completion_window_key_press
604                                         (GtkWidget       *widget,
605                                          GdkEventKey     *event,
606                                          CompletionWindow *compWin );
607 static void address_completion_create_completion_window( GtkEntry *entry_ );
608
609 /**
610  * Create a completion window object.
611  * \return Initialized completion window.
612  */
613 static CompletionWindow *addrcompl_create_window( void ) {
614         CompletionWindow *cw;
615
616         cw = g_new0( CompletionWindow, 1 );
617         cw->listCount = 0;
618         cw->searchTerm = NULL;
619         cw->window = NULL;
620         cw->entry = NULL;
621         cw->list_view = NULL;
622         cw->in_mouse = FALSE;
623         cw->destroying = FALSE;
624
625         return cw;      
626 }
627
628 /**
629  * Destroy completion window.
630  * \param cw Window to destroy.
631  */
632 static void addrcompl_destroy_window( CompletionWindow *cw ) {
633         /* Stop all searches currently in progress */
634         addrindex_stop_search( _queryID_ );
635
636         /* Remove idler function... or application may not terminate */
637         if( _completionIdleID_ != 0 ) {
638                 gtk_idle_remove( _completionIdleID_ );
639                 _completionIdleID_ = 0;
640         }
641
642         /* Now destroy window */        
643         if( cw ) {
644                 /* Clear references to widgets */
645                 cw->entry = NULL;
646                 cw->list_view = NULL;
647
648                 /* Free objects */
649                 if( cw->window ) {
650                         gtk_widget_hide( cw->window );
651                         gtk_widget_destroy( cw->window );
652                 }
653                 cw->window = NULL;
654                 cw->destroying = FALSE;
655                 cw->in_mouse = FALSE;
656         }
657         
658 }
659
660 /**
661  * Free up completion window.
662  * \param cw Window to free.
663  */
664 static void addrcompl_free_window( CompletionWindow *cw ) {
665         if( cw ) {
666                 addrcompl_destroy_window( cw );
667
668                 g_free( cw->searchTerm );
669                 cw->searchTerm = NULL;
670
671                 /* Clear references */          
672                 cw->listCount = 0;
673
674                 /* Free object */               
675                 g_free( cw );
676         }
677 }
678
679 /**
680  * Advance selection to previous/next item in list.
681  * \param list_view List to process.
682  * \param forward Set to <i>TRUE</i> to select next or <i>FALSE</i> for
683  *                previous entry.
684  */
685 static void completion_window_advance_selection(GtkTreeView *list_view, gboolean forward)
686 {
687         GtkTreeSelection *selection;
688         GtkTreeIter iter;
689         GtkTreeModel *model;
690
691         g_return_if_fail(list_view != NULL);
692
693         selection = gtk_tree_view_get_selection(list_view);
694         if (!gtk_tree_selection_get_selected(selection, &model, &iter))
695                 return;
696
697         if (forward) { 
698                 forward = gtk_tree_model_iter_next(model, &iter);
699                 if (forward) 
700                         gtk_tree_selection_select_iter(selection, &iter);
701         } else {
702                 GtkTreePath *prev;
703
704                 prev = gtk_tree_model_get_path(model, &iter);
705                 if (!prev) 
706                         return;
707
708                 if (gtk_tree_path_prev(prev))
709                         gtk_tree_selection_select_path(selection, prev);
710                 
711                 gtk_tree_path_free(prev);
712         }
713 }
714
715 #if 0
716 /* completion_window_accept_selection() - accepts the current selection in the
717  * clist, and destroys the window */
718 static void completion_window_accept_selection(GtkWidget **window,
719                                                GtkCList *clist,
720                                                GtkEntry *entry)
721 {
722         gchar *address = NULL, *text = NULL;
723         gint   cursor_pos, row;
724
725         g_return_if_fail(window != NULL);
726         g_return_if_fail(*window != NULL);
727         g_return_if_fail(clist != NULL);
728         g_return_if_fail(entry != NULL);
729         g_return_if_fail(clist->selection != NULL);
730
731         /* FIXME: I believe it's acceptable to access the selection member directly  */
732         row = GPOINTER_TO_INT(clist->selection->data);
733
734         /* we just need the cursor position */
735         address = get_address_from_edit(entry, &cursor_pos);
736         g_free(address);
737         gtk_clist_get_text(clist, row, 0, &text);
738         replace_address_in_edit(entry, text, cursor_pos);
739
740         clear_completion_cache();
741         gtk_widget_destroy(*window);
742         *window = NULL;
743 }
744 #endif
745
746 /**
747  * Resize window to accommodate maximum number of address entries.
748  * \param cw Completion window.
749  */
750 static void addrcompl_resize_window( CompletionWindow *cw ) {
751         GtkRequisition r;
752         gint x, y, width, height, depth;
753
754         /* Get current geometry of window */
755         gdk_window_get_geometry( cw->window->window, &x, &y, &width, &height, &depth );
756
757         gtk_widget_hide_all( cw->window );
758         gtk_widget_show_all( cw->window );
759         gtk_widget_size_request( cw->list_view, &r );
760
761         /* Adjust window height to available screen space */
762         if( ( y + r.height ) > gdk_screen_height() ) {
763                 gtk_window_set_resizable(GTK_WINDOW(cw->window), FALSE);
764                 gtk_widget_set_size_request( cw->window, width, gdk_screen_height() - y );
765         } else
766                 gtk_widget_set_size_request(cw->window, width, r.height);
767 }
768
769 /**
770  * Add an address the completion window address list.
771  * \param cw      Completion window.
772  * \param address Address to add.
773  */
774 static void addrcompl_add_entry( CompletionWindow *cw, gchar *address ) {
775         GtkListStore *store;
776         GtkTreeIter iter;
777         GtkTreeSelection *selection;
778
779         store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(cw->list_view)));
780         gtk_list_store_append(store, &iter);
781
782         /* printf( "\t\tAdding :%s\n", address ); */
783         gtk_list_store_set(store, &iter, ADDR_COMPL_ADDRESS, address, -1);
784         cw->listCount++;
785
786         /* Resize window */
787         addrcompl_resize_window( cw );
788         gtk_grab_add( cw->window );
789
790         selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(cw->list_view));
791         gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store), &iter);
792
793         if( cw->listCount == 1 ) {
794                 /* Select first row for now */
795                 gtk_tree_selection_select_iter(selection, &iter);
796         }
797         else if( cw->listCount == 2 ) {
798                 gtk_tree_model_iter_next(GTK_TREE_MODEL(store), &iter);
799                 /* Move off first row */
800                 gtk_tree_selection_select_iter(selection, &iter);
801         }
802 }
803
804 /**
805  * Completion idle function. This function is called by the main (UI) thread
806  * during UI idle time while an address search is in progress. Items from the
807  * display queue are processed and appended to the address list.
808  *
809  * \param data Target completion window to receive email addresses.
810  * \return <i>TRUE</i> to ensure that idle event do not get ignored.
811  */
812 static gboolean addrcompl_idle( gpointer data ) {
813         GList *node;
814         gchar *address;
815
816         /* Process all entries in display queue */
817         pthread_mutex_lock( & _completionMutex_ );
818         if( _displayQueue_ ) {
819                 node = _displayQueue_;
820                 while( node ) {
821                         address = node->data;
822                         /* printf( "address ::: %s :::\n", address ); */
823                         addrcompl_add_entry( _compWindow_, address );
824                         g_free( address );
825                         node = g_list_next( node );
826                 }
827                 g_list_free( _displayQueue_ );
828                 _displayQueue_ = NULL;
829         }
830         pthread_mutex_unlock( & _completionMutex_ );
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 void addr_compl_list_view_add_address(GtkWidget *list_view,
1472                                              const gchar *address)
1473 {
1474         GtkTreeIter iter;
1475         GtkListStore *store = GTK_LIST_STORE(gtk_tree_view_get_model
1476                                         (GTK_TREE_VIEW(list_view)));
1477         
1478         gtk_list_store_append(store, &iter);
1479         gtk_list_store_set(store, &iter,
1480                            ADDR_COMPL_ADDRESS, address,
1481                            -1);
1482 }
1483                                              
1484 static GtkWidget *addr_compl_list_view_create(CompletionWindow *window)
1485 {
1486         GtkTreeView *list_view;
1487         GtkTreeSelection *selector;
1488         GtkTreeModel *model;
1489
1490         model = GTK_TREE_MODEL(addr_compl_create_store());
1491         list_view = GTK_TREE_VIEW(gtk_tree_view_new_with_model(model));
1492         g_object_unref(model);  
1493         
1494         gtk_tree_view_set_rules_hint(list_view, TRUE);
1495         gtk_tree_view_set_headers_visible(list_view, FALSE);
1496         
1497         selector = gtk_tree_view_get_selection(list_view);
1498         gtk_tree_selection_set_mode(selector, GTK_SELECTION_BROWSE);
1499         gtk_tree_selection_set_select_function(selector, addr_compl_selected,
1500                                                window, NULL);
1501
1502         /* create the columns */
1503         addr_compl_create_list_view_columns(GTK_WIDGET(list_view));
1504
1505         return GTK_WIDGET(list_view);
1506 }
1507
1508 static void addr_compl_create_list_view_columns(GtkWidget *list_view)
1509 {
1510         GtkTreeViewColumn *column;
1511         GtkCellRenderer *renderer;
1512
1513         renderer = gtk_cell_renderer_text_new();
1514         column = gtk_tree_view_column_new_with_attributes
1515                 ("", renderer, "text", ADDR_COMPL_ADDRESS, NULL);
1516         gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);          
1517 }
1518
1519 static gboolean list_view_button_press(GtkWidget *widget, GdkEventButton *event,
1520                                        CompletionWindow *window)
1521 {
1522         if (window && event && event->type == GDK_BUTTON_PRESS) {
1523                 window->in_mouse = TRUE;
1524         }
1525         return FALSE;
1526 }
1527
1528 static gboolean list_view_button_release(GtkWidget *widget, GdkEventButton *event,
1529                                          CompletionWindow *window)
1530 {
1531         if (window && event && event->type == GDK_BUTTON_RELEASE) {
1532                 window->in_mouse = FALSE;
1533         }
1534         return FALSE;
1535 }
1536
1537 static gboolean addr_compl_selected(GtkTreeSelection *selector,
1538                                     GtkTreeModel *model, 
1539                                     GtkTreePath *path,
1540                                     gboolean currently_selected,
1541                                     gpointer data)
1542 {
1543         CompletionWindow *window = data;
1544
1545         if (currently_selected)
1546                 return TRUE;
1547         
1548         if (!window->in_mouse)
1549                 return TRUE;
1550
1551         /* XXX: select the entry and kill window later... select is called before
1552          * any other mouse events handlers including the tree view internal one;
1553          * not using a time out would result in a crash. if this doesn't work
1554          * safely, maybe we should set variables when receiving button presses
1555          * in the tree view. */
1556         if (!window->destroying) {       
1557                 window->destroying = TRUE;       
1558                 g_idle_add((GSourceFunc) addr_compl_defer_select_destruct, data);
1559         }               
1560         
1561         return TRUE;
1562 }
1563
1564 static gboolean addr_compl_defer_select_destruct(CompletionWindow *window)
1565 {
1566         GtkEntry *entry = GTK_ENTRY(window->entry);
1567
1568         completion_window_apply_selection(GTK_TREE_VIEW(window->list_view), 
1569                                           entry);
1570
1571         clear_completion_cache();
1572
1573         addrcompl_destroy_window(window);
1574         return FALSE;
1575 }
1576
1577
1578 /*
1579  * End of Source.
1580  */
1581