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