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