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