2006-09-26 [colin] 2.5.2cvs1
[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 Sylpheed Claws Team.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  */
20
21 #ifdef HAVE_CONFIG_H
22 #  include "config.h"
23 #endif
24 #include "defs.h"
25
26 #include <glib.h>
27 #include <glib/gi18n.h>
28 #include <gdk/gdkkeysyms.h>
29 #include <gtk/gtkmain.h>
30 #include <gtk/gtkwindow.h>
31 #include <gtk/gtkentry.h>
32 #include <gtk/gtkeditable.h>
33 #include <gtk/gtkscrolledwindow.h>
34 #include <gtk/gtktreeview.h>
35 #include <gtk/gtktreemodel.h>
36 #include <gtk/gtkliststore.h>
37
38 #include <string.h>
39 #include <ctype.h>
40 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
41 #  include <wchar.h>
42 #  include <wctype.h>
43 #endif
44
45 #include "addrindex.h"
46 #include "addr_compl.h"
47 #include "utils.h"
48 #include "prefs_common.h"
49 #include "sylpheed.h"
50 #include <pthread.h>
51
52 /*!
53  *\brief        For the GtkListStore
54  */
55 enum {
56         ADDR_COMPL_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 _allowGroups_ = 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_GROUPS "allowgrp"      /* 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 && !_allowGroups_)
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  */
1023 static void completion_window_apply_selection(GtkTreeView *list_view, GtkEntry *entry)
1024 {
1025         gchar *address = NULL, *text = NULL;
1026         gint   cursor_pos;
1027         GtkWidget *parent;
1028         GtkTreeSelection *selection;
1029         GtkTreeModel *model;
1030         GtkTreeIter iter;
1031         gboolean is_group = FALSE;
1032         g_return_if_fail(list_view != NULL);
1033         g_return_if_fail(entry != NULL);
1034         GList *grp_emails = NULL;
1035
1036         selection = gtk_tree_view_get_selection(list_view);
1037         if (! gtk_tree_selection_get_selected(selection, &model, &iter))
1038                 return;
1039
1040         /* First remove the idler */
1041         if( _completionIdleID_ != 0 ) {
1042                 gtk_idle_remove( _completionIdleID_ );
1043                 _completionIdleID_ = 0;
1044         }
1045
1046         /* Process selected item */
1047         gtk_tree_model_get(model, &iter, ADDR_COMPL_ADDRESS, &text, 
1048                                 ADDR_COMPL_ISGROUP, &is_group, 
1049                                 ADDR_COMPL_GROUPLIST, &grp_emails,
1050                                 -1);
1051
1052         address = get_address_from_edit(entry, &cursor_pos);
1053         g_free(address);
1054         replace_address_in_edit(entry, text, cursor_pos, is_group, grp_emails);
1055         g_free(text);
1056
1057         /* Move focus to next widget */
1058         parent = GTK_WIDGET(entry)->parent;
1059         if( parent ) {
1060                 gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1061         }
1062 }
1063
1064 /**
1065  * Start address completion. Should be called when creating the main window
1066  * containing address completion entries.
1067  * \param mainwindow Main window.
1068  */
1069 void address_completion_start(GtkWidget *mainwindow)
1070 {
1071         start_address_completion(NULL);
1072
1073         /* register focus change hook */
1074         g_signal_connect(G_OBJECT(mainwindow), "set_focus",
1075                          G_CALLBACK(address_completion_mainwindow_set_focus),
1076                          mainwindow);
1077 }
1078
1079 /**
1080  * Need unique data to make unregistering signal handler possible for the auto
1081  * completed entry.
1082  */
1083 #define COMPLETION_UNIQUE_DATA (GINT_TO_POINTER(0xfeefaa))
1084
1085 /**
1086  * Register specified entry widget for address completion.
1087  * \param entry Address entry field.
1088  */
1089 void address_completion_register_entry(GtkEntry *entry, gboolean allow_groups)
1090 {
1091         g_return_if_fail(entry != NULL);
1092         g_return_if_fail(GTK_IS_ENTRY(entry));
1093
1094         /* add hooked property */
1095         g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, entry);
1096         g_object_set_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_GROUPS, GINT_TO_POINTER(allow_groups));
1097
1098         /* add keypress event */
1099         g_signal_connect_closure
1100                 (G_OBJECT(entry), "key_press_event",
1101                  g_cclosure_new(G_CALLBACK(address_completion_entry_key_pressed),
1102                                 COMPLETION_UNIQUE_DATA,
1103                                 NULL),
1104                  FALSE); /* magic */
1105 }
1106
1107 /**
1108  * Unregister specified entry widget from address completion operations.
1109  * \param entry Address entry field.
1110  */
1111 void address_completion_unregister_entry(GtkEntry *entry)
1112 {
1113         GtkObject *entry_obj;
1114
1115         g_return_if_fail(entry != NULL);
1116         g_return_if_fail(GTK_IS_ENTRY(entry));
1117
1118         entry_obj = g_object_get_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK);
1119         g_return_if_fail(entry_obj);
1120         g_return_if_fail(G_OBJECT(entry_obj) == G_OBJECT(entry));
1121
1122         /* has the hooked property? */
1123         g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, NULL);
1124
1125         /* remove the hook */
1126         g_signal_handlers_disconnect_by_func(G_OBJECT(entry), 
1127                         G_CALLBACK(address_completion_entry_key_pressed),
1128                         COMPLETION_UNIQUE_DATA);
1129 }
1130
1131 /**
1132  * End address completion. Should be called when main window with address
1133  * completion entries terminates. NOTE: this function assumes that it is
1134  * called upon destruction of the window.
1135  * \param mainwindow Main window.
1136  */
1137 void address_completion_end(GtkWidget *mainwindow)
1138 {
1139         /* if address_completion_end() is really called on closing the window,
1140          * we don't need to unregister the set_focus_cb */
1141         end_address_completion();
1142 }
1143
1144 /* if focus changes to another entry, then clear completion cache */
1145 static void address_completion_mainwindow_set_focus(GtkWindow *window,
1146                                                     GtkWidget *widget,
1147                                                     gpointer   data)
1148 {
1149         
1150         if (widget && GTK_IS_ENTRY(widget) &&
1151             g_object_get_data(G_OBJECT(widget), ENTRY_DATA_TAB_HOOK)) {
1152                 _allowGroups_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), ENTRY_DATA_ALLOW_GROUPS));
1153                 clear_completion_cache();
1154         }
1155 }
1156
1157 /**
1158  * Listener that watches for tab or other keystroke in address entry field.
1159  * \param entry Address entry field.
1160  * \param ev    Event object.
1161  * \param data  User data.
1162  * \return <i>TRUE</i>.
1163  */
1164 static gboolean address_completion_entry_key_pressed(GtkEntry    *entry,
1165                                                      GdkEventKey *ev,
1166                                                      gpointer     data)
1167 {
1168         if (ev->keyval == GDK_Tab) {
1169                 addrcompl_clear_queue();
1170                 _allowGroups_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_GROUPS));
1171                 if( address_completion_complete_address_in_entry( entry, TRUE ) ) {
1172                         /* route a void character to the default handler */
1173                         /* this is a dirty hack; we're actually changing a key
1174                          * reported by the system. */
1175                         ev->keyval = GDK_AudibleBell_Enable;
1176                         ev->state &= ~GDK_SHIFT_MASK;
1177
1178                         /* Create window */                     
1179                         address_completion_create_completion_window(entry);
1180
1181                         /* Start remote queries */
1182                         addrcompl_start_search();
1183
1184                         return TRUE;
1185                 }
1186                 else {
1187                         /* old behaviour */
1188                 }
1189         } else if (ev->keyval == GDK_Shift_L
1190                 || ev->keyval == GDK_Shift_R
1191                 || ev->keyval == GDK_Control_L
1192                 || ev->keyval == GDK_Control_R
1193                 || ev->keyval == GDK_Caps_Lock
1194                 || ev->keyval == GDK_Shift_Lock
1195                 || ev->keyval == GDK_Meta_L
1196                 || ev->keyval == GDK_Meta_R
1197                 || ev->keyval == GDK_Alt_L
1198                 || ev->keyval == GDK_Alt_R) {
1199                 /* these buttons should not clear the cache... */
1200         } else
1201                 clear_completion_cache();
1202
1203         return FALSE;
1204 }
1205 /**
1206  * Initialize search term for address completion.
1207  * \param entry Address entry field.
1208  */
1209 static gboolean address_completion_complete_address_in_entry(GtkEntry *entry,
1210                                                              gboolean  next)
1211 {
1212         gint ncount, cursor_pos;
1213         gchar *searchTerm, *new = NULL;
1214
1215         g_return_val_if_fail(entry != NULL, FALSE);
1216
1217         if (!GTK_WIDGET_HAS_FOCUS(entry)) return FALSE;
1218
1219         /* get an address component from the cursor */
1220         searchTerm = get_address_from_edit( entry, &cursor_pos );
1221         if( ! searchTerm ) return FALSE;
1222         /* printf( "search for :::%s:::\n", searchTerm ); */
1223
1224         /* Clear any existing search */
1225         g_free( _compWindow_->searchTerm );
1226         _compWindow_->searchTerm = g_strdup( searchTerm );
1227
1228         /* Perform search on local completion index */
1229         ncount = complete_address( searchTerm );
1230         if( 0 < ncount ) {
1231                 new = get_next_complete_address();
1232                 g_free( new );
1233         }
1234 #ifndef USE_LDAP
1235         /* Select the address if there is only one match */
1236         if (ncount == 2) {
1237                 /* Display selected address in entry field */           
1238                 gchar *addr = get_complete_address(1);
1239                 if (addr && !strstr(addr, " <!--___group___-->")) {
1240                         replace_address_in_edit(entry, addr, cursor_pos, FALSE, NULL);
1241                         /* Discard the window */
1242                         clear_completion_cache();
1243                 } 
1244                 g_free(addr);
1245         }
1246         /* Make sure that drop-down appears uniform! */
1247         else 
1248 #endif
1249         if( ncount == 0 ) {
1250                 addrcompl_add_queue( g_strdup( searchTerm ) );
1251         }
1252         g_free( searchTerm );
1253
1254         return TRUE;
1255 }
1256
1257 /**
1258  * Create new address completion window for specified entry.
1259  * \param entry_ Entry widget to associate with window.
1260  */
1261 static void address_completion_create_completion_window( GtkEntry *entry_ )
1262 {
1263         gint x, y, height, width, depth;
1264         GtkWidget *scroll, *list_view;
1265         GtkRequisition r;
1266         GtkWidget *window;
1267         GtkWidget *entry = GTK_WIDGET(entry_);
1268
1269         /* Create new window and list */
1270         window = gtk_window_new(GTK_WINDOW_POPUP);
1271         list_view  = addr_compl_list_view_create(_compWindow_);
1272
1273         /* Destroy any existing window */
1274         addrcompl_destroy_window( _compWindow_ );
1275
1276         /* Create new object */
1277         _compWindow_->window    = window;
1278         _compWindow_->entry     = entry;
1279         _compWindow_->list_view = list_view;
1280         _compWindow_->listCount = 0;
1281         _compWindow_->in_mouse  = FALSE;
1282
1283         scroll = gtk_scrolled_window_new(NULL, NULL);
1284         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
1285                                        GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
1286         gtk_container_add(GTK_CONTAINER(window), scroll);
1287         gtk_container_add(GTK_CONTAINER(scroll), list_view);
1288         gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll),
1289                 GTK_SHADOW_OUT);
1290         /* Use entry widget to create initial window */
1291         gdk_window_get_geometry(entry->window, &x, &y, &width, &height, &depth);
1292         gdk_window_get_deskrelative_origin (entry->window, &x, &y);
1293         y += height;
1294         gtk_window_move(GTK_WINDOW(window), x, y);
1295
1296         /* Resize window to fit initial (empty) address list */
1297         gtk_widget_size_request( list_view, &r );
1298         gtk_widget_set_size_request( window, width, r.height );
1299         gtk_widget_show_all( window );
1300         gtk_widget_size_request( list_view, &r );
1301
1302         /* Setup handlers */
1303         g_signal_connect(G_OBJECT(list_view), "button_press_event",
1304                          G_CALLBACK(list_view_button_press),
1305                          _compWindow_);
1306                          
1307         g_signal_connect(G_OBJECT(list_view), "button_release_event",
1308                          G_CALLBACK(list_view_button_release),
1309                          _compWindow_);
1310         
1311         g_signal_connect(G_OBJECT(window),
1312                          "button-press-event",
1313                          G_CALLBACK(completion_window_button_press),
1314                          _compWindow_ );
1315         g_signal_connect(G_OBJECT(window),
1316                          "key-press-event",
1317                          G_CALLBACK(completion_window_key_press),
1318                          _compWindow_ );
1319         gdk_pointer_grab(window->window, TRUE,
1320                          GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK |
1321                          GDK_BUTTON_RELEASE_MASK,
1322                          NULL, NULL, GDK_CURRENT_TIME);
1323         gtk_grab_add( window );
1324
1325         /* XXX: GTK2 too??? 
1326          *
1327          * GTK1: this gets rid of the irritating focus rectangle that doesn't
1328          * follow the selection */
1329         GTK_WIDGET_UNSET_FLAGS(list_view, GTK_CAN_FOCUS);
1330 }
1331
1332 /**
1333  * Respond to button press in completion window. Check if mouse click is
1334  * anywhere outside the completion window. In that case the completion
1335  * window is destroyed, and the original searchTerm is restored.
1336  *
1337  * \param widget   Window object.
1338  * \param event    Event.
1339  * \param compWin  Reference to completion window.
1340  */
1341 static gboolean completion_window_button_press(GtkWidget *widget,
1342                                                GdkEventButton *event,
1343                                                CompletionWindow *compWin )
1344 {
1345         GtkWidget *event_widget, *entry;
1346         gchar *searchTerm;
1347         gint cursor_pos;
1348         gboolean restore = TRUE;
1349
1350         g_return_val_if_fail(compWin != NULL, FALSE);
1351
1352         entry = compWin->entry;
1353         g_return_val_if_fail(entry != NULL, FALSE);
1354
1355         /* Test where mouse was clicked */
1356         event_widget = gtk_get_event_widget((GdkEvent *)event);
1357         if (event_widget != widget) {
1358                 while (event_widget) {
1359                         if (event_widget == widget)
1360                                 return FALSE;
1361                         else if (event_widget == entry) {
1362                                 restore = FALSE;
1363                                 break;
1364                         }
1365                         event_widget = event_widget->parent;
1366                 }
1367         }
1368
1369         if (restore) {
1370                 /* Clicked outside of completion window - restore */
1371                 searchTerm = _compWindow_->searchTerm;
1372                 g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1373                 replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos, FALSE, NULL);
1374         }
1375
1376         clear_completion_cache();
1377         addrcompl_destroy_window( _compWindow_ );
1378
1379         return TRUE;
1380 }
1381
1382 /**
1383  * Respond to key press in completion window.
1384  * \param widget   Window object.
1385  * \param event    Event.
1386  * \param compWind Reference to completion window.
1387  */
1388 static gboolean completion_window_key_press(GtkWidget *widget,
1389                                             GdkEventKey *event,
1390                                             CompletionWindow *compWin )
1391 {
1392         GdkEventKey tmp_event;
1393         GtkWidget *entry;
1394         gchar *searchTerm;
1395         gint cursor_pos;
1396         GtkWidget *list_view;
1397         GtkWidget *parent;
1398
1399         g_return_val_if_fail(compWin != NULL, FALSE);
1400
1401         entry = compWin->entry;
1402         list_view = compWin->list_view;
1403         g_return_val_if_fail(entry != NULL, FALSE);
1404
1405         /* allow keyboard navigation in the alternatives tree view */
1406         if (event->keyval == GDK_Up || event->keyval == GDK_Down ||
1407             event->keyval == GDK_Page_Up || event->keyval == GDK_Page_Down) {
1408                 completion_window_advance_selection
1409                         (GTK_TREE_VIEW(list_view),
1410                          event->keyval == GDK_Down ||
1411                          event->keyval == GDK_Page_Down ? TRUE : FALSE);
1412                 return FALSE;
1413         }               
1414
1415         /* make tab move to next field */
1416         if( event->keyval == GDK_Tab ) {
1417                 /* Reference to parent */
1418                 parent = GTK_WIDGET(entry)->parent;
1419
1420                 /* Discard the window */
1421                 clear_completion_cache();
1422                 addrcompl_destroy_window( _compWindow_ );
1423
1424                 /* Move focus to next widget */
1425                 if( parent ) {
1426                         gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1427                 }
1428                 return FALSE;
1429         }
1430
1431         /* make backtab move to previous field */
1432         if( event->keyval == GDK_ISO_Left_Tab ) {
1433                 /* Reference to parent */
1434                 parent = GTK_WIDGET(entry)->parent;
1435
1436                 /* Discard the window */
1437                 clear_completion_cache();
1438                 addrcompl_destroy_window( _compWindow_ );
1439
1440                 /* Move focus to previous widget */
1441                 if( parent ) {
1442                         gtk_widget_child_focus( parent, GTK_DIR_TAB_BACKWARD );
1443                 }
1444                 return FALSE;
1445         }
1446
1447         /* look for presses that accept the selection */
1448         if (event->keyval == GDK_Return || event->keyval == GDK_space) {
1449                 /* User selected address with a key press */
1450
1451                 /* Display selected address in entry field */           
1452                 completion_window_apply_selection(
1453                         GTK_TREE_VIEW(list_view), GTK_ENTRY(entry) );
1454
1455                 /* Discard the window */
1456                 clear_completion_cache();
1457                 addrcompl_destroy_window( _compWindow_ );
1458                 return FALSE;
1459         }
1460
1461         /* key state keys should never be handled */
1462         if (event->keyval == GDK_Shift_L
1463                  || event->keyval == GDK_Shift_R
1464                  || event->keyval == GDK_Control_L
1465                  || event->keyval == GDK_Control_R
1466                  || event->keyval == GDK_Caps_Lock
1467                  || event->keyval == GDK_Shift_Lock
1468                  || event->keyval == GDK_Meta_L
1469                  || event->keyval == GDK_Meta_R
1470                  || event->keyval == GDK_Alt_L
1471                  || event->keyval == GDK_Alt_R) {
1472                 return FALSE;
1473         }
1474
1475         /* some other key, let's restore the searchTerm (orignal text) */
1476         searchTerm = _compWindow_->searchTerm;
1477         g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1478         replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos, FALSE, NULL);
1479
1480         /* make sure anything we typed comes in the edit box */
1481         tmp_event.type       = event->type;
1482         tmp_event.window     = entry->window;
1483         tmp_event.send_event = TRUE;
1484         tmp_event.time       = event->time;
1485         tmp_event.state      = event->state;
1486         tmp_event.keyval     = event->keyval;
1487         tmp_event.length     = event->length;
1488         tmp_event.string     = event->string;
1489         gtk_widget_event(entry, (GdkEvent *)&tmp_event);
1490
1491         /* and close the completion window */
1492         clear_completion_cache();
1493         addrcompl_destroy_window( _compWindow_ );
1494
1495         return TRUE;
1496 }
1497
1498 /*
1499  * ============================================================================
1500  * Publically accessible functions.
1501  * ============================================================================
1502  */
1503
1504 /**
1505  * Setup completion object.
1506  */
1507 void addrcompl_initialize( void ) {
1508         /* printf( "addrcompl_initialize...\n" ); */
1509         if( ! _compWindow_ ) {
1510                 _compWindow_ = addrcompl_create_window();
1511         }
1512         _queryID_ = 0;
1513         _completionIdleID_ = 0;
1514         /* printf( "addrcompl_initialize...done\n" ); */
1515 }
1516
1517 /**
1518  * Teardown completion object.
1519  */
1520 void addrcompl_teardown( void ) {
1521         /* printf( "addrcompl_teardown...\n" ); */
1522         addrcompl_free_window( _compWindow_ );
1523         _compWindow_ = NULL;
1524         if( _displayQueue_ ) {
1525                 g_list_free( _displayQueue_ );
1526         }
1527         _displayQueue_ = NULL;
1528         _completionIdleID_ = 0;
1529         /* printf( "addrcompl_teardown...done\n" ); */
1530 }
1531
1532 /*
1533  * tree view functions
1534  */
1535
1536 static GtkListStore *addr_compl_create_store(void)
1537 {
1538         return gtk_list_store_new(N_ADDR_COMPL_COLUMNS,
1539                                   GDK_TYPE_PIXBUF,
1540                                   G_TYPE_STRING,
1541                                   G_TYPE_BOOLEAN,
1542                                   G_TYPE_POINTER,
1543                                   -1);
1544 }
1545                                              
1546 static GtkWidget *addr_compl_list_view_create(CompletionWindow *window)
1547 {
1548         GtkTreeView *list_view;
1549         GtkTreeSelection *selector;
1550         GtkTreeModel *model;
1551
1552         model = GTK_TREE_MODEL(addr_compl_create_store());
1553         list_view = GTK_TREE_VIEW(gtk_tree_view_new_with_model(model));
1554         g_object_unref(model);  
1555         
1556         gtk_tree_view_set_rules_hint(list_view, prefs_common.use_stripes_everywhere);
1557         gtk_tree_view_set_headers_visible(list_view, FALSE);
1558         
1559         selector = gtk_tree_view_get_selection(list_view);
1560         gtk_tree_selection_set_mode(selector, GTK_SELECTION_BROWSE);
1561         gtk_tree_selection_set_select_function(selector, addr_compl_selected,
1562                                                window, NULL);
1563
1564         /* create the columns */
1565         addr_compl_create_list_view_columns(GTK_WIDGET(list_view));
1566
1567         return GTK_WIDGET(list_view);
1568 }
1569
1570 static void addr_compl_create_list_view_columns(GtkWidget *list_view)
1571 {
1572         GtkTreeViewColumn *column;
1573         GtkCellRenderer *renderer;
1574
1575         renderer = gtk_cell_renderer_pixbuf_new();
1576         column = gtk_tree_view_column_new_with_attributes
1577                 ("", renderer,
1578                  "pixbuf", ADDR_COMPL_ICON, NULL);
1579         gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);          
1580         renderer = gtk_cell_renderer_text_new();
1581         column = gtk_tree_view_column_new_with_attributes
1582                 ("", renderer, "text", ADDR_COMPL_ADDRESS, NULL);
1583         gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);          
1584 }
1585
1586 static gboolean list_view_button_press(GtkWidget *widget, GdkEventButton *event,
1587                                        CompletionWindow *window)
1588 {
1589         if (window && event && event->type == GDK_BUTTON_PRESS) {
1590                 window->in_mouse = TRUE;
1591         }
1592         return FALSE;
1593 }
1594
1595 static gboolean list_view_button_release(GtkWidget *widget, GdkEventButton *event,
1596                                          CompletionWindow *window)
1597 {
1598         if (window && event && event->type == GDK_BUTTON_RELEASE) {
1599                 window->in_mouse = FALSE;
1600         }
1601         return FALSE;
1602 }
1603
1604 static gboolean addr_compl_selected(GtkTreeSelection *selector,
1605                                     GtkTreeModel *model, 
1606                                     GtkTreePath *path,
1607                                     gboolean currently_selected,
1608                                     gpointer data)
1609 {
1610         CompletionWindow *window = data;
1611
1612         if (currently_selected)
1613                 return TRUE;
1614         
1615         if (!window->in_mouse)
1616                 return TRUE;
1617
1618         /* XXX: select the entry and kill window later... select is called before
1619          * any other mouse events handlers including the tree view internal one;
1620          * not using a time out would result in a crash. if this doesn't work
1621          * safely, maybe we should set variables when receiving button presses
1622          * in the tree view. */
1623         if (!window->destroying) {       
1624                 window->destroying = TRUE;       
1625                 g_idle_add((GSourceFunc) addr_compl_defer_select_destruct, data);
1626         }               
1627         
1628         return TRUE;
1629 }
1630
1631 static gboolean addr_compl_defer_select_destruct(CompletionWindow *window)
1632 {
1633         GtkEntry *entry = GTK_ENTRY(window->entry);
1634
1635         completion_window_apply_selection(GTK_TREE_VIEW(window->list_view), 
1636                                           entry);
1637
1638         clear_completion_cache();
1639
1640         addrcompl_destroy_window(window);
1641         return FALSE;
1642 }
1643
1644
1645 /*
1646  * End of Source.
1647  */
1648