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