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