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