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