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