In compose window, allow address completion to match any part of address, not just...
[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 /**
973  * Completion idle function. This function is called by the main (UI) thread
974  * during UI idle time while an address search is in progress. Items from the
975  * display queue are processed and appended to the address list.
976  *
977  * \param data Target completion window to receive email addresses.
978  * \return <i>TRUE</i> to ensure that idle event do not get ignored.
979  */
980 static gboolean addrcompl_idle( gpointer data ) {
981         GList *node;
982         gchar *address;
983
984         /* Process all entries in display queue */
985         pthread_mutex_lock( & _completionMutex_ );
986         if( _displayQueue_ ) {
987                 node = _displayQueue_;
988                 while( node ) {
989                         address = node->data;
990                         /* g_print( "address ::: %s :::\n", address ); */
991                         addrcompl_add_entry( _compWindow_, address );
992                         g_free( address );
993                         node = g_list_next( node );
994                 }
995                 g_list_free( _displayQueue_ );
996                 _displayQueue_ = NULL;
997         }
998         pthread_mutex_unlock( & _completionMutex_ );
999         claws_do_idle();
1000
1001         return TRUE;
1002 }
1003
1004 /**
1005  * Callback entry point. The background thread (if any) appends the address
1006  * list to the display queue.
1007  * \param sender     Sender of query.
1008  * \param queryID    Query ID of search request.
1009  * \param listEMail  List of zero of more email objects that met search
1010  *                   criteria.
1011  * \param data       Query data.
1012  */
1013 #ifndef USE_NEW_ADDRBOOK
1014 static gint addrcompl_callback_entry(
1015         gpointer sender, gint queryID, GList *listEMail, gpointer data )
1016 {
1017         GList *node;
1018         gchar *address;
1019
1020         /* g_print( "addrcompl_callback_entry::queryID=%d\n", queryID ); */
1021         pthread_mutex_lock( & _completionMutex_ );
1022         if( queryID == _queryID_ ) {
1023                 /* Append contents to end of display queue */
1024                 node = listEMail;
1025                 while( node ) {
1026                         ItemEMail *email = node->data;
1027
1028                         address = addritem_format_email( email );
1029                         /* g_print( "\temail/address ::%s::\n", address ); */
1030                         _displayQueue_ = g_list_append( _displayQueue_, address );
1031                         node = g_list_next( node );
1032                 }
1033         }
1034         g_list_free( listEMail );
1035         pthread_mutex_unlock( & _completionMutex_ );
1036
1037         return 0;
1038 }
1039 #endif
1040
1041 /**
1042  * Clear the display queue.
1043  */
1044 static void addrcompl_clear_queue( void ) {
1045         /* Clear out display queue */
1046         pthread_mutex_lock( & _completionMutex_ );
1047
1048         g_list_free( _displayQueue_ );
1049         _displayQueue_ = NULL;
1050
1051         pthread_mutex_unlock( & _completionMutex_ );
1052 }
1053
1054 /**
1055  * Add a single address entry into the display queue.
1056  * \param address Address to append.
1057  */
1058 static void addrcompl_add_queue( gchar *address ) {
1059         pthread_mutex_lock( & _completionMutex_ );
1060         _displayQueue_ = g_list_append( _displayQueue_, address );
1061         pthread_mutex_unlock( & _completionMutex_ );
1062 }
1063
1064 /**
1065  * Load list with entries from local completion index.
1066  */
1067 static void addrcompl_load_local( void ) {
1068         guint count = 0;
1069
1070         for (count = 0; count < get_completion_count(); count++) {
1071                 gchar *address;
1072
1073                 address = get_complete_address( count );
1074                 /* g_print( "\taddress ::%s::\n", address ); */
1075
1076                 /* Append contents to end of display queue */
1077                 addrcompl_add_queue( address );
1078         }
1079 }
1080
1081 /**
1082  * Start the search.
1083  */
1084 static void addrcompl_start_search( void ) {
1085 #ifndef USE_NEW_ADDRBOOK
1086         gchar *searchTerm;
1087
1088         searchTerm = g_strdup( _compWindow_->searchTerm );
1089
1090         /* Setup the search */
1091         _queryID_ = addrindex_setup_search(
1092                 searchTerm, NULL, addrcompl_callback_entry );
1093         g_free( searchTerm );
1094 #endif
1095         /* g_print( "addrcompl_start_search::queryID=%d\n", _queryID_ ); */
1096
1097         /* Load local stuff */
1098         addrcompl_load_local();
1099
1100         /* Sit back and wait until something happens */
1101         _completionIdleID_ =
1102                 g_idle_add( (GSourceFunc) addrcompl_idle, NULL );
1103         /* g_print( "addrindex_start_search::queryID=%d\n", _queryID_ ); */
1104
1105 #ifndef USE_NEW_ADDRBOOK
1106         addrindex_start_search( _queryID_ );
1107 #else
1108         
1109 #endif
1110 }
1111
1112 /**
1113  * Apply the current selection in the list to the entry field. Focus is also
1114  * moved to the next widget so that Tab key works correctly.
1115  * \param list_view List to process.
1116  * \param entry Address entry field.
1117  * \param move_focus Move focus to the next widget ?
1118  */
1119 static void completion_window_apply_selection(GtkTreeView *list_view,
1120                                                 GtkEntry *entry,
1121                                                 gboolean move_focus)
1122 {
1123         gchar *address = NULL, *text = NULL;
1124         gint   cursor_pos;
1125         GtkWidget *parent;
1126         GtkTreeSelection *selection;
1127         GtkTreeModel *model;
1128         GtkTreeIter iter;
1129         gboolean is_group = FALSE;
1130         cm_return_if_fail(list_view != NULL);
1131         cm_return_if_fail(entry != NULL);
1132         GList *grp_emails = NULL;
1133
1134         selection = gtk_tree_view_get_selection(list_view);
1135         if (! gtk_tree_selection_get_selected(selection, &model, &iter))
1136                 return;
1137
1138         /* First remove the idler */
1139         if( _completionIdleID_ != 0 ) {
1140                 g_source_remove( _completionIdleID_ );
1141                 _completionIdleID_ = 0;
1142         }
1143
1144         /* Process selected item */
1145         gtk_tree_model_get(model, &iter, ADDR_COMPL_ADDRESS, &text, 
1146                                 ADDR_COMPL_ISGROUP, &is_group, 
1147                                 ADDR_COMPL_GROUPLIST, &grp_emails,
1148                                 -1);
1149
1150         address = get_address_from_edit(entry, &cursor_pos);
1151         g_free(address);
1152         replace_address_in_edit(entry, text, cursor_pos, is_group, grp_emails);
1153         g_free(text);
1154
1155         /* Move focus to next widget */
1156         parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1157         if( parent && move_focus) {
1158                 gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1159         }
1160 }
1161
1162 /**
1163  * Start address completion. Should be called when creating the main window
1164  * containing address completion entries.
1165  * \param mainwindow Main window.
1166  */
1167 void address_completion_start(GtkWidget *mainwindow)
1168 {
1169         start_address_completion(NULL);
1170
1171         /* register focus change hook */
1172         g_signal_connect(G_OBJECT(mainwindow), "set_focus",
1173                          G_CALLBACK(address_completion_mainwindow_set_focus),
1174                          mainwindow);
1175 }
1176
1177 /**
1178  * Need unique data to make unregistering signal handler possible for the auto
1179  * completed entry.
1180  */
1181 #define COMPLETION_UNIQUE_DATA (GINT_TO_POINTER(0xfeefaa))
1182
1183 /**
1184  * Register specified entry widget for address completion.
1185  * \param entry Address entry field.
1186  */
1187 void address_completion_register_entry(GtkEntry *entry, gboolean allow_commas)
1188 {
1189         cm_return_if_fail(entry != NULL);
1190         cm_return_if_fail(GTK_IS_ENTRY(entry));
1191
1192         /* add hooked property */
1193         g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, entry);
1194         g_object_set_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS, GINT_TO_POINTER(allow_commas));
1195
1196         /* add keypress event */
1197         g_signal_connect_closure
1198                 (G_OBJECT(entry), "key_press_event",
1199                  g_cclosure_new(G_CALLBACK(address_completion_entry_key_pressed),
1200                                 COMPLETION_UNIQUE_DATA,
1201                                 NULL),
1202                  FALSE); /* magic */
1203 }
1204
1205 /**
1206  * Unregister specified entry widget from address completion operations.
1207  * \param entry Address entry field.
1208  */
1209 void address_completion_unregister_entry(GtkEntry *entry)
1210 {
1211         GObject *entry_obj;
1212
1213         cm_return_if_fail(entry != NULL);
1214         cm_return_if_fail(GTK_IS_ENTRY(entry));
1215
1216         entry_obj = g_object_get_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK);
1217         cm_return_if_fail(entry_obj);
1218         cm_return_if_fail(G_OBJECT(entry_obj) == G_OBJECT(entry));
1219
1220         /* has the hooked property? */
1221         g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, NULL);
1222
1223         /* remove the hook */
1224         g_signal_handlers_disconnect_by_func(G_OBJECT(entry), 
1225                         G_CALLBACK(address_completion_entry_key_pressed),
1226                         COMPLETION_UNIQUE_DATA);
1227 }
1228
1229 /**
1230  * End address completion. Should be called when main window with address
1231  * completion entries terminates. NOTE: this function assumes that it is
1232  * called upon destruction of the window.
1233  * \param mainwindow Main window.
1234  */
1235 void address_completion_end(GtkWidget *mainwindow)
1236 {
1237         /* if address_completion_end() is really called on closing the window,
1238          * we don't need to unregister the set_focus_cb */
1239         end_address_completion();
1240 }
1241
1242 /* if focus changes to another entry, then clear completion cache */
1243 static void address_completion_mainwindow_set_focus(GtkWindow *window,
1244                                                     GtkWidget *widget,
1245                                                     gpointer   data)
1246 {
1247         
1248         if (widget && GTK_IS_ENTRY(widget) &&
1249             g_object_get_data(G_OBJECT(widget), ENTRY_DATA_TAB_HOOK)) {
1250                 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), ENTRY_DATA_ALLOW_COMMAS));
1251                 clear_completion_cache();
1252         }
1253 }
1254
1255 /**
1256  * Listener that watches for tab or other keystroke in address entry field.
1257  * \param entry Address entry field.
1258  * \param ev    Event object.
1259  * \param data  User data.
1260  * \return <i>TRUE</i>.
1261  */
1262 static gboolean address_completion_entry_key_pressed(GtkEntry    *entry,
1263                                                      GdkEventKey *ev,
1264                                                      gpointer     data)
1265 {
1266         if (ev->keyval == GDK_KEY_Tab) {
1267                 addrcompl_clear_queue();
1268                 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS));
1269                 if( address_completion_complete_address_in_entry( entry, TRUE ) ) {
1270                         /* route a void character to the default handler */
1271                         /* this is a dirty hack; we're actually changing a key
1272                          * reported by the system. */
1273                         ev->keyval = GDK_KEY_AudibleBell_Enable;
1274                         ev->state &= ~GDK_SHIFT_MASK;
1275
1276                         /* Create window */                     
1277                         address_completion_create_completion_window(entry);
1278
1279                         /* Start remote queries */
1280                         addrcompl_start_search();
1281
1282                         return TRUE;
1283                 }
1284                 else {
1285                         /* old behaviour */
1286                 }
1287         } else if (ev->keyval == GDK_KEY_Shift_L
1288                 || ev->keyval == GDK_KEY_Shift_R
1289                 || ev->keyval == GDK_KEY_Control_L
1290                 || ev->keyval == GDK_KEY_Control_R
1291                 || ev->keyval == GDK_KEY_Caps_Lock
1292                 || ev->keyval == GDK_KEY_Shift_Lock
1293                 || ev->keyval == GDK_KEY_Meta_L
1294                 || ev->keyval == GDK_KEY_Meta_R
1295                 || ev->keyval == GDK_KEY_Alt_L
1296                 || ev->keyval == GDK_KEY_Alt_R) {
1297                 /* these buttons should not clear the cache... */
1298         } else
1299                 clear_completion_cache();
1300
1301         return FALSE;
1302 }
1303 /**
1304  * Initialize search term for address completion.
1305  * \param entry Address entry field.
1306  */
1307 static gboolean address_completion_complete_address_in_entry(GtkEntry *entry,
1308                                                              gboolean  next)
1309 {
1310         gint ncount, cursor_pos;
1311         gchar *searchTerm, *new = NULL;
1312
1313         cm_return_val_if_fail(entry != NULL, FALSE);
1314
1315         if (!gtk_widget_has_focus(GTK_WIDGET(entry))) return FALSE;
1316
1317         /* get an address component from the cursor */
1318         searchTerm = get_address_from_edit( entry, &cursor_pos );
1319         if( ! searchTerm ) return FALSE;
1320         /* g_print( "search for :::%s:::\n", searchTerm ); */
1321
1322         /* Clear any existing search */
1323         g_free( _compWindow_->searchTerm );
1324         _compWindow_->searchTerm = g_strdup( searchTerm );
1325
1326         /* Perform search on local completion index */
1327         ncount = complete_address( searchTerm );
1328         if( 0 < ncount ) {
1329                 new = get_next_complete_address();
1330                 g_free( new );
1331         }
1332 #if (!defined(USE_LDAP) && !defined(GENERIC_UMPC))
1333         /* Select the address if there is only one match */
1334         if (ncount == 2) {
1335                 /* Display selected address in entry field */           
1336                 gchar *addr = get_complete_address(1);
1337                 if (addr && !strstr(addr, " <!--___group___-->")) {
1338                         replace_address_in_edit(entry, addr, cursor_pos, FALSE, NULL);
1339                         /* Discard the window */
1340                         clear_completion_cache();
1341                 } 
1342                 g_free(addr);
1343         }
1344         /* Make sure that drop-down appears uniform! */
1345         else 
1346 #endif
1347         if( ncount == 0 ) {
1348                 addrcompl_add_queue( g_strdup( searchTerm ) );
1349         }
1350         g_free( searchTerm );
1351
1352         return TRUE;
1353 }
1354
1355 /**
1356  * Create new address completion window for specified entry.
1357  * \param entry_ Entry widget to associate with window.
1358  */
1359 static void address_completion_create_completion_window( GtkEntry *entry_ )
1360 {
1361         gint x, y, height, width, depth;
1362         GtkWidget *scroll, *list_view;
1363         GtkRequisition r;
1364         GtkWidget *window;
1365         GtkWidget *entry = GTK_WIDGET(entry_);
1366         GdkWindow *gdkwin;
1367
1368         /* Create new window and list */
1369         window = gtk_window_new(GTK_WINDOW_POPUP);
1370         list_view  = addr_compl_list_view_create(_compWindow_);
1371
1372         /* Destroy any existing window */
1373         addrcompl_destroy_window( _compWindow_ );
1374
1375         /* Create new object */
1376         _compWindow_->window    = window;
1377         _compWindow_->entry     = entry;
1378         _compWindow_->list_view = list_view;
1379         _compWindow_->listCount = 0;
1380         _compWindow_->in_mouse  = FALSE;
1381
1382         scroll = gtk_scrolled_window_new(NULL, NULL);
1383         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
1384                                        GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
1385         gtk_container_add(GTK_CONTAINER(window), scroll);
1386         gtk_container_add(GTK_CONTAINER(scroll), list_view);
1387         gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll),
1388                 GTK_SHADOW_OUT);
1389         /* Use entry widget to create initial window */
1390         gdkwin = gtk_widget_get_window(entry),
1391 #if !GTK_CHECK_VERSION(3, 0, 0)
1392         gdk_window_get_geometry(gdkwin, &x, &y, &width, &height, &depth);
1393 #else
1394         gdk_window_get_geometry(gdkwin, &x, &y, &width, &height);
1395 #endif
1396         gdk_window_get_origin (gdkwin, &x, &y);
1397         y += height;
1398         gtk_window_move(GTK_WINDOW(window), x, y);
1399
1400         /* Resize window to fit initial (empty) address list */
1401         gtk_widget_size_request( list_view, &r );
1402         gtk_widget_set_size_request( window, width, r.height );
1403         gtk_widget_show_all( window );
1404         gtk_widget_size_request( list_view, &r );
1405
1406         /* Setup handlers */
1407         g_signal_connect(G_OBJECT(list_view), "button_press_event",
1408                          G_CALLBACK(list_view_button_press),
1409                          _compWindow_);
1410                          
1411         g_signal_connect(G_OBJECT(list_view), "button_release_event",
1412                          G_CALLBACK(list_view_button_release),
1413                          _compWindow_);
1414         
1415         g_signal_connect(G_OBJECT(window),
1416                          "button-press-event",
1417                          G_CALLBACK(completion_window_button_press),
1418                          _compWindow_ );
1419         g_signal_connect(G_OBJECT(window),
1420                          "key-press-event",
1421                          G_CALLBACK(completion_window_key_press),
1422                          _compWindow_ );
1423         gdk_pointer_grab(gtk_widget_get_window(window), TRUE,
1424                          GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK |
1425                          GDK_BUTTON_RELEASE_MASK,
1426                          NULL, NULL, GDK_CURRENT_TIME);
1427         gdk_keyboard_grab(gtk_widget_get_window(window), FALSE, GDK_CURRENT_TIME);
1428         gtk_grab_add( window );
1429 }
1430
1431 /**
1432  * Respond to button press in completion window. Check if mouse click is
1433  * anywhere outside the completion window. In that case the completion
1434  * window is destroyed, and the original searchTerm is restored.
1435  *
1436  * \param widget   Window object.
1437  * \param event    Event.
1438  * \param compWin  Reference to completion window.
1439  */
1440 static gboolean completion_window_button_press(GtkWidget *widget,
1441                                                GdkEventButton *event,
1442                                                CompletionWindow *compWin )
1443 {
1444         GtkWidget *event_widget, *entry;
1445         gchar *searchTerm;
1446         gint cursor_pos;
1447         gboolean restore = TRUE;
1448
1449         cm_return_val_if_fail(compWin != NULL, FALSE);
1450
1451         entry = compWin->entry;
1452         cm_return_val_if_fail(entry != NULL, FALSE);
1453
1454         /* Test where mouse was clicked */
1455         event_widget = gtk_get_event_widget((GdkEvent *)event);
1456         if (event_widget != widget) {
1457                 while (event_widget) {
1458                         if (event_widget == widget)
1459                                 return FALSE;
1460                         else if (event_widget == entry) {
1461                                 restore = FALSE;
1462                                 break;
1463                         }
1464                         event_widget = gtk_widget_get_parent(event_widget);
1465                 }
1466         }
1467
1468         if (restore) {
1469                 /* Clicked outside of completion window - restore */
1470                 searchTerm = _compWindow_->searchTerm;
1471                 g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1472                 replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos, FALSE, NULL);
1473         }
1474
1475         clear_completion_cache();
1476         addrcompl_destroy_window( _compWindow_ );
1477
1478         return TRUE;
1479 }
1480
1481 /**
1482  * Respond to key press in completion window.
1483  * \param widget   Window object.
1484  * \param event    Event.
1485  * \param compWind Reference to completion window.
1486  */
1487 static gboolean completion_window_key_press(GtkWidget *widget,
1488                                             GdkEventKey *event,
1489                                             CompletionWindow *compWin )
1490 {
1491         GdkEventKey tmp_event;
1492         GtkWidget *entry;
1493         gchar *searchTerm;
1494         gint cursor_pos;
1495         GtkWidget *list_view;
1496         GtkWidget *parent;
1497         cm_return_val_if_fail(compWin != NULL, FALSE);
1498
1499         entry = compWin->entry;
1500         list_view = compWin->list_view;
1501         cm_return_val_if_fail(entry != NULL, FALSE);
1502
1503         /* allow keyboard navigation in the alternatives tree view */
1504         if (event->keyval == GDK_KEY_Up || event->keyval == GDK_KEY_Down ||
1505             event->keyval == GDK_KEY_Page_Up || event->keyval == GDK_KEY_Page_Down) {
1506                 completion_window_advance_selection
1507                         (GTK_TREE_VIEW(list_view),
1508                          event->keyval == GDK_KEY_Down ||
1509                          event->keyval == GDK_KEY_Page_Down ? TRUE : FALSE);
1510                 return FALSE;
1511         }               
1512
1513         /* make tab move to next field */
1514         if( event->keyval == GDK_KEY_Tab ) {
1515                 /* Reference to parent */
1516                 parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1517
1518                 /* Discard the window */
1519                 clear_completion_cache();
1520                 addrcompl_destroy_window( _compWindow_ );
1521
1522                 /* Move focus to next widget */
1523                 if( parent ) {
1524                         gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1525                 }
1526                 return FALSE;
1527         }
1528
1529         /* make backtab move to previous field */
1530         if( event->keyval == GDK_KEY_ISO_Left_Tab ) {
1531                 /* Reference to parent */
1532                 parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1533
1534                 /* Discard the window */
1535                 clear_completion_cache();
1536                 addrcompl_destroy_window( _compWindow_ );
1537
1538                 /* Move focus to previous widget */
1539                 if( parent ) {
1540                         gtk_widget_child_focus( parent, GTK_DIR_TAB_BACKWARD );
1541                 }
1542                 return FALSE;
1543         }
1544         _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS));
1545
1546         /* look for presses that accept the selection */
1547         if (event->keyval == GDK_KEY_Return || event->keyval == GDK_KEY_space ||
1548                         event->keyval == GDK_KEY_KP_Enter ||
1549                         (_allowCommas_ && event->keyval == GDK_KEY_comma)) {
1550                 /* User selected address with a key press */
1551
1552                 /* Display selected address in entry field */           
1553                 completion_window_apply_selection(
1554                         GTK_TREE_VIEW(list_view), GTK_ENTRY(entry),
1555                         event->keyval != GDK_KEY_comma);
1556
1557                 if (event->keyval == GDK_KEY_comma) {
1558                         gint pos = gtk_editable_get_position(GTK_EDITABLE(entry));
1559                         gtk_editable_insert_text(GTK_EDITABLE(entry), ", ", 2, &pos);
1560                         gtk_editable_set_position(GTK_EDITABLE(entry), pos + 1);
1561                 }
1562
1563                 /* Discard the window */
1564                 clear_completion_cache();
1565                 addrcompl_destroy_window( _compWindow_ );
1566                 return FALSE;
1567         }
1568
1569         /* key state keys should never be handled */
1570         if (event->keyval == GDK_KEY_Shift_L
1571                  || event->keyval == GDK_KEY_Shift_R
1572                  || event->keyval == GDK_KEY_Control_L
1573                  || event->keyval == GDK_KEY_Control_R
1574                  || event->keyval == GDK_KEY_Caps_Lock
1575                  || event->keyval == GDK_KEY_Shift_Lock
1576                  || event->keyval == GDK_KEY_Meta_L
1577                  || event->keyval == GDK_KEY_Meta_R
1578                  || event->keyval == GDK_KEY_Alt_L
1579                  || event->keyval == GDK_KEY_Alt_R) {
1580                 return FALSE;
1581         }
1582
1583         /* some other key, let's restore the searchTerm (orignal text) */
1584         searchTerm = _compWindow_->searchTerm;
1585         g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1586         replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos, FALSE, NULL);
1587
1588         /* make sure anything we typed comes in the edit box */
1589         tmp_event.type       = event->type;
1590         tmp_event.window     = gtk_widget_get_window(GTK_WIDGET(entry));
1591         tmp_event.send_event = TRUE;
1592         tmp_event.time       = event->time;
1593         tmp_event.state      = event->state;
1594         tmp_event.keyval     = event->keyval;
1595         tmp_event.length     = event->length;
1596         tmp_event.string     = event->string;
1597         gtk_widget_event(entry, (GdkEvent *)&tmp_event);
1598
1599         /* and close the completion window */
1600         clear_completion_cache();
1601         addrcompl_destroy_window( _compWindow_ );
1602
1603         return TRUE;
1604 }
1605
1606 /*
1607  * ============================================================================
1608  * Publically accessible functions.
1609  * ============================================================================
1610  */
1611
1612 /**
1613  * Setup completion object.
1614  */
1615 void addrcompl_initialize( void ) {
1616         /* g_print( "addrcompl_initialize...\n" ); */
1617         if( ! _compWindow_ ) {
1618                 _compWindow_ = addrcompl_create_window();
1619         }
1620         _queryID_ = 0;
1621         _completionIdleID_ = 0;
1622         /* g_print( "addrcompl_initialize...done\n" ); */
1623 }
1624
1625 /**
1626  * Teardown completion object.
1627  */
1628 void addrcompl_teardown( void ) {
1629         /* g_print( "addrcompl_teardown...\n" ); */
1630         addrcompl_free_window( _compWindow_ );
1631         _compWindow_ = NULL;
1632         if( _displayQueue_ ) {
1633                 g_list_free( _displayQueue_ );
1634         }
1635         _displayQueue_ = NULL;
1636         _completionIdleID_ = 0;
1637         /* g_print( "addrcompl_teardown...done\n" ); */
1638 }
1639
1640 /*
1641  * tree view functions
1642  */
1643
1644 static GtkListStore *addr_compl_create_store(void)
1645 {
1646         return gtk_list_store_new(N_ADDR_COMPL_COLUMNS,
1647                                   GDK_TYPE_PIXBUF,
1648                                   G_TYPE_STRING,
1649                                   G_TYPE_BOOLEAN,
1650                                   G_TYPE_POINTER,
1651                                   -1);
1652 }
1653                                              
1654 static GtkWidget *addr_compl_list_view_create(CompletionWindow *window)
1655 {
1656         GtkTreeView *list_view;
1657         GtkTreeSelection *selector;
1658         GtkTreeModel *model;
1659
1660         model = GTK_TREE_MODEL(addr_compl_create_store());
1661         list_view = GTK_TREE_VIEW(gtk_tree_view_new_with_model(model));
1662         g_object_unref(model);  
1663         
1664         gtk_tree_view_set_rules_hint(list_view, prefs_common.use_stripes_everywhere);
1665         gtk_tree_view_set_headers_visible(list_view, FALSE);
1666         
1667         selector = gtk_tree_view_get_selection(list_view);
1668         gtk_tree_selection_set_mode(selector, GTK_SELECTION_BROWSE);
1669         gtk_tree_selection_set_select_function(selector, addr_compl_selected,
1670                                                window, NULL);
1671
1672         /* create the columns */
1673         addr_compl_create_list_view_columns(GTK_WIDGET(list_view));
1674
1675         return GTK_WIDGET(list_view);
1676 }
1677
1678 static void addr_compl_create_list_view_columns(GtkWidget *list_view)
1679 {
1680         GtkTreeViewColumn *column;
1681         GtkCellRenderer *renderer;
1682
1683         renderer = gtk_cell_renderer_pixbuf_new();
1684         column = gtk_tree_view_column_new_with_attributes
1685                 ("", renderer,
1686                  "pixbuf", ADDR_COMPL_ICON, NULL);
1687         gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);          
1688         renderer = gtk_cell_renderer_text_new();
1689         column = gtk_tree_view_column_new_with_attributes
1690                 ("", renderer, "text", ADDR_COMPL_ADDRESS, NULL);
1691         gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);          
1692 }
1693
1694 static gboolean list_view_button_press(GtkWidget *widget, GdkEventButton *event,
1695                                        CompletionWindow *window)
1696 {
1697         if (window && event && event->type == GDK_BUTTON_PRESS) {
1698                 window->in_mouse = TRUE;
1699         }
1700         return FALSE;
1701 }
1702
1703 static gboolean list_view_button_release(GtkWidget *widget, GdkEventButton *event,
1704                                          CompletionWindow *window)
1705 {
1706         if (window && event && event->type == GDK_BUTTON_RELEASE) {
1707                 window->in_mouse = FALSE;
1708         }
1709         return FALSE;
1710 }
1711
1712 static gboolean addr_compl_selected(GtkTreeSelection *selector,
1713                                     GtkTreeModel *model, 
1714                                     GtkTreePath *path,
1715                                     gboolean currently_selected,
1716                                     gpointer data)
1717 {
1718         CompletionWindow *window = data;
1719
1720         if (currently_selected)
1721                 return TRUE;
1722         
1723         if (!window->in_mouse)
1724                 return TRUE;
1725
1726         /* XXX: select the entry and kill window later... select is called before
1727          * any other mouse events handlers including the tree view internal one;
1728          * not using a time out would result in a crash. if this doesn't work
1729          * safely, maybe we should set variables when receiving button presses
1730          * in the tree view. */
1731         if (!window->destroying) {
1732                 window->destroying = TRUE;
1733                 g_idle_add((GSourceFunc) addr_compl_defer_select_destruct, data);
1734         }
1735
1736         return TRUE;
1737 }
1738
1739 static gboolean addr_compl_defer_select_destruct(CompletionWindow *window)
1740 {
1741         GtkEntry *entry = GTK_ENTRY(window->entry);
1742
1743         completion_window_apply_selection(GTK_TREE_VIEW(window->list_view), 
1744                                           entry, TRUE);
1745
1746         clear_completion_cache();
1747
1748         addrcompl_destroy_window(window);
1749         return FALSE;
1750 }
1751
1752
1753 /*
1754  * End of Source.
1755  */
1756