Coverity fixes
[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                 if (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         }
980 #endif
981 }
982
983 void addrcompl_reflect_prefs_pixmap_theme(void) {
984         if (group_pixbuf) {
985                 g_object_unref(G_OBJECT(group_pixbuf));
986                 group_pixbuf = NULL;
987         }
988         if (email_pixbuf) {
989                 g_object_unref(G_OBJECT(email_pixbuf));
990                 email_pixbuf = NULL;
991         }
992 }
993
994 /**
995  * Completion idle function. This function is called by the main (UI) thread
996  * during UI idle time while an address search is in progress. Items from the
997  * display queue are processed and appended to the address list.
998  *
999  * \param data Target completion window to receive email addresses.
1000  * \return <i>TRUE</i> to ensure that idle event do not get ignored.
1001  */
1002 static gboolean addrcompl_idle( gpointer data ) {
1003         GList *node;
1004         gchar *address;
1005
1006         /* Process all entries in display queue */
1007         pthread_mutex_lock( & _completionMutex_ );
1008         if( _displayQueue_ ) {
1009                 node = _displayQueue_;
1010                 while( node ) {
1011                         address = node->data;
1012                         /* g_print( "address ::: %s :::\n", address ); */
1013                         addrcompl_add_entry( _compWindow_, address );
1014                         g_free( address );
1015                         node = g_list_next( node );
1016                 }
1017                 g_list_free( _displayQueue_ );
1018                 _displayQueue_ = NULL;
1019         }
1020         pthread_mutex_unlock( & _completionMutex_ );
1021         claws_do_idle();
1022
1023         return TRUE;
1024 }
1025
1026 /**
1027  * Callback entry point. The background thread (if any) appends the address
1028  * list to the display queue.
1029  * \param sender     Sender of query.
1030  * \param queryID    Query ID of search request.
1031  * \param listEMail  List of zero of more email objects that met search
1032  *                   criteria.
1033  * \param data       Query data.
1034  */
1035 #ifndef USE_NEW_ADDRBOOK
1036 static gint addrcompl_callback_entry(
1037         gpointer sender, gint queryID, GList *listEMail, gpointer data )
1038 {
1039         GList *node;
1040         gchar *address;
1041
1042         /* g_print( "addrcompl_callback_entry::queryID=%d\n", queryID ); */
1043         pthread_mutex_lock( & _completionMutex_ );
1044         if( queryID == _queryID_ ) {
1045                 /* Append contents to end of display queue */
1046                 node = listEMail;
1047                 while( node ) {
1048                         ItemEMail *email = node->data;
1049
1050                         address = addritem_format_email( email );
1051                         /* g_print( "\temail/address ::%s::\n", address ); */
1052                         _displayQueue_ = g_list_append( _displayQueue_, address );
1053                         node = g_list_next( node );
1054                 }
1055         }
1056         g_list_free( listEMail );
1057         pthread_mutex_unlock( & _completionMutex_ );
1058
1059         return 0;
1060 }
1061 #endif
1062
1063 /**
1064  * Clear the display queue.
1065  */
1066 static void addrcompl_clear_queue( void ) {
1067         /* Clear out display queue */
1068         pthread_mutex_lock( & _completionMutex_ );
1069
1070         g_list_free( _displayQueue_ );
1071         _displayQueue_ = NULL;
1072
1073         pthread_mutex_unlock( & _completionMutex_ );
1074 }
1075
1076 /**
1077  * Add a single address entry into the display queue.
1078  * \param address Address to append.
1079  */
1080 static void addrcompl_add_queue( gchar *address ) {
1081         pthread_mutex_lock( & _completionMutex_ );
1082         _displayQueue_ = g_list_append( _displayQueue_, address );
1083         pthread_mutex_unlock( & _completionMutex_ );
1084 }
1085
1086 /**
1087  * Load list with entries from local completion index.
1088  */
1089 static void addrcompl_load_local( void ) {
1090         guint count = 0;
1091
1092         for (count = 0; count < get_completion_count(); count++) {
1093                 gchar *address;
1094
1095                 address = get_complete_address( count );
1096                 /* g_print( "\taddress ::%s::\n", address ); */
1097
1098                 /* Append contents to end of display queue */
1099                 addrcompl_add_queue( address );
1100         }
1101 }
1102
1103 /**
1104  * Start the search.
1105  */
1106 static void addrcompl_start_search( void ) {
1107 #ifndef USE_NEW_ADDRBOOK
1108         gchar *searchTerm;
1109
1110         searchTerm = g_strdup( _compWindow_->searchTerm );
1111
1112         /* Setup the search */
1113         _queryID_ = addrindex_setup_search(
1114                 searchTerm, NULL, addrcompl_callback_entry );
1115         g_free( searchTerm );
1116 #endif
1117         /* g_print( "addrcompl_start_search::queryID=%d\n", _queryID_ ); */
1118
1119         /* Load local stuff */
1120         addrcompl_load_local();
1121
1122         /* Sit back and wait until something happens */
1123         _completionIdleID_ =
1124                 g_idle_add( (GSourceFunc) addrcompl_idle, NULL );
1125         /* g_print( "addrindex_start_search::queryID=%d\n", _queryID_ ); */
1126
1127 #ifndef USE_NEW_ADDRBOOK
1128         addrindex_start_search( _queryID_ );
1129 #else
1130         
1131 #endif
1132 }
1133
1134 /**
1135  * Apply the current selection in the list to the entry field. Focus is also
1136  * moved to the next widget so that Tab key works correctly.
1137  * \param list_view List to process.
1138  * \param entry Address entry field.
1139  * \param move_focus Move focus to the next widget ?
1140  */
1141 static void completion_window_apply_selection(GtkTreeView *list_view,
1142                                                 GtkEntry *entry,
1143                                                 gboolean move_focus)
1144 {
1145         gchar *address = NULL, *text = NULL;
1146         gint   cursor_pos;
1147         GtkWidget *parent;
1148         GtkTreeSelection *selection;
1149         GtkTreeModel *model;
1150         GtkTreeIter iter;
1151         gboolean is_group = FALSE;
1152         cm_return_if_fail(list_view != NULL);
1153         cm_return_if_fail(entry != NULL);
1154         GList *grp_emails = NULL;
1155
1156         selection = gtk_tree_view_get_selection(list_view);
1157         if (! gtk_tree_selection_get_selected(selection, &model, &iter))
1158                 return;
1159
1160         /* First remove the idler */
1161         if( _completionIdleID_ != 0 ) {
1162                 g_source_remove( _completionIdleID_ );
1163                 _completionIdleID_ = 0;
1164         }
1165
1166         /* Process selected item */
1167         gtk_tree_model_get(model, &iter, ADDR_COMPL_ADDRESS, &text, 
1168                                 ADDR_COMPL_ISGROUP, &is_group, 
1169                                 ADDR_COMPL_GROUPLIST, &grp_emails,
1170                                 -1);
1171
1172         address = get_address_from_edit(entry, &cursor_pos);
1173         g_free(address);
1174         replace_address_in_edit(entry, text, cursor_pos, is_group, grp_emails);
1175         g_free(text);
1176
1177         /* Move focus to next widget */
1178         parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1179         if( parent && move_focus) {
1180                 gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1181         }
1182 }
1183
1184 /**
1185  * Start address completion. Should be called when creating the main window
1186  * containing address completion entries.
1187  * \param mainwindow Main window.
1188  */
1189 void address_completion_start(GtkWidget *mainwindow)
1190 {
1191         start_address_completion(NULL);
1192         set_match_any_part(TRUE);
1193
1194         /* register focus change hook */
1195         g_signal_connect(G_OBJECT(mainwindow), "set_focus",
1196                          G_CALLBACK(address_completion_mainwindow_set_focus),
1197                          mainwindow);
1198 }
1199
1200 /**
1201  * Need unique data to make unregistering signal handler possible for the auto
1202  * completed entry.
1203  */
1204 #define COMPLETION_UNIQUE_DATA (GINT_TO_POINTER(0xfeefaa))
1205
1206 /**
1207  * Register specified entry widget for address completion.
1208  * \param entry Address entry field.
1209  */
1210 void address_completion_register_entry(GtkEntry *entry, gboolean allow_commas)
1211 {
1212         cm_return_if_fail(entry != NULL);
1213         cm_return_if_fail(GTK_IS_ENTRY(entry));
1214
1215         /* add hooked property */
1216         g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, entry);
1217         g_object_set_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS, GINT_TO_POINTER(allow_commas));
1218
1219         /* add keypress event */
1220         g_signal_connect_closure
1221                 (G_OBJECT(entry), "key_press_event",
1222                  g_cclosure_new(G_CALLBACK(address_completion_entry_key_pressed),
1223                                 COMPLETION_UNIQUE_DATA,
1224                                 NULL),
1225                  FALSE); /* magic */
1226 }
1227
1228 /**
1229  * Unregister specified entry widget from address completion operations.
1230  * \param entry Address entry field.
1231  */
1232 void address_completion_unregister_entry(GtkEntry *entry)
1233 {
1234         GObject *entry_obj;
1235
1236         cm_return_if_fail(entry != NULL);
1237         cm_return_if_fail(GTK_IS_ENTRY(entry));
1238
1239         entry_obj = g_object_get_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK);
1240         cm_return_if_fail(entry_obj);
1241         cm_return_if_fail(G_OBJECT(entry_obj) == G_OBJECT(entry));
1242
1243         /* has the hooked property? */
1244         g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, NULL);
1245
1246         /* remove the hook */
1247         g_signal_handlers_disconnect_by_func(G_OBJECT(entry), 
1248                         G_CALLBACK(address_completion_entry_key_pressed),
1249                         COMPLETION_UNIQUE_DATA);
1250 }
1251
1252 /**
1253  * End address completion. Should be called when main window with address
1254  * completion entries terminates. NOTE: this function assumes that it is
1255  * called upon destruction of the window.
1256  * \param mainwindow Main window.
1257  */
1258 void address_completion_end(GtkWidget *mainwindow)
1259 {
1260         /* if address_completion_end() is really called on closing the window,
1261          * we don't need to unregister the set_focus_cb */
1262         end_address_completion();
1263 }
1264
1265 /* if focus changes to another entry, then clear completion cache */
1266 static void address_completion_mainwindow_set_focus(GtkWindow *window,
1267                                                     GtkWidget *widget,
1268                                                     gpointer   data)
1269 {
1270         
1271         if (widget && GTK_IS_ENTRY(widget) &&
1272             g_object_get_data(G_OBJECT(widget), ENTRY_DATA_TAB_HOOK)) {
1273                 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), ENTRY_DATA_ALLOW_COMMAS));
1274                 clear_completion_cache();
1275         }
1276 }
1277
1278 /**
1279  * Listener that watches for tab or other keystroke in address entry field.
1280  * \param entry Address entry field.
1281  * \param ev    Event object.
1282  * \param data  User data.
1283  * \return <i>TRUE</i>.
1284  */
1285 static gboolean address_completion_entry_key_pressed(GtkEntry    *entry,
1286                                                      GdkEventKey *ev,
1287                                                      gpointer     data)
1288 {
1289         if (ev->keyval == GDK_KEY_Tab) {
1290                 addrcompl_clear_queue();
1291                 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS));
1292                 if( address_completion_complete_address_in_entry( entry, TRUE ) ) {
1293                         /* route a void character to the default handler */
1294                         /* this is a dirty hack; we're actually changing a key
1295                          * reported by the system. */
1296                         ev->keyval = GDK_KEY_AudibleBell_Enable;
1297                         ev->state &= ~GDK_SHIFT_MASK;
1298
1299                         /* Create window */                     
1300                         address_completion_create_completion_window(entry);
1301
1302                         /* Start remote queries */
1303                         addrcompl_start_search();
1304
1305                         return TRUE;
1306                 }
1307                 else {
1308                         /* old behaviour */
1309                 }
1310         } else if (ev->keyval == GDK_KEY_Shift_L
1311                 || ev->keyval == GDK_KEY_Shift_R
1312                 || ev->keyval == GDK_KEY_Control_L
1313                 || ev->keyval == GDK_KEY_Control_R
1314                 || ev->keyval == GDK_KEY_Caps_Lock
1315                 || ev->keyval == GDK_KEY_Shift_Lock
1316                 || ev->keyval == GDK_KEY_Meta_L
1317                 || ev->keyval == GDK_KEY_Meta_R
1318                 || ev->keyval == GDK_KEY_Alt_L
1319                 || ev->keyval == GDK_KEY_Alt_R) {
1320                 /* these buttons should not clear the cache... */
1321         } else
1322                 clear_completion_cache();
1323
1324         return FALSE;
1325 }
1326 /**
1327  * Initialize search term for address completion.
1328  * \param entry Address entry field.
1329  */
1330 static gboolean address_completion_complete_address_in_entry(GtkEntry *entry,
1331                                                              gboolean  next)
1332 {
1333         gint ncount, cursor_pos;
1334         gchar *searchTerm, *new = NULL;
1335
1336         cm_return_val_if_fail(entry != NULL, FALSE);
1337
1338         if (!gtk_widget_has_focus(GTK_WIDGET(entry))) return FALSE;
1339
1340         /* get an address component from the cursor */
1341         searchTerm = get_address_from_edit( entry, &cursor_pos );
1342         if( ! searchTerm ) return FALSE;
1343         /* g_print( "search for :::%s:::\n", searchTerm ); */
1344
1345         /* Clear any existing search */
1346         g_free( _compWindow_->searchTerm );
1347         _compWindow_->searchTerm = g_strdup( searchTerm );
1348
1349         /* Perform search on local completion index */
1350         ncount = complete_address( searchTerm );
1351         if( 0 < ncount ) {
1352                 new = get_next_complete_address();
1353                 g_free( new );
1354         }
1355 #if (!defined(USE_LDAP) && !defined(GENERIC_UMPC))
1356         /* Select the address if there is only one match */
1357         if (ncount == 2) {
1358                 /* Display selected address in entry field */           
1359                 gchar *addr = get_complete_address(1);
1360                 if (addr && !strstr(addr, " <!--___group___-->")) {
1361                         replace_address_in_edit(entry, addr, cursor_pos, FALSE, NULL);
1362                         /* Discard the window */
1363                         clear_completion_cache();
1364                 } 
1365                 g_free(addr);
1366         }
1367         /* Make sure that drop-down appears uniform! */
1368         else 
1369 #endif
1370         if( ncount == 0 ) {
1371                 addrcompl_add_queue( g_strdup( searchTerm ) );
1372         }
1373         g_free( searchTerm );
1374
1375         return TRUE;
1376 }
1377
1378 /**
1379  * Create new address completion window for specified entry.
1380  * \param entry_ Entry widget to associate with window.
1381  */
1382 static void address_completion_create_completion_window( GtkEntry *entry_ )
1383 {
1384         gint x, y, height, width, depth;
1385         GtkWidget *scroll, *list_view;
1386         GtkRequisition r;
1387         GtkWidget *window;
1388         GtkWidget *entry = GTK_WIDGET(entry_);
1389         GdkWindow *gdkwin;
1390
1391         /* Create new window and list */
1392         window = gtk_window_new(GTK_WINDOW_POPUP);
1393         list_view  = addr_compl_list_view_create(_compWindow_);
1394
1395         /* Destroy any existing window */
1396         addrcompl_destroy_window( _compWindow_ );
1397
1398         /* Create new object */
1399         _compWindow_->window    = window;
1400         _compWindow_->entry     = entry;
1401         _compWindow_->list_view = list_view;
1402         _compWindow_->listCount = 0;
1403         _compWindow_->in_mouse  = FALSE;
1404
1405         scroll = gtk_scrolled_window_new(NULL, NULL);
1406         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
1407                                        GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
1408         gtk_container_add(GTK_CONTAINER(window), scroll);
1409         gtk_container_add(GTK_CONTAINER(scroll), list_view);
1410         gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll),
1411                 GTK_SHADOW_OUT);
1412         /* Use entry widget to create initial window */
1413         gdkwin = gtk_widget_get_window(entry),
1414 #if !GTK_CHECK_VERSION(3, 0, 0)
1415         gdk_window_get_geometry(gdkwin, &x, &y, &width, &height, &depth);
1416 #else
1417         gdk_window_get_geometry(gdkwin, &x, &y, &width, &height);
1418 #endif
1419         gdk_window_get_origin (gdkwin, &x, &y);
1420         y += height;
1421         gtk_window_move(GTK_WINDOW(window), x, y);
1422
1423         /* Resize window to fit initial (empty) address list */
1424         gtk_widget_size_request( list_view, &r );
1425         gtk_widget_set_size_request( window, width, r.height );
1426         gtk_widget_show_all( window );
1427         gtk_widget_size_request( list_view, &r );
1428
1429         /* Setup handlers */
1430         g_signal_connect(G_OBJECT(list_view), "button_press_event",
1431                          G_CALLBACK(list_view_button_press),
1432                          _compWindow_);
1433                          
1434         g_signal_connect(G_OBJECT(list_view), "button_release_event",
1435                          G_CALLBACK(list_view_button_release),
1436                          _compWindow_);
1437         
1438         g_signal_connect(G_OBJECT(window),
1439                          "button-press-event",
1440                          G_CALLBACK(completion_window_button_press),
1441                          _compWindow_ );
1442         g_signal_connect(G_OBJECT(window),
1443                          "key-press-event",
1444                          G_CALLBACK(completion_window_key_press),
1445                          _compWindow_ );
1446         gdk_pointer_grab(gtk_widget_get_window(window), TRUE,
1447                          GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK |
1448                          GDK_BUTTON_RELEASE_MASK,
1449                          NULL, NULL, GDK_CURRENT_TIME);
1450         gdk_keyboard_grab(gtk_widget_get_window(window), FALSE, GDK_CURRENT_TIME);
1451         gtk_grab_add( window );
1452 }
1453
1454 /**
1455  * Respond to button press in completion window. Check if mouse click is
1456  * anywhere outside the completion window. In that case the completion
1457  * window is destroyed, and the original searchTerm is restored.
1458  *
1459  * \param widget   Window object.
1460  * \param event    Event.
1461  * \param compWin  Reference to completion window.
1462  */
1463 static gboolean completion_window_button_press(GtkWidget *widget,
1464                                                GdkEventButton *event,
1465                                                CompletionWindow *compWin )
1466 {
1467         GtkWidget *event_widget, *entry;
1468         gchar *searchTerm;
1469         gint cursor_pos;
1470         gboolean restore = TRUE;
1471
1472         cm_return_val_if_fail(compWin != NULL, FALSE);
1473
1474         entry = compWin->entry;
1475         cm_return_val_if_fail(entry != NULL, FALSE);
1476
1477         /* Test where mouse was clicked */
1478         event_widget = gtk_get_event_widget((GdkEvent *)event);
1479         if (event_widget != widget) {
1480                 while (event_widget) {
1481                         if (event_widget == widget)
1482                                 return FALSE;
1483                         else if (event_widget == entry) {
1484                                 restore = FALSE;
1485                                 break;
1486                         }
1487                         event_widget = gtk_widget_get_parent(event_widget);
1488                 }
1489         }
1490
1491         if (restore) {
1492                 /* Clicked outside of completion window - restore */
1493                 searchTerm = _compWindow_->searchTerm;
1494                 g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1495                 replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos, FALSE, NULL);
1496         }
1497
1498         clear_completion_cache();
1499         addrcompl_destroy_window( _compWindow_ );
1500
1501         return TRUE;
1502 }
1503
1504 /**
1505  * Respond to key press in completion window.
1506  * \param widget   Window object.
1507  * \param event    Event.
1508  * \param compWind Reference to completion window.
1509  */
1510 static gboolean completion_window_key_press(GtkWidget *widget,
1511                                             GdkEventKey *event,
1512                                             CompletionWindow *compWin )
1513 {
1514         GdkEventKey tmp_event;
1515         GtkWidget *entry;
1516         gchar *searchTerm;
1517         gint cursor_pos;
1518         GtkWidget *list_view;
1519         GtkWidget *parent;
1520         cm_return_val_if_fail(compWin != NULL, FALSE);
1521
1522         entry = compWin->entry;
1523         list_view = compWin->list_view;
1524         cm_return_val_if_fail(entry != NULL, FALSE);
1525
1526         /* allow keyboard navigation in the alternatives tree view */
1527         if (event->keyval == GDK_KEY_Up || event->keyval == GDK_KEY_Down ||
1528             event->keyval == GDK_KEY_Page_Up || event->keyval == GDK_KEY_Page_Down) {
1529                 completion_window_advance_selection
1530                         (GTK_TREE_VIEW(list_view),
1531                          event->keyval == GDK_KEY_Down ||
1532                          event->keyval == GDK_KEY_Page_Down ? TRUE : FALSE);
1533                 return FALSE;
1534         }               
1535
1536         /* make tab move to next field */
1537         if( event->keyval == GDK_KEY_Tab ) {
1538                 /* Reference to parent */
1539                 parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1540
1541                 /* Discard the window */
1542                 clear_completion_cache();
1543                 addrcompl_destroy_window( _compWindow_ );
1544
1545                 /* Move focus to next widget */
1546                 if( parent ) {
1547                         gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1548                 }
1549                 return FALSE;
1550         }
1551
1552         /* make backtab move to previous field */
1553         if( event->keyval == GDK_KEY_ISO_Left_Tab ) {
1554                 /* Reference to parent */
1555                 parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1556
1557                 /* Discard the window */
1558                 clear_completion_cache();
1559                 addrcompl_destroy_window( _compWindow_ );
1560
1561                 /* Move focus to previous widget */
1562                 if( parent ) {
1563                         gtk_widget_child_focus( parent, GTK_DIR_TAB_BACKWARD );
1564                 }
1565                 return FALSE;
1566         }
1567         _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS));
1568
1569         /* look for presses that accept the selection */
1570         if (event->keyval == GDK_KEY_Return || event->keyval == GDK_KEY_space ||
1571                         event->keyval == GDK_KEY_KP_Enter ||
1572                         (_allowCommas_ && event->keyval == GDK_KEY_comma)) {
1573                 /* User selected address with a key press */
1574
1575                 /* Display selected address in entry field */           
1576                 completion_window_apply_selection(
1577                         GTK_TREE_VIEW(list_view), GTK_ENTRY(entry),
1578                         event->keyval != GDK_KEY_comma);
1579
1580                 if (event->keyval == GDK_KEY_comma) {
1581                         gint pos = gtk_editable_get_position(GTK_EDITABLE(entry));
1582                         gtk_editable_insert_text(GTK_EDITABLE(entry), ", ", 2, &pos);
1583                         gtk_editable_set_position(GTK_EDITABLE(entry), pos + 1);
1584                 }
1585
1586                 /* Discard the window */
1587                 clear_completion_cache();
1588                 addrcompl_destroy_window( _compWindow_ );
1589                 return FALSE;
1590         }
1591
1592         /* key state keys should never be handled */
1593         if (event->keyval == GDK_KEY_Shift_L
1594                  || event->keyval == GDK_KEY_Shift_R
1595                  || event->keyval == GDK_KEY_Control_L
1596                  || event->keyval == GDK_KEY_Control_R
1597                  || event->keyval == GDK_KEY_Caps_Lock
1598                  || event->keyval == GDK_KEY_Shift_Lock
1599                  || event->keyval == GDK_KEY_Meta_L
1600                  || event->keyval == GDK_KEY_Meta_R
1601                  || event->keyval == GDK_KEY_Alt_L
1602                  || event->keyval == GDK_KEY_Alt_R) {
1603                 return FALSE;
1604         }
1605
1606         /* some other key, let's restore the searchTerm (orignal text) */
1607         searchTerm = _compWindow_->searchTerm;
1608         g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1609         replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos, FALSE, NULL);
1610
1611         /* make sure anything we typed comes in the edit box */
1612         tmp_event.type       = event->type;
1613         tmp_event.window     = gtk_widget_get_window(GTK_WIDGET(entry));
1614         tmp_event.send_event = TRUE;
1615         tmp_event.time       = event->time;
1616         tmp_event.state      = event->state;
1617         tmp_event.keyval     = event->keyval;
1618         tmp_event.length     = event->length;
1619         tmp_event.string     = event->string;
1620         gtk_widget_event(entry, (GdkEvent *)&tmp_event);
1621
1622         /* and close the completion window */
1623         clear_completion_cache();
1624         addrcompl_destroy_window( _compWindow_ );
1625
1626         return TRUE;
1627 }
1628
1629 /*
1630  * ============================================================================
1631  * Publically accessible functions.
1632  * ============================================================================
1633  */
1634
1635 /**
1636  * Setup completion object.
1637  */
1638 void addrcompl_initialize( void ) {
1639         /* g_print( "addrcompl_initialize...\n" ); */
1640         if( ! _compWindow_ ) {
1641                 _compWindow_ = addrcompl_create_window();
1642         }
1643         _queryID_ = 0;
1644         _completionIdleID_ = 0;
1645         /* g_print( "addrcompl_initialize...done\n" ); */
1646 }
1647
1648 /**
1649  * Teardown completion object.
1650  */
1651 void addrcompl_teardown( void ) {
1652         /* g_print( "addrcompl_teardown...\n" ); */
1653         addrcompl_free_window( _compWindow_ );
1654         _compWindow_ = NULL;
1655
1656         addrcompl_clear_queue();
1657
1658         _completionIdleID_ = 0;
1659         /* g_print( "addrcompl_teardown...done\n" ); */
1660 }
1661
1662 /*
1663  * tree view functions
1664  */
1665
1666 static GtkListStore *addr_compl_create_store(void)
1667 {
1668         return gtk_list_store_new(N_ADDR_COMPL_COLUMNS,
1669                                   GDK_TYPE_PIXBUF,
1670                                   G_TYPE_STRING,
1671                                   G_TYPE_BOOLEAN,
1672                                   G_TYPE_POINTER,
1673                                   -1);
1674 }
1675                                              
1676 static GtkWidget *addr_compl_list_view_create(CompletionWindow *window)
1677 {
1678         GtkTreeView *list_view;
1679         GtkTreeSelection *selector;
1680         GtkTreeModel *model;
1681
1682         model = GTK_TREE_MODEL(addr_compl_create_store());
1683         list_view = GTK_TREE_VIEW(gtk_tree_view_new_with_model(model));
1684         g_object_unref(model);  
1685         
1686         gtk_tree_view_set_rules_hint(list_view, prefs_common.use_stripes_everywhere);
1687         gtk_tree_view_set_headers_visible(list_view, FALSE);
1688         
1689         selector = gtk_tree_view_get_selection(list_view);
1690         gtk_tree_selection_set_mode(selector, GTK_SELECTION_BROWSE);
1691         gtk_tree_selection_set_select_function(selector, addr_compl_selected,
1692                                                window, NULL);
1693
1694         /* create the columns */
1695         addr_compl_create_list_view_columns(GTK_WIDGET(list_view));
1696
1697         return GTK_WIDGET(list_view);
1698 }
1699
1700 static void addr_compl_create_list_view_columns(GtkWidget *list_view)
1701 {
1702         GtkTreeViewColumn *column;
1703         GtkCellRenderer *renderer;
1704
1705         renderer = gtk_cell_renderer_pixbuf_new();
1706         column = gtk_tree_view_column_new_with_attributes
1707                 ("", renderer,
1708                  "pixbuf", ADDR_COMPL_ICON, NULL);
1709         gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);          
1710         renderer = gtk_cell_renderer_text_new();
1711         column = gtk_tree_view_column_new_with_attributes
1712                 ("", renderer, "text", ADDR_COMPL_ADDRESS, NULL);
1713         gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);          
1714 }
1715
1716 static gboolean list_view_button_press(GtkWidget *widget, GdkEventButton *event,
1717                                        CompletionWindow *window)
1718 {
1719         if (window && event && event->type == GDK_BUTTON_PRESS) {
1720                 window->in_mouse = TRUE;
1721         }
1722         return FALSE;
1723 }
1724
1725 static gboolean list_view_button_release(GtkWidget *widget, GdkEventButton *event,
1726                                          CompletionWindow *window)
1727 {
1728         if (window && event && event->type == GDK_BUTTON_RELEASE) {
1729                 window->in_mouse = FALSE;
1730         }
1731         return FALSE;
1732 }
1733
1734 static gboolean addr_compl_selected(GtkTreeSelection *selector,
1735                                     GtkTreeModel *model, 
1736                                     GtkTreePath *path,
1737                                     gboolean currently_selected,
1738                                     gpointer data)
1739 {
1740         CompletionWindow *window = data;
1741
1742         if (currently_selected)
1743                 return TRUE;
1744         
1745         if (!window->in_mouse)
1746                 return TRUE;
1747
1748         /* XXX: select the entry and kill window later... select is called before
1749          * any other mouse events handlers including the tree view internal one;
1750          * not using a time out would result in a crash. if this doesn't work
1751          * safely, maybe we should set variables when receiving button presses
1752          * in the tree view. */
1753         if (!window->destroying) {
1754                 window->destroying = TRUE;
1755                 g_idle_add((GSourceFunc) addr_compl_defer_select_destruct, data);
1756         }
1757
1758         return TRUE;
1759 }
1760
1761 static gboolean addr_compl_defer_select_destruct(CompletionWindow *window)
1762 {
1763         GtkEntry *entry = GTK_ENTRY(window->entry);
1764
1765         completion_window_apply_selection(GTK_TREE_VIEW(window->list_view), 
1766                                           entry, TRUE);
1767
1768         clear_completion_cache();
1769
1770         addrcompl_destroy_window(window);
1771         return FALSE;
1772 }
1773
1774
1775 /*
1776  * End of Source.
1777  */
1778