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