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