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