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