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