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