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