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