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