2007-03-20 [colin] 2.8.1cvs26
[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         if (_groupAddresses_)
200                 g_hash_table_destroy(_groupAddresses_);
201         _groupAddresses_ = NULL;
202 }
203
204 static void clear_completion_cache(void);
205 static void free_completion_list(void)
206 {
207         GList *walk;
208         if (!g_completion_list)
209                 return;
210         
211         clear_completion_cache();
212         if (g_completion)
213                 g_completion_clear_items(g_completion);
214
215         walk = g_list_first(g_completion_list);
216         for (; walk != NULL; walk = g_list_next(walk)) {
217                 completion_entry *ce = (completion_entry *) walk->data;
218                 g_free(ce->string);
219                 g_free(walk->data);
220         }
221         g_list_free(g_completion_list);
222         g_completion_list = NULL;
223 }
224 /**
225  * Free up all completion index data.
226  */
227 static void free_all(void)
228 {
229         free_completion_list(); 
230         free_all_addresses();   
231         g_completion_free(g_completion);
232         g_completion = 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  * complete_matches_found() returns the number of matched addresses according
550  * to the completion mechanism. Unlike complete_address(), the returned value
551  * doesn't count str itself. If there's no match, it returns 0.
552  * To get a list of completion matches, see complete_address() instead.
553  */
554 guint complete_matches_found(const gchar *str)
555 {
556         GList *result = NULL;
557         gchar *d = NULL;
558
559         g_return_val_if_fail(str != NULL, 0);
560
561         /* g_completion is case sensitive */
562         d = g_utf8_strdown(str, -1);
563
564         clear_completion_cache();
565         g_completion_prefix = g_strdup(str);
566
567         result = g_completion_complete(g_completion, d, NULL);
568
569         g_free(g_completion_prefix);
570         g_free(d);
571
572         return g_list_length(result);
573 }
574
575 /**
576  * Return a complete address from the index.
577  * \param index Index of entry that was found (by the previous call to
578  *              <code>complete_address()</code>
579  * \return Completed address string; this should be freed when done.
580  */
581 gchar *get_complete_address(gint index)
582 {
583         const address_entry *p;
584         gchar *address = NULL;
585
586         if (index < g_completion_count) {
587                 if (index == 0)
588                         address = g_strdup(g_completion_prefix);
589                 else {
590                         /* get something from the unique addresses */
591                         p = (address_entry *)g_slist_nth_data
592                                 (g_completion_addresses, index - 1);
593                         if (p != NULL && p->address != NULL) {
594                                 address = get_complete_address_from_name_email(p->name, p->address);
595                         } else if (p != NULL && p->address == NULL && p->name != NULL) {
596                                 /* that's a group */
597                                 address = g_strdup_printf("%s (%s) <!--___group___-->", p->name, _("Group"));
598                                 if (!_groupAddresses_) {
599                                         _groupAddresses_ = g_hash_table_new(NULL, g_direct_equal);
600                                 }
601                                 if (!g_hash_table_lookup(_groupAddresses_, GINT_TO_POINTER(g_str_hash(address)))) {
602                                         g_hash_table_insert(_groupAddresses_, GINT_TO_POINTER(g_str_hash(address)), p->grp_emails);
603
604                                 }
605                         }
606                 }
607         }
608
609         return address;
610 }
611
612 /**
613  * Return the next complete address match from the completion index.
614  * \return Completed address string; this should be freed when done.
615  */
616 static gchar *get_next_complete_address(void)
617 {
618         if (is_completion_pending()) {
619                 gchar *res;
620
621                 res = get_complete_address(g_completion_next);
622                 g_completion_next += 1;
623                 if (g_completion_next >= g_completion_count)
624                         g_completion_next = 0;
625
626                 return res;
627         } else
628                 return NULL;
629 }
630
631 /**
632  * Return a count of the completed matches in the completion index.
633  * \return Number of matched entries.
634  */
635 static guint get_completion_count(void)
636 {
637         if (is_completion_pending())
638                 return g_completion_count;
639         else
640                 return 0;
641 }
642
643 /**
644  * Invalidate address completion index. This function should be called whenever
645  * the address book changes. This forces data to be read into the completion
646  * data.
647  * \return Number of entries in index.
648  */
649 gint invalidate_address_completion(void)
650 {
651         if (g_ref_count) {
652                 /* simply the same as start_address_completion() */
653                 debug_print("Invalidation request for address completion\n");
654                 read_address_book(completion_folder_path);
655                 clear_completion_cache();
656         }
657
658         return g_list_length(g_completion_list);
659 }
660
661 /**
662  * Finished with completion index. This function should be called after
663  * matching addresses.
664  * \return Reference count.
665  */
666 gint end_address_completion(void)
667 {
668         gboolean different_folder = FALSE;
669         clear_completion_cache();
670
671         /* reset the folderpath to NULL */
672         if (completion_folder_path) {
673                 g_free(completion_folder_path);
674                 completion_folder_path = NULL;
675                 different_folder = TRUE;
676         }
677         if (0 == --g_ref_count)
678                 free_all();
679
680         debug_print("end_address_completion ref count %d\n", g_ref_count);
681         if (g_ref_count && different_folder) {
682                 debug_print("still ref'd, different folder\n");
683                 invalidate_address_completion();
684         }
685
686         return g_ref_count; 
687 }
688
689 /**
690  * Completion window.
691  */
692 static CompletionWindow *_compWindow_ = NULL;
693
694 /**
695  * Mutex to protect callback from multiple threads.
696  */
697 static pthread_mutex_t _completionMutex_ = PTHREAD_MUTEX_INITIALIZER;
698
699 /**
700  * Completion queue list.
701  */
702 static GList *_displayQueue_ = NULL;
703 /**
704  * Current query ID.
705  */
706 static gint _queryID_ = 0;
707
708 /**
709  * Completion idle ID.
710  */
711 static guint _completionIdleID_ = 0;
712
713 /*
714  * address completion entry ui. the ui (completion list was inspired by galeon's
715  * auto completion list). remaining things powered by claws's completion engine.
716  */
717
718 #define ENTRY_DATA_TAB_HOOK     "tab_hook"      /* used to lookup entry */
719 #define ENTRY_DATA_ALLOW_COMMAS "allowcommas"   /* used to know whether to present groups */
720
721 static void address_completion_mainwindow_set_focus     (GtkWindow   *window,
722                                                          GtkWidget   *widget,
723                                                          gpointer     data);
724 static gboolean address_completion_entry_key_pressed    (GtkEntry    *entry,
725                                                          GdkEventKey *ev,
726                                                          gpointer     data);
727 static gboolean address_completion_complete_address_in_entry
728                                                         (GtkEntry    *entry,
729                                                          gboolean     next);
730 static void address_completion_create_completion_window (GtkEntry    *entry);
731
732 static gboolean completion_window_button_press
733                                         (GtkWidget       *widget,
734                                          GdkEventButton  *event,
735                                          CompletionWindow *compWin );
736
737 static gboolean completion_window_key_press
738                                         (GtkWidget       *widget,
739                                          GdkEventKey     *event,
740                                          CompletionWindow *compWin );
741 static void address_completion_create_completion_window( GtkEntry *entry_ );
742
743 /**
744  * Create a completion window object.
745  * \return Initialized completion window.
746  */
747 static CompletionWindow *addrcompl_create_window( void ) {
748         CompletionWindow *cw;
749
750         cw = g_new0( CompletionWindow, 1 );
751         cw->listCount = 0;
752         cw->searchTerm = NULL;
753         cw->window = NULL;
754         cw->entry = NULL;
755         cw->list_view = NULL;
756         cw->in_mouse = FALSE;
757         cw->destroying = FALSE;
758
759         return cw;      
760 }
761
762 /**
763  * Destroy completion window.
764  * \param cw Window to destroy.
765  */
766 static void addrcompl_destroy_window( CompletionWindow *cw ) {
767         /* Stop all searches currently in progress */
768         addrindex_stop_search( _queryID_ );
769
770         /* Remove idler function... or application may not terminate */
771         if( _completionIdleID_ != 0 ) {
772                 g_source_remove( _completionIdleID_ );
773                 _completionIdleID_ = 0;
774         }
775
776         /* Now destroy window */        
777         if( cw ) {
778                 /* Clear references to widgets */
779                 cw->entry = NULL;
780                 cw->list_view = NULL;
781
782                 /* Free objects */
783                 if( cw->window ) {
784                         gtk_widget_hide( cw->window );
785                         gtk_widget_destroy( cw->window );
786                 }
787                 cw->window = NULL;
788                 cw->destroying = FALSE;
789                 cw->in_mouse = FALSE;
790         }
791         
792 }
793
794 /**
795  * Free up completion window.
796  * \param cw Window to free.
797  */
798 static void addrcompl_free_window( CompletionWindow *cw ) {
799         if( cw ) {
800                 addrcompl_destroy_window( cw );
801
802                 g_free( cw->searchTerm );
803                 cw->searchTerm = NULL;
804
805                 /* Clear references */          
806                 cw->listCount = 0;
807
808                 /* Free object */               
809                 g_free( cw );
810         }
811 }
812
813 /**
814  * Advance selection to previous/next item in list.
815  * \param list_view List to process.
816  * \param forward Set to <i>TRUE</i> to select next or <i>FALSE</i> for
817  *                previous entry.
818  */
819 static void completion_window_advance_selection(GtkTreeView *list_view, gboolean forward)
820 {
821         GtkTreeSelection *selection;
822         GtkTreeIter iter;
823         GtkTreeModel *model;
824
825         g_return_if_fail(list_view != NULL);
826
827         selection = gtk_tree_view_get_selection(list_view);
828         if (!gtk_tree_selection_get_selected(selection, &model, &iter))
829                 return;
830
831         if (forward) { 
832                 forward = gtk_tree_model_iter_next(model, &iter);
833                 if (forward) 
834                         gtk_tree_selection_select_iter(selection, &iter);
835         } else {
836                 GtkTreePath *prev;
837
838                 prev = gtk_tree_model_get_path(model, &iter);
839                 if (!prev) 
840                         return;
841
842                 if (gtk_tree_path_prev(prev))
843                         gtk_tree_selection_select_path(selection, prev);
844                 
845                 gtk_tree_path_free(prev);
846         }
847 }
848
849 /**
850  * Resize window to accommodate maximum number of address entries.
851  * \param cw Completion window.
852  */
853 static void addrcompl_resize_window( CompletionWindow *cw ) {
854         GtkRequisition r;
855         gint x, y, width, height, depth;
856
857         /* Get current geometry of window */
858         gdk_window_get_geometry( cw->window->window, &x, &y, &width, &height, &depth );
859
860         gtk_widget_hide_all( cw->window );
861         gtk_widget_show_all( cw->window );
862         gtk_widget_size_request( cw->list_view, &r );
863
864         /* Adjust window height to available screen space */
865         if( ( y + r.height ) > gdk_screen_height() ) {
866                 gtk_window_set_resizable(GTK_WINDOW(cw->window), FALSE);
867                 gtk_widget_set_size_request( cw->window, width, gdk_screen_height() - y );
868         } else
869                 gtk_widget_set_size_request(cw->window, width, r.height);
870 }
871
872 static GdkPixbuf *group_pixbuf = NULL;
873 static GdkPixbuf *email_pixbuf = NULL;
874
875 /**
876  * Add an address the completion window address list.
877  * \param cw      Completion window.
878  * \param address Address to add.
879  */
880 static void addrcompl_add_entry( CompletionWindow *cw, gchar *address ) {
881         GtkListStore *store;
882         GtkTreeIter iter;
883         GtkTreeSelection *selection;
884         gboolean is_group = FALSE;
885         GList *grp_emails = NULL;
886         store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(cw->list_view)));
887         GdkPixbuf *pixbuf;
888         
889         if (!group_pixbuf) {
890                 stock_pixbuf_gdk(cw->list_view, STOCK_PIXMAP_ADDR_TWO, &group_pixbuf);
891                 g_object_ref(G_OBJECT(group_pixbuf));
892         }
893         if (!email_pixbuf) {
894                 stock_pixbuf_gdk(cw->list_view, STOCK_PIXMAP_ADDR_ONE, &email_pixbuf);
895                 g_object_ref(G_OBJECT(email_pixbuf));
896         }
897         /* printf( "\t\tAdding :%s\n", address ); */
898         if (strstr(address, " <!--___group___-->")) {
899                 is_group = TRUE;
900                 if (_groupAddresses_)
901                         grp_emails = g_hash_table_lookup(_groupAddresses_, GINT_TO_POINTER(g_str_hash(address)));
902                 *(strstr(address, " <!--___group___-->")) = '\0';
903                 pixbuf = group_pixbuf;
904         } else if (strchr(address, '@') && strchr(address, '<') &&
905                    strchr(address, '>')) {
906                 pixbuf = email_pixbuf;
907         } else
908                 pixbuf = NULL;
909         
910         if (is_group && !_allowCommas_)
911                 return;
912         gtk_list_store_append(store, &iter);
913         gtk_list_store_set(store, &iter, 
914                                 ADDR_COMPL_ICON, pixbuf,
915                                 ADDR_COMPL_ADDRESS, address, 
916                                 ADDR_COMPL_ISGROUP, is_group, 
917                                 ADDR_COMPL_GROUPLIST, grp_emails,
918                                 -1);
919         cw->listCount++;
920
921         /* Resize window */
922         addrcompl_resize_window( cw );
923         gtk_grab_add( cw->window );
924
925         selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(cw->list_view));
926         gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store), &iter);
927
928         if( cw->listCount == 1 ) {
929                 /* Select first row for now */
930                 gtk_tree_selection_select_iter(selection, &iter);
931         }
932         else if( cw->listCount == 2 ) {
933                 gtk_tree_model_iter_next(GTK_TREE_MODEL(store), &iter);
934                 /* Move off first row */
935                 gtk_tree_selection_select_iter(selection, &iter);
936         }
937 }
938
939 /**
940  * Completion idle function. This function is called by the main (UI) thread
941  * during UI idle time while an address search is in progress. Items from the
942  * display queue are processed and appended to the address list.
943  *
944  * \param data Target completion window to receive email addresses.
945  * \return <i>TRUE</i> to ensure that idle event do not get ignored.
946  */
947 static gboolean addrcompl_idle( gpointer data ) {
948         GList *node;
949         gchar *address;
950
951         /* Process all entries in display queue */
952         pthread_mutex_lock( & _completionMutex_ );
953         if( _displayQueue_ ) {
954                 node = _displayQueue_;
955                 while( node ) {
956                         address = node->data;
957                         /* printf( "address ::: %s :::\n", address ); */
958                         addrcompl_add_entry( _compWindow_, address );
959                         g_free( address );
960                         node = g_list_next( node );
961                 }
962                 g_list_free( _displayQueue_ );
963                 _displayQueue_ = NULL;
964         }
965         pthread_mutex_unlock( & _completionMutex_ );
966         claws_do_idle();
967
968         return TRUE;
969 }
970
971 /**
972  * Callback entry point. The background thread (if any) appends the address
973  * list to the display queue.
974  * \param sender     Sender of query.
975  * \param queryID    Query ID of search request.
976  * \param listEMail  List of zero of more email objects that met search
977  *                   criteria.
978  * \param data       Query data.
979  */
980 static gint addrcompl_callback_entry(
981         gpointer sender, gint queryID, GList *listEMail, gpointer data )
982 {
983         GList *node;
984         gchar *address;
985
986         /* printf( "addrcompl_callback_entry::queryID=%d\n", queryID ); */
987         pthread_mutex_lock( & _completionMutex_ );
988         if( queryID == _queryID_ ) {
989                 /* Append contents to end of display queue */
990                 node = listEMail;
991                 while( node ) {
992                         ItemEMail *email = node->data;
993
994                         address = addritem_format_email( email );
995                         /* printf( "\temail/address ::%s::\n", address ); */
996                         _displayQueue_ = g_list_append( _displayQueue_, address );
997                         node = g_list_next( node );
998                 }
999         }
1000         g_list_free( listEMail );
1001         pthread_mutex_unlock( & _completionMutex_ );
1002
1003         return 0;
1004 }
1005
1006 /**
1007  * Clear the display queue.
1008  */
1009 static void addrcompl_clear_queue( void ) {
1010         /* Clear out display queue */
1011         pthread_mutex_lock( & _completionMutex_ );
1012
1013         g_list_free( _displayQueue_ );
1014         _displayQueue_ = NULL;
1015
1016         pthread_mutex_unlock( & _completionMutex_ );
1017 }
1018
1019 /**
1020  * Add a single address entry into the display queue.
1021  * \param address Address to append.
1022  */
1023 static void addrcompl_add_queue( gchar *address ) {
1024         pthread_mutex_lock( & _completionMutex_ );
1025         _displayQueue_ = g_list_append( _displayQueue_, address );
1026         pthread_mutex_unlock( & _completionMutex_ );
1027 }
1028
1029 /**
1030  * Load list with entries from local completion index.
1031  */
1032 static void addrcompl_load_local( void ) {
1033         guint count = 0;
1034
1035         for (count = 0; count < get_completion_count(); count++) {
1036                 gchar *address;
1037
1038                 address = get_complete_address( count );
1039                 /* printf( "\taddress ::%s::\n", address ); */
1040
1041                 /* Append contents to end of display queue */
1042                 addrcompl_add_queue( address );
1043         }
1044 }
1045
1046 /**
1047  * Start the search.
1048  */
1049 static void addrcompl_start_search( void ) {
1050         gchar *searchTerm;
1051
1052         searchTerm = g_strdup( _compWindow_->searchTerm );
1053
1054         /* Setup the search */
1055         _queryID_ = addrindex_setup_search(
1056                 searchTerm, NULL, addrcompl_callback_entry );
1057         g_free( searchTerm );
1058         /* printf( "addrcompl_start_search::queryID=%d\n", _queryID_ ); */
1059
1060         /* Load local stuff */
1061         addrcompl_load_local();
1062
1063         /* Sit back and wait until something happens */
1064         _completionIdleID_ =
1065                 g_idle_add( ( GtkFunction ) addrcompl_idle, NULL );
1066         /* printf( "addrindex_start_search::queryID=%d\n", _queryID_ ); */
1067
1068         addrindex_start_search( _queryID_ );
1069 }
1070
1071 /**
1072  * Apply the current selection in the list to the entry field. Focus is also
1073  * moved to the next widget so that Tab key works correctly.
1074  * \param list_view List to process.
1075  * \param entry Address entry field.
1076  * \param move_focus Move focus to the next widget ?
1077  */
1078 static void completion_window_apply_selection(GtkTreeView *list_view,
1079                                                 GtkEntry *entry,
1080                                                 gboolean move_focus)
1081 {
1082         gchar *address = NULL, *text = NULL;
1083         gint   cursor_pos;
1084         GtkWidget *parent;
1085         GtkTreeSelection *selection;
1086         GtkTreeModel *model;
1087         GtkTreeIter iter;
1088         gboolean is_group = FALSE;
1089         g_return_if_fail(list_view != NULL);
1090         g_return_if_fail(entry != NULL);
1091         GList *grp_emails = NULL;
1092
1093         selection = gtk_tree_view_get_selection(list_view);
1094         if (! gtk_tree_selection_get_selected(selection, &model, &iter))
1095                 return;
1096
1097         /* First remove the idler */
1098         if( _completionIdleID_ != 0 ) {
1099                 g_source_remove( _completionIdleID_ );
1100                 _completionIdleID_ = 0;
1101         }
1102
1103         /* Process selected item */
1104         gtk_tree_model_get(model, &iter, ADDR_COMPL_ADDRESS, &text, 
1105                                 ADDR_COMPL_ISGROUP, &is_group, 
1106                                 ADDR_COMPL_GROUPLIST, &grp_emails,
1107                                 -1);
1108
1109         address = get_address_from_edit(entry, &cursor_pos);
1110         g_free(address);
1111         replace_address_in_edit(entry, text, cursor_pos, is_group, grp_emails);
1112         g_free(text);
1113
1114         /* Move focus to next widget */
1115         parent = GTK_WIDGET(entry)->parent;
1116         if( parent && move_focus) {
1117                 gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1118         }
1119 }
1120
1121 /**
1122  * Start address completion. Should be called when creating the main window
1123  * containing address completion entries.
1124  * \param mainwindow Main window.
1125  */
1126 void address_completion_start(GtkWidget *mainwindow)
1127 {
1128         start_address_completion(NULL);
1129
1130         /* register focus change hook */
1131         g_signal_connect(G_OBJECT(mainwindow), "set_focus",
1132                          G_CALLBACK(address_completion_mainwindow_set_focus),
1133                          mainwindow);
1134 }
1135
1136 /**
1137  * Need unique data to make unregistering signal handler possible for the auto
1138  * completed entry.
1139  */
1140 #define COMPLETION_UNIQUE_DATA (GINT_TO_POINTER(0xfeefaa))
1141
1142 /**
1143  * Register specified entry widget for address completion.
1144  * \param entry Address entry field.
1145  */
1146 void address_completion_register_entry(GtkEntry *entry, gboolean allow_commas)
1147 {
1148         g_return_if_fail(entry != NULL);
1149         g_return_if_fail(GTK_IS_ENTRY(entry));
1150
1151         /* add hooked property */
1152         g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, entry);
1153         g_object_set_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS, GINT_TO_POINTER(allow_commas));
1154
1155         /* add keypress event */
1156         g_signal_connect_closure
1157                 (G_OBJECT(entry), "key_press_event",
1158                  g_cclosure_new(G_CALLBACK(address_completion_entry_key_pressed),
1159                                 COMPLETION_UNIQUE_DATA,
1160                                 NULL),
1161                  FALSE); /* magic */
1162 }
1163
1164 /**
1165  * Unregister specified entry widget from address completion operations.
1166  * \param entry Address entry field.
1167  */
1168 void address_completion_unregister_entry(GtkEntry *entry)
1169 {
1170         GtkObject *entry_obj;
1171
1172         g_return_if_fail(entry != NULL);
1173         g_return_if_fail(GTK_IS_ENTRY(entry));
1174
1175         entry_obj = g_object_get_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK);
1176         g_return_if_fail(entry_obj);
1177         g_return_if_fail(G_OBJECT(entry_obj) == G_OBJECT(entry));
1178
1179         /* has the hooked property? */
1180         g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, NULL);
1181
1182         /* remove the hook */
1183         g_signal_handlers_disconnect_by_func(G_OBJECT(entry), 
1184                         G_CALLBACK(address_completion_entry_key_pressed),
1185                         COMPLETION_UNIQUE_DATA);
1186 }
1187
1188 /**
1189  * End address completion. Should be called when main window with address
1190  * completion entries terminates. NOTE: this function assumes that it is
1191  * called upon destruction of the window.
1192  * \param mainwindow Main window.
1193  */
1194 void address_completion_end(GtkWidget *mainwindow)
1195 {
1196         /* if address_completion_end() is really called on closing the window,
1197          * we don't need to unregister the set_focus_cb */
1198         end_address_completion();
1199 }
1200
1201 /* if focus changes to another entry, then clear completion cache */
1202 static void address_completion_mainwindow_set_focus(GtkWindow *window,
1203                                                     GtkWidget *widget,
1204                                                     gpointer   data)
1205 {
1206         
1207         if (widget && GTK_IS_ENTRY(widget) &&
1208             g_object_get_data(G_OBJECT(widget), ENTRY_DATA_TAB_HOOK)) {
1209                 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), ENTRY_DATA_ALLOW_COMMAS));
1210                 clear_completion_cache();
1211         }
1212 }
1213
1214 /**
1215  * Listener that watches for tab or other keystroke in address entry field.
1216  * \param entry Address entry field.
1217  * \param ev    Event object.
1218  * \param data  User data.
1219  * \return <i>TRUE</i>.
1220  */
1221 static gboolean address_completion_entry_key_pressed(GtkEntry    *entry,
1222                                                      GdkEventKey *ev,
1223                                                      gpointer     data)
1224 {
1225         if (ev->keyval == GDK_Tab) {
1226                 addrcompl_clear_queue();
1227                 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS));
1228                 if( address_completion_complete_address_in_entry( entry, TRUE ) ) {
1229                         /* route a void character to the default handler */
1230                         /* this is a dirty hack; we're actually changing a key
1231                          * reported by the system. */
1232                         ev->keyval = GDK_AudibleBell_Enable;
1233                         ev->state &= ~GDK_SHIFT_MASK;
1234
1235                         /* Create window */                     
1236                         address_completion_create_completion_window(entry);
1237
1238                         /* Start remote queries */
1239                         addrcompl_start_search();
1240
1241                         return TRUE;
1242                 }
1243                 else {
1244                         /* old behaviour */
1245                 }
1246         } else if (ev->keyval == GDK_Shift_L
1247                 || ev->keyval == GDK_Shift_R
1248                 || ev->keyval == GDK_Control_L
1249                 || ev->keyval == GDK_Control_R
1250                 || ev->keyval == GDK_Caps_Lock
1251                 || ev->keyval == GDK_Shift_Lock
1252                 || ev->keyval == GDK_Meta_L
1253                 || ev->keyval == GDK_Meta_R
1254                 || ev->keyval == GDK_Alt_L
1255                 || ev->keyval == GDK_Alt_R) {
1256                 /* these buttons should not clear the cache... */
1257         } else
1258                 clear_completion_cache();
1259
1260         return FALSE;
1261 }
1262 /**
1263  * Initialize search term for address completion.
1264  * \param entry Address entry field.
1265  */
1266 static gboolean address_completion_complete_address_in_entry(GtkEntry *entry,
1267                                                              gboolean  next)
1268 {
1269         gint ncount, cursor_pos;
1270         gchar *searchTerm, *new = NULL;
1271
1272         g_return_val_if_fail(entry != NULL, FALSE);
1273
1274         if (!GTK_WIDGET_HAS_FOCUS(entry)) return FALSE;
1275
1276         /* get an address component from the cursor */
1277         searchTerm = get_address_from_edit( entry, &cursor_pos );
1278         if( ! searchTerm ) return FALSE;
1279         /* printf( "search for :::%s:::\n", searchTerm ); */
1280
1281         /* Clear any existing search */
1282         g_free( _compWindow_->searchTerm );
1283         _compWindow_->searchTerm = g_strdup( searchTerm );
1284
1285         /* Perform search on local completion index */
1286         ncount = complete_address( searchTerm );
1287         if( 0 < ncount ) {
1288                 new = get_next_complete_address();
1289                 g_free( new );
1290         }
1291 #ifndef USE_LDAP
1292         /* Select the address if there is only one match */
1293         if (ncount == 2) {
1294                 /* Display selected address in entry field */           
1295                 gchar *addr = get_complete_address(1);
1296                 if (addr && !strstr(addr, " <!--___group___-->")) {
1297                         replace_address_in_edit(entry, addr, cursor_pos, FALSE, NULL);
1298                         /* Discard the window */
1299                         clear_completion_cache();
1300                 } 
1301                 g_free(addr);
1302         }
1303         /* Make sure that drop-down appears uniform! */
1304         else 
1305 #endif
1306         if( ncount == 0 ) {
1307                 addrcompl_add_queue( g_strdup( searchTerm ) );
1308         }
1309         g_free( searchTerm );
1310
1311         return TRUE;
1312 }
1313
1314 /**
1315  * Create new address completion window for specified entry.
1316  * \param entry_ Entry widget to associate with window.
1317  */
1318 static void address_completion_create_completion_window( GtkEntry *entry_ )
1319 {
1320         gint x, y, height, width, depth;
1321         GtkWidget *scroll, *list_view;
1322         GtkRequisition r;
1323         GtkWidget *window;
1324         GtkWidget *entry = GTK_WIDGET(entry_);
1325
1326         /* Create new window and list */
1327         window = gtk_window_new(GTK_WINDOW_POPUP);
1328         list_view  = addr_compl_list_view_create(_compWindow_);
1329
1330         /* Destroy any existing window */
1331         addrcompl_destroy_window( _compWindow_ );
1332
1333         /* Create new object */
1334         _compWindow_->window    = window;
1335         _compWindow_->entry     = entry;
1336         _compWindow_->list_view = list_view;
1337         _compWindow_->listCount = 0;
1338         _compWindow_->in_mouse  = FALSE;
1339
1340         scroll = gtk_scrolled_window_new(NULL, NULL);
1341         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
1342                                        GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
1343         gtk_container_add(GTK_CONTAINER(window), scroll);
1344         gtk_container_add(GTK_CONTAINER(scroll), list_view);
1345         gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll),
1346                 GTK_SHADOW_OUT);
1347         /* Use entry widget to create initial window */
1348         gdk_window_get_geometry(entry->window, &x, &y, &width, &height, &depth);
1349         gdk_window_get_deskrelative_origin (entry->window, &x, &y);
1350         y += height;
1351         gtk_window_move(GTK_WINDOW(window), x, y);
1352
1353         /* Resize window to fit initial (empty) address list */
1354         gtk_widget_size_request( list_view, &r );
1355         gtk_widget_set_size_request( window, width, r.height );
1356         gtk_widget_show_all( window );
1357         gtk_widget_size_request( list_view, &r );
1358
1359         /* Setup handlers */
1360         g_signal_connect(G_OBJECT(list_view), "button_press_event",
1361                          G_CALLBACK(list_view_button_press),
1362                          _compWindow_);
1363                          
1364         g_signal_connect(G_OBJECT(list_view), "button_release_event",
1365                          G_CALLBACK(list_view_button_release),
1366                          _compWindow_);
1367         
1368         g_signal_connect(G_OBJECT(window),
1369                          "button-press-event",
1370                          G_CALLBACK(completion_window_button_press),
1371                          _compWindow_ );
1372         g_signal_connect(G_OBJECT(window),
1373                          "key-press-event",
1374                          G_CALLBACK(completion_window_key_press),
1375                          _compWindow_ );
1376         gdk_pointer_grab(window->window, TRUE,
1377                          GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK |
1378                          GDK_BUTTON_RELEASE_MASK,
1379                          NULL, NULL, GDK_CURRENT_TIME);
1380         gtk_grab_add( window );
1381
1382         /* XXX: GTK2 too??? 
1383          *
1384          * GTK1: this gets rid of the irritating focus rectangle that doesn't
1385          * follow the selection */
1386         GTK_WIDGET_UNSET_FLAGS(list_view, GTK_CAN_FOCUS);
1387 }
1388
1389 /**
1390  * Respond to button press in completion window. Check if mouse click is
1391  * anywhere outside the completion window. In that case the completion
1392  * window is destroyed, and the original searchTerm is restored.
1393  *
1394  * \param widget   Window object.
1395  * \param event    Event.
1396  * \param compWin  Reference to completion window.
1397  */
1398 static gboolean completion_window_button_press(GtkWidget *widget,
1399                                                GdkEventButton *event,
1400                                                CompletionWindow *compWin )
1401 {
1402         GtkWidget *event_widget, *entry;
1403         gchar *searchTerm;
1404         gint cursor_pos;
1405         gboolean restore = TRUE;
1406
1407         g_return_val_if_fail(compWin != NULL, FALSE);
1408
1409         entry = compWin->entry;
1410         g_return_val_if_fail(entry != NULL, FALSE);
1411
1412         /* Test where mouse was clicked */
1413         event_widget = gtk_get_event_widget((GdkEvent *)event);
1414         if (event_widget != widget) {
1415                 while (event_widget) {
1416                         if (event_widget == widget)
1417                                 return FALSE;
1418                         else if (event_widget == entry) {
1419                                 restore = FALSE;
1420                                 break;
1421                         }
1422                         event_widget = event_widget->parent;
1423                 }
1424         }
1425
1426         if (restore) {
1427                 /* Clicked outside of completion window - restore */
1428                 searchTerm = _compWindow_->searchTerm;
1429                 g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1430                 replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos, FALSE, NULL);
1431         }
1432
1433         clear_completion_cache();
1434         addrcompl_destroy_window( _compWindow_ );
1435
1436         return TRUE;
1437 }
1438
1439 /**
1440  * Respond to key press in completion window.
1441  * \param widget   Window object.
1442  * \param event    Event.
1443  * \param compWind Reference to completion window.
1444  */
1445 static gboolean completion_window_key_press(GtkWidget *widget,
1446                                             GdkEventKey *event,
1447                                             CompletionWindow *compWin )
1448 {
1449         GdkEventKey tmp_event;
1450         GtkWidget *entry;
1451         gchar *searchTerm;
1452         gint cursor_pos;
1453         GtkWidget *list_view;
1454         GtkWidget *parent;
1455         g_return_val_if_fail(compWin != NULL, FALSE);
1456
1457         entry = compWin->entry;
1458         list_view = compWin->list_view;
1459         g_return_val_if_fail(entry != NULL, FALSE);
1460
1461         /* allow keyboard navigation in the alternatives tree view */
1462         if (event->keyval == GDK_Up || event->keyval == GDK_Down ||
1463             event->keyval == GDK_Page_Up || event->keyval == GDK_Page_Down) {
1464                 completion_window_advance_selection
1465                         (GTK_TREE_VIEW(list_view),
1466                          event->keyval == GDK_Down ||
1467                          event->keyval == GDK_Page_Down ? TRUE : FALSE);
1468                 return FALSE;
1469         }               
1470
1471         /* make tab move to next field */
1472         if( event->keyval == GDK_Tab ) {
1473                 /* Reference to parent */
1474                 parent = GTK_WIDGET(entry)->parent;
1475
1476                 /* Discard the window */
1477                 clear_completion_cache();
1478                 addrcompl_destroy_window( _compWindow_ );
1479
1480                 /* Move focus to next widget */
1481                 if( parent ) {
1482                         gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1483                 }
1484                 return FALSE;
1485         }
1486
1487         /* make backtab move to previous field */
1488         if( event->keyval == GDK_ISO_Left_Tab ) {
1489                 /* Reference to parent */
1490                 parent = GTK_WIDGET(entry)->parent;
1491
1492                 /* Discard the window */
1493                 clear_completion_cache();
1494                 addrcompl_destroy_window( _compWindow_ );
1495
1496                 /* Move focus to previous widget */
1497                 if( parent ) {
1498                         gtk_widget_child_focus( parent, GTK_DIR_TAB_BACKWARD );
1499                 }
1500                 return FALSE;
1501         }
1502         _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS));
1503
1504         /* look for presses that accept the selection */
1505         if (event->keyval == GDK_Return || event->keyval == GDK_space
1506                         || (_allowCommas_ && event->keyval == GDK_comma)) {
1507                 /* User selected address with a key press */
1508
1509                 /* Display selected address in entry field */           
1510                 completion_window_apply_selection(
1511                         GTK_TREE_VIEW(list_view), GTK_ENTRY(entry),
1512                         event->keyval != GDK_comma);
1513
1514                 if (event->keyval == GDK_comma) {
1515                         gint pos = gtk_editable_get_position(GTK_EDITABLE(entry));
1516                         gtk_editable_insert_text(GTK_EDITABLE(entry), ", ", 2, &pos);
1517                         gtk_editable_set_position(GTK_EDITABLE(entry), pos + 1);
1518                 }
1519
1520                 /* Discard the window */
1521                 clear_completion_cache();
1522                 addrcompl_destroy_window( _compWindow_ );
1523                 return FALSE;
1524         }
1525
1526         /* key state keys should never be handled */
1527         if (event->keyval == GDK_Shift_L
1528                  || event->keyval == GDK_Shift_R
1529                  || event->keyval == GDK_Control_L
1530                  || event->keyval == GDK_Control_R
1531                  || event->keyval == GDK_Caps_Lock
1532                  || event->keyval == GDK_Shift_Lock
1533                  || event->keyval == GDK_Meta_L
1534                  || event->keyval == GDK_Meta_R
1535                  || event->keyval == GDK_Alt_L
1536                  || event->keyval == GDK_Alt_R) {
1537                 return FALSE;
1538         }
1539
1540         /* some other key, let's restore the searchTerm (orignal text) */
1541         searchTerm = _compWindow_->searchTerm;
1542         g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1543         replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos, FALSE, NULL);
1544
1545         /* make sure anything we typed comes in the edit box */
1546         tmp_event.type       = event->type;
1547         tmp_event.window     = entry->window;
1548         tmp_event.send_event = TRUE;
1549         tmp_event.time       = event->time;
1550         tmp_event.state      = event->state;
1551         tmp_event.keyval     = event->keyval;
1552         tmp_event.length     = event->length;
1553         tmp_event.string     = event->string;
1554         gtk_widget_event(entry, (GdkEvent *)&tmp_event);
1555
1556         /* and close the completion window */
1557         clear_completion_cache();
1558         addrcompl_destroy_window( _compWindow_ );
1559
1560         return TRUE;
1561 }
1562
1563 /*
1564  * ============================================================================
1565  * Publically accessible functions.
1566  * ============================================================================
1567  */
1568
1569 /**
1570  * Setup completion object.
1571  */
1572 void addrcompl_initialize( void ) {
1573         /* printf( "addrcompl_initialize...\n" ); */
1574         if( ! _compWindow_ ) {
1575                 _compWindow_ = addrcompl_create_window();
1576         }
1577         _queryID_ = 0;
1578         _completionIdleID_ = 0;
1579         /* printf( "addrcompl_initialize...done\n" ); */
1580 }
1581
1582 /**
1583  * Teardown completion object.
1584  */
1585 void addrcompl_teardown( void ) {
1586         /* printf( "addrcompl_teardown...\n" ); */
1587         addrcompl_free_window( _compWindow_ );
1588         _compWindow_ = NULL;
1589         if( _displayQueue_ ) {
1590                 g_list_free( _displayQueue_ );
1591         }
1592         _displayQueue_ = NULL;
1593         _completionIdleID_ = 0;
1594         /* printf( "addrcompl_teardown...done\n" ); */
1595 }
1596
1597 /*
1598  * tree view functions
1599  */
1600
1601 static GtkListStore *addr_compl_create_store(void)
1602 {
1603         return gtk_list_store_new(N_ADDR_COMPL_COLUMNS,
1604                                   GDK_TYPE_PIXBUF,
1605                                   G_TYPE_STRING,
1606                                   G_TYPE_BOOLEAN,
1607                                   G_TYPE_POINTER,
1608                                   -1);
1609 }
1610                                              
1611 static GtkWidget *addr_compl_list_view_create(CompletionWindow *window)
1612 {
1613         GtkTreeView *list_view;
1614         GtkTreeSelection *selector;
1615         GtkTreeModel *model;
1616
1617         model = GTK_TREE_MODEL(addr_compl_create_store());
1618         list_view = GTK_TREE_VIEW(gtk_tree_view_new_with_model(model));
1619         g_object_unref(model);  
1620         
1621         gtk_tree_view_set_rules_hint(list_view, prefs_common.use_stripes_everywhere);
1622         gtk_tree_view_set_headers_visible(list_view, FALSE);
1623         
1624         selector = gtk_tree_view_get_selection(list_view);
1625         gtk_tree_selection_set_mode(selector, GTK_SELECTION_BROWSE);
1626         gtk_tree_selection_set_select_function(selector, addr_compl_selected,
1627                                                window, NULL);
1628
1629         /* create the columns */
1630         addr_compl_create_list_view_columns(GTK_WIDGET(list_view));
1631
1632         return GTK_WIDGET(list_view);
1633 }
1634
1635 static void addr_compl_create_list_view_columns(GtkWidget *list_view)
1636 {
1637         GtkTreeViewColumn *column;
1638         GtkCellRenderer *renderer;
1639
1640         renderer = gtk_cell_renderer_pixbuf_new();
1641         column = gtk_tree_view_column_new_with_attributes
1642                 ("", renderer,
1643                  "pixbuf", ADDR_COMPL_ICON, NULL);
1644         gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);          
1645         renderer = gtk_cell_renderer_text_new();
1646         column = gtk_tree_view_column_new_with_attributes
1647                 ("", renderer, "text", ADDR_COMPL_ADDRESS, NULL);
1648         gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);          
1649 }
1650
1651 static gboolean list_view_button_press(GtkWidget *widget, GdkEventButton *event,
1652                                        CompletionWindow *window)
1653 {
1654         if (window && event && event->type == GDK_BUTTON_PRESS) {
1655                 window->in_mouse = TRUE;
1656         }
1657         return FALSE;
1658 }
1659
1660 static gboolean list_view_button_release(GtkWidget *widget, GdkEventButton *event,
1661                                          CompletionWindow *window)
1662 {
1663         if (window && event && event->type == GDK_BUTTON_RELEASE) {
1664                 window->in_mouse = FALSE;
1665         }
1666         return FALSE;
1667 }
1668
1669 static gboolean addr_compl_selected(GtkTreeSelection *selector,
1670                                     GtkTreeModel *model, 
1671                                     GtkTreePath *path,
1672                                     gboolean currently_selected,
1673                                     gpointer data)
1674 {
1675         CompletionWindow *window = data;
1676
1677         if (currently_selected)
1678                 return TRUE;
1679         
1680         if (!window->in_mouse)
1681                 return TRUE;
1682
1683         /* XXX: select the entry and kill window later... select is called before
1684          * any other mouse events handlers including the tree view internal one;
1685          * not using a time out would result in a crash. if this doesn't work
1686          * safely, maybe we should set variables when receiving button presses
1687          * in the tree view. */
1688         if (!window->destroying) {       
1689                 window->destroying = TRUE;       
1690                 g_idle_add((GSourceFunc) addr_compl_defer_select_destruct, data);
1691         }               
1692         
1693         return TRUE;
1694 }
1695
1696 static gboolean addr_compl_defer_select_destruct(CompletionWindow *window)
1697 {
1698         GtkEntry *entry = GTK_ENTRY(window->entry);
1699
1700         completion_window_apply_selection(GTK_TREE_VIEW(window->list_view), 
1701                                           entry, TRUE);
1702
1703         clear_completion_cache();
1704
1705         addrcompl_destroy_window(window);
1706         return FALSE;
1707 }
1708
1709
1710 /*
1711  * End of Source.
1712  */
1713