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