2a71384b8c84bba90094acc5ce0dbe19947310e5
[claws.git] / src / addr_compl.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  *
4  * Copyright (c) 2000-2001 by Alfons Hoogervorst <alfons@proteus.demon.nl>
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 2 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, write to the Free Software
18  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19  */
20
21 #ifdef HAVE_CONFIG_H
22 #  include "config.h"
23 #endif
24 #include "intl.h"
25 #include "defs.h"
26
27 #include <glib.h>
28 #include <gdk/gdkkeysyms.h>
29 #include <gtk/gtkmain.h>
30 #include <gtk/gtkwindow.h>
31 #include <gtk/gtkentry.h>
32 #include <gtk/gtkeditable.h>
33 #include <gtk/gtkclist.h>
34 #include <gtk/gtkscrolledwindow.h>
35
36 #include <string.h>
37 #include <ctype.h>
38 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
39 #  include <wchar.h>
40 #  include <wctype.h>
41 #endif
42
43 #include "xml.h"
44 #include "addr_compl.h"
45 #include "utils.h"
46 #include "addressbook.h"
47 #include "main.h"
48
49 #define LOG_MESSAGE \
50         debug_mode == 0 ? (debug_mode == debug_mode) : (void)debug_print 
51
52 /* How it works:
53  *
54  * The address book is read into memory. We set up an address list
55  * containing all address book entries. Next we make the completion
56  * list, which contains all the completable strings, and store a
57  * reference to the address entry it belongs to.
58  * After calling the g_completion_complete(), we get a reference
59  * to a valid email address.  
60  *
61  * Completion is very simplified. We never complete on another prefix,
62  * i.e. we neglect the next smallest possible prefix for the current
63  * completion cache. This is simply done so we might break up the
64  * addresses a little more (e.g. break up alfons@proteus.demon.nl into
65  * something like alfons, proteus, demon, nl; and then completing on
66  * any of those words).
67  */ 
68         
69 /* address_entry - structure which refers to the original address entry in the
70  * address book 
71  */
72 typedef struct
73 {
74         gchar *name;
75         gchar *address;
76 } address_entry;
77
78 /* completion_entry - structure used to complete addresses, with a reference
79  * the the real address information.
80  */
81 typedef struct
82 {
83         gchar           *string; /* string to complete */
84         address_entry   *ref;    /* address the string belongs to  */
85 } completion_entry;
86
87 /*******************************************************************************/
88
89 static gint         g_ref_count;        /* list ref count */
90 static GList       *g_completion_list;  /* list of strings to be checked */
91 static GList       *g_address_list;     /* address storage */
92 static GCompletion *g_completion;       /* completion object */
93
94 /* To allow for continuing completion we have to keep track of the state
95  * using the following variables. No need to create a context object. */
96
97 static gint         g_completion_count;         /* nr of addresses incl. the prefix */
98 static gint         g_completion_next;          /* next prev address */
99 static GSList      *g_completion_addresses;     /* unique addresses found in the
100                                                    completion cache. */
101 static gchar       *g_completion_prefix;        /* last prefix. (this is cached here
102                                                  * because the prefix passed to g_completion
103                                                  * is g_strdown()'ed */
104
105 /*******************************************************************************/
106
107 /* completion_func() - used by GTK to find the string data to be used for 
108  * completion 
109  */
110 static gchar *completion_func(gpointer data)
111 {
112         g_return_val_if_fail(data != NULL, NULL);
113
114         return ((completion_entry *)data)->string;
115
116
117 static void init_all(void)
118 {
119         g_completion = g_completion_new(completion_func);
120         g_return_if_fail(g_completion != NULL);
121 }
122
123 static void free_all(void)
124 {
125         GList *walk;
126         
127         walk = g_list_first(g_completion_list);
128         for (; walk != NULL; walk = g_list_next(walk)) {
129                 completion_entry *ce = (completion_entry *) walk->data;
130                 g_free(ce->string);
131                 g_free(walk->data);
132         }
133         g_list_free(g_completion_list);
134         g_completion_list = NULL;
135         
136         walk = g_address_list;
137         for (; walk != NULL; walk = g_list_next(walk)) {
138                 address_entry *ae = (address_entry *) walk->data;
139                 g_free(ae->name);
140                 g_free(ae->address);
141                 g_free(walk->data);
142         }
143         g_list_free(g_address_list);
144         g_address_list = NULL;
145         
146         g_completion_free(g_completion);
147         g_completion = NULL;
148 }
149
150 /* add_address() - adds address to the completion list. this function looks
151  * complicated, but it's only allocation checks.
152  */
153 static gint add_address(const gchar *name, const gchar *address)
154 {
155         address_entry    *ae;
156         completion_entry *ce1;
157         completion_entry *ce2;
158
159         if (!name || !address) return -1;
160
161         ae = g_new0(address_entry, 1);
162         ce1 = g_new0(completion_entry, 1),
163         ce2 = g_new0(completion_entry, 1);
164
165         g_return_val_if_fail(ae != NULL, -1);
166         g_return_val_if_fail(ce1 != NULL && ce2 != NULL, -1);   
167
168         ae->name    = g_strdup(name);
169         ae->address = g_strdup(address);                
170         ce1->string = g_strdup(name);
171         ce2->string = g_strdup(address);
172
173         /* GCompletion list is case sensitive */
174         g_strdown(ce2->string);
175         g_strdown(ce1->string);
176         ce1->ref = ce2->ref = ae;
177
178         g_completion_list = g_list_append(g_completion_list, ce1);
179         g_completion_list = g_list_append(g_completion_list, ce2);
180         g_address_list    = g_list_append(g_address_list,    ae);
181
182         return 0;
183 }
184
185 static gboolean get_all_addresses(GNode *node, gpointer ae)
186 {
187         XMLNode *xmlnode = (XMLNode *)node->data;
188         address_entry *addr = (address_entry *)ae;
189
190         /* this simply checks if tag is "item". in that case, it
191          * verifies it has already seen an item. if it did, an
192          * address retrieval was complete */
193         if (!strcmp(xmlnode->tag->tag, "item")) {
194                 /* see if a previous item was complete */
195                 /* TODO: does sylpheed address book allow empty names to be entered?
196                  * if so, addr->name *AND* addr->address should be checked. */
197                 /* add address to our database */
198                 add_address(addr->name, addr->address);
199                 g_free(addr->name);
200                 g_free(addr->address);
201                 addr->name = NULL;
202                 addr->address = NULL;
203         } else if (!strcmp(xmlnode->tag->tag, "name"))
204                 addr->name = g_strdup(xmlnode->element);
205         else if (!strcmp(xmlnode->tag->tag, "address"))
206                 addr->address = g_strdup(xmlnode->element);
207
208         return FALSE;
209 }
210
211 /* read_address_book()
212  */ 
213 static void read_address_book(void)
214 {       
215         gchar *path;
216         GNode *tree; 
217         address_entry ad = {NULL, NULL};
218
219         LOG_MESSAGE( _("%s%d entering read_address_book\n"), __FILE__, __LINE__);
220         path = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, ADDRESS_BOOK, NULL);
221         tree = xml_parse_file(path);
222         g_free(path);
223         if (!tree) {
224                 LOG_MESSAGE( _("%s(%d) no addressbook\n"), __FILE__, __LINE__);
225                 return;
226         }
227
228         /* retrieve all addresses */
229         g_node_traverse(tree, G_PRE_ORDER, G_TRAVERSE_ALL, -1,
230                         (GNodeTraverseFunc) get_all_addresses, &ad);
231         /* still one pending? */
232         if (ad.name) {
233                 add_address(ad.name, ad.address);
234                 if (ad.name)
235                         g_free(ad.name);
236                 if (ad.address)
237                         g_free(ad.address);
238         }
239
240         xml_free_tree(tree);
241
242         LOG_MESSAGE(_("%s(%d) leaving read_address_book - OK\n"), __FILE__, __LINE__);
243 }
244
245 /* start_address_completion() - returns the number of addresses 
246  * that should be matched for completion.
247  */
248 gint start_address_completion(void)
249 {
250         clear_completion_cache();
251         if (!g_ref_count) {
252                 init_all();
253                 /* open the address book */
254                 read_address_book();
255                 /* merge the completion entry list into g_completion */
256                 if (g_completion_list)
257                         g_completion_add_items(g_completion, g_completion_list);
258         }
259         g_ref_count++;
260         LOG_MESSAGE("start_address_completion ref count %d\n", g_ref_count);
261
262         return g_list_length(g_completion_list);
263 }
264
265 /* get_address_from_edit() - returns a possible address (or a part)
266  * from an entry box. To make life easier, we only look at the last valid address 
267  * component; address completion only works at the last string component in
268  * the entry box. 
269  */ 
270 gchar *get_address_from_edit(GtkEntry *entry, gint *start_pos)
271 {
272         const gchar *edit_text;
273         gint cur_pos;
274         wchar_t *wtext;
275         wchar_t *wp;
276         wchar_t rfc_mail_sep;
277         gchar *str;
278
279         edit_text = gtk_entry_get_text(entry);
280         if (edit_text == NULL) return NULL;
281
282         wtext = strdup_mbstowcs(edit_text);
283         g_return_val_if_fail(wtext != NULL, NULL);
284
285         cur_pos = gtk_editable_get_position(GTK_EDITABLE(entry));
286
287         if (mbtowc(&rfc_mail_sep, ",", 1) < 0) {
288                 g_free(wtext);
289                 return NULL;
290         }
291
292         /* scan for a separator. doesn't matter if walk points at null byte. */
293         for (wp = wtext + cur_pos; wp > wtext && *wp != rfc_mail_sep; wp--)
294                 ;
295
296         /* have something valid */
297         if (wcslen(wp) == 0) {
298                 g_free(wtext);
299                 return NULL;
300         }
301
302 #define IS_VALID_CHAR(x)        (iswalnum(x) || ((x) > 0x7f))
303
304         /* now scan back until we hit a valid character */
305         for (; *wp && !IS_VALID_CHAR(*wp); wp++)
306                 ;
307
308 #undef IS_VALID_CHAR
309
310         if (wcslen(wp) == 0) {
311                 g_free(wtext);
312                 return NULL;
313         }
314
315         if (start_pos) *start_pos = wp - wtext;
316
317         str = strdup_wcstombs(wp);
318         g_free(wtext);
319
320         return str;
321
322
323 /* replace_address_in_edit() - replaces an incompleted address with a completed one.
324  */
325 void replace_address_in_edit(GtkEntry *entry, const gchar *newtext,
326                              gint start_pos)
327 {
328         gtk_editable_delete_text(GTK_EDITABLE(entry), start_pos, -1);
329         gtk_editable_insert_text(GTK_EDITABLE(entry), newtext, strlen(newtext),
330                                  &start_pos);
331         gtk_editable_set_position(GTK_EDITABLE(entry), -1);
332 }
333
334 /* complete_address() - tries to complete an addres, and returns the
335  * number of addresses found. use get_complete_address() to get one.
336  * returns zero if no match was found, otherwise the number of addresses,
337  * with the original prefix at index 0. 
338  */
339 guint complete_address(const gchar *str)
340 {
341         GList *result;
342         gchar *d;
343         guint  count, cpl;
344         completion_entry *ce;
345
346         g_return_val_if_fail(str != NULL, 0);
347
348         Xstrdup_a(d, str, return 0);
349
350         clear_completion_cache();
351         g_completion_prefix = g_strdup(str);
352
353         /* g_completion is case sensitive */
354         g_strdown(d);
355         result = g_completion_complete(g_completion, d, NULL);
356
357         count = g_list_length(result);
358         if (count) {
359                 /* create list with unique addresses  */
360                 for (cpl = 0, result = g_list_first(result);
361                      result != NULL;
362                      result = g_list_next(result)) {
363                         ce = (completion_entry *)(result->data);
364                         if (NULL == g_slist_find(g_completion_addresses,
365                                                  ce->ref)) {
366                                 cpl++;
367                                 g_completion_addresses =
368                                         g_slist_append(g_completion_addresses,
369                                                        ce->ref);
370                         }
371                 }
372                 count = cpl + 1;        /* index 0 is the original prefix */
373                 g_completion_next = 1;  /* we start at the first completed one */
374         } else {
375                 g_free(g_completion_prefix);
376                 g_completion_prefix = NULL;
377         }
378
379         g_completion_count = count;
380         return count;
381 }
382
383 /* get_complete_address() - returns a complete address. the returned
384  * string should be freed 
385  */
386 gchar *get_complete_address(gint index)
387 {
388         const address_entry *p;
389         
390         if (index < g_completion_count) {
391                 if (index == 0)
392                         return g_strdup(g_completion_prefix);
393                 else {
394                         /* get something from the unique addresses */
395                         p = (address_entry *)g_slist_nth_data
396                                 (g_completion_addresses, index - 1);
397                         if (p == NULL)
398                                 return NULL;
399                         else
400                                 return g_strdup_printf
401                                         ("%s <%s>", p->name, p->address);
402                 }
403         } else
404                 return NULL;
405 }
406
407 gchar *get_next_complete_address(void)
408 {
409         if (is_completion_pending()) {
410                 gchar *res;
411
412                 res = get_complete_address(g_completion_next);
413                 g_completion_next += 1;
414                 if (g_completion_next >= g_completion_count)
415                         g_completion_next = 0;
416
417                 return res;
418         } else
419                 return NULL;
420 }
421
422 gchar *get_prev_complete_address(void)
423 {
424         if (is_completion_pending()) {
425                 int n = g_completion_next - 2;
426
427                 /* real previous */
428                 n = (n + (g_completion_count * 5)) % g_completion_count;
429
430                 /* real next */
431                 g_completion_next = n + 1;
432                 if (g_completion_next >=  g_completion_count)
433                         g_completion_next = 0;
434                 return get_complete_address(n);
435         } else
436                 return NULL;
437 }
438
439 guint get_completion_count(void)
440 {
441         if (is_completion_pending)
442                 return g_completion_count;
443         else
444                 return 0;
445 }
446
447 /* should clear up anything after complete_address() */
448 void clear_completion_cache(void)
449 {
450         if (is_completion_pending()) {
451                 if (g_completion_prefix)
452                         g_free(g_completion_prefix);
453
454                 if (g_completion_addresses) {
455                         g_slist_free(g_completion_addresses);
456                         g_completion_addresses = NULL;
457                 }
458
459                 g_completion_count = g_completion_next = 0;
460         }
461 }
462
463 gboolean is_completion_pending(void)
464 {
465         /* check if completion pending, i.e. we might satisfy a request for the next
466          * or previous address */
467          return g_completion_count;
468 }
469
470 /* invalidate_address_completion() - should be called if address book
471  * changed; 
472  */
473 gint invalidate_address_completion(void)
474 {
475         if (g_ref_count) {
476                 /* simply the same as start_address_completion() */
477                 LOG_MESSAGE("Invalidation request for address completion\n");
478                 free_all();
479                 init_all();
480                 read_address_book();
481                 g_completion_add_items(g_completion, g_completion_list);
482                 clear_completion_cache();
483         }
484
485         return g_list_length(g_completion_list);
486 }
487
488 gint end_address_completion(void)
489 {
490         clear_completion_cache();
491
492         if (0 == --g_ref_count)
493                 free_all();
494
495         LOG_MESSAGE("end_address_completion ref count %d\n", g_ref_count);
496
497         return g_ref_count; 
498 }
499
500
501 /* address completion entry ui. the ui (completion list was inspired by galeon's
502  * auto completion list). remaining things powered by sylpheed's completion engine.
503  */
504
505 #define ENTRY_DATA_TAB_HOOK     "tab_hook"                      /* used to lookup entry */
506 #define WINDOW_DATA_COMPL_ENTRY "compl_entry"   /* used to store entry for compl. window */
507 #define WINDOW_DATA_COMPL_CLIST "compl_clist"   /* used to store clist for compl. window */
508
509 static void address_completion_mainwindow_set_focus     (GtkWindow   *window,
510                                                          GtkWidget   *widget,
511                                                          gpointer     data);
512 static gboolean address_completion_entry_key_pressed    (GtkEntry    *entry,
513                                                          GdkEventKey *ev,
514                                                          gpointer     data);
515 static gboolean address_completion_complete_address_in_entry
516                                                         (GtkEntry    *entry,
517                                                          gboolean     next);
518 static void address_completion_create_completion_window (GtkEntry    *entry);
519
520 static void completion_window_select_row(GtkCList        *clist,
521                                          gint             row,
522                                          gint             col,
523                                          GdkEvent        *event,
524                                          GtkWidget      **completion_window);
525 static gboolean completion_window_button_press
526                                         (GtkWidget       *widget,
527                                          GdkEventButton  *event,
528                                          GtkWidget      **completion_window);
529 static gboolean completion_window_key_press
530                                         (GtkWidget       *widget,
531                                          GdkEventKey     *event,
532                                          GtkWidget      **completion_window);
533
534
535 static void completion_window_advance_to_row(GtkCList *clist, gint row)
536 {
537         g_return_if_fail(row < g_completion_count);
538         gtk_clist_select_row(clist, row, 0);
539 }
540
541 static void completion_window_advance_selection(GtkCList *clist, gboolean forward)
542 {
543         int row;
544
545         g_return_if_fail(clist != NULL);
546         g_return_if_fail(clist->selection != NULL);
547
548         row = GPOINTER_TO_INT(clist->selection->data);
549
550         row = forward ? (row + 1) % g_completion_count :
551                         (row - 1) < 0 ? g_completion_count - 1 : row - 1;
552
553         gtk_clist_freeze(clist);
554         completion_window_advance_to_row(clist, row);                                   
555         gtk_clist_thaw(clist);
556 }
557
558 /* completion_window_accept_selection() - accepts the current selection in the
559  * clist, and destroys the window */
560 static void completion_window_accept_selection(GtkWidget **window,
561                                                GtkCList *clist,
562                                                GtkEntry *entry)
563 {
564         gchar *address = NULL, *text = NULL;
565         gint   cursor_pos, row, col;
566
567         g_return_if_fail(window != NULL);
568         g_return_if_fail(*window != NULL);
569         g_return_if_fail(clist != NULL);
570         g_return_if_fail(entry != NULL);
571         g_return_if_fail(clist->selection != NULL);
572
573         col = 0;
574
575         /* FIXME: I believe it's acceptable to access the selection member directly  */
576         row = GPOINTER_TO_INT(clist->selection->data);
577
578         /* we just need the cursor position */
579         address = get_address_from_edit(entry, &cursor_pos);
580         gtk_clist_get_text(clist, row, col, &text);
581         replace_address_in_edit(entry, text, cursor_pos);
582         g_free(address);                                
583
584         clear_completion_cache();
585         gtk_widget_destroy(*window);
586         *window = NULL;
587 }
588
589 /* should be called when creating the main window containing address
590  * completion entries */
591 void address_completion_start(GtkWidget *mainwindow)
592 {
593         start_address_completion();
594
595         /* register focus change hook */
596         gtk_signal_connect(GTK_OBJECT(mainwindow), "set_focus",
597                            GTK_SIGNAL_FUNC(address_completion_mainwindow_set_focus),
598                            mainwindow);
599 }
600
601 void address_completion_register_entry(GtkEntry *entry)
602 {
603         g_return_if_fail(entry != NULL);
604         g_return_if_fail(GTK_IS_ENTRY(entry));
605
606         /* add hooked property */
607         gtk_object_set_data(GTK_OBJECT(entry), ENTRY_DATA_TAB_HOOK, entry);
608
609         /* add keypress event */
610         gtk_signal_connect_full(GTK_OBJECT(entry), "key_press_event",
611                                 GTK_SIGNAL_FUNC(address_completion_entry_key_pressed),
612                                 NULL,
613                                 NULL,
614                                 NULL,
615                                 0,
616                                 0); /* magic */
617 }
618
619 /* should be called when main window with address completion entries
620  * terminates */
621 void address_completion_end(GtkWidget *mainwindow)
622 {
623         /* if address_completion_end() is really called on closing the window,
624          * we don't need to unregister the set_focus_cb */
625         end_address_completion();
626 }
627
628 /* if focus changes to another entry, then clear completion cache */
629 static void address_completion_mainwindow_set_focus(GtkWindow *window,
630                                                     GtkWidget *widget,
631                                                     gpointer   data)
632 {
633         if (widget)
634                 clear_completion_cache();
635 }
636
637 /* watch for tabs in one of the address entries. if no tab then clear the
638  * completion cache */
639 static gboolean address_completion_entry_key_pressed(GtkEntry    *entry,
640                                                      GdkEventKey *ev,
641                                                      gpointer     data)
642 {
643         if (ev->keyval == GDK_Tab) {
644                 if (address_completion_complete_address_in_entry(entry, TRUE)) {
645                         address_completion_create_completion_window(entry);
646                         /* route a void character to the default handler */
647                         /* this is a dirty hack; we're actually changing a key
648                          * reported by the system. */
649                         ev->keyval = GDK_AudibleBell_Enable;
650                         ev->state &= ~GDK_SHIFT_MASK;
651                         gtk_signal_emit_stop_by_name(GTK_OBJECT(entry),
652                                                      "key_press_event");
653                 } else {
654                         /* old behaviour */
655                 }
656         } else if (ev->keyval == GDK_Shift_L
657                 || ev->keyval == GDK_Shift_R
658                 || ev->keyval == GDK_Control_L
659                 || ev->keyval == GDK_Control_R
660                 || ev->keyval == GDK_Caps_Lock
661                 || ev->keyval == GDK_Shift_Lock
662                 || ev->keyval == GDK_Meta_L
663                 || ev->keyval == GDK_Meta_R
664                 || ev->keyval == GDK_Alt_L
665                 || ev->keyval == GDK_Alt_R) {
666                 /* these buttons should not clear the cache... */
667         } else
668                 clear_completion_cache();
669
670         return TRUE;
671 }
672
673 /* initialize the completion cache and put first completed string
674  * in entry. this function used to do back cycling but this is not
675  * currently used. since the address completion behaviour has been
676  * changed regularly, we keep the feature in case someone changes
677  * his / her mind again. :) */
678 static gboolean address_completion_complete_address_in_entry(GtkEntry *entry,
679                                                              gboolean  next)
680 {
681         gint ncount, cursor_pos;
682         gchar *address, *new = NULL;
683         gboolean completed = FALSE;
684
685         g_return_val_if_fail(entry != NULL, FALSE);
686
687         if (!GTK_WIDGET_HAS_FOCUS(entry)) return FALSE;
688
689         /* get an address component from the cursor */
690         if (0 != (address = get_address_from_edit(entry, &cursor_pos))) {
691                 /* still something in the cache */
692                 if (is_completion_pending()) {
693                         new = next ? get_next_complete_address() :
694                                 get_prev_complete_address();
695                 } else {
696                         if (0 < (ncount = complete_address(address)))
697                                 new = get_next_complete_address();
698                 }
699
700                 if (new) {
701                         /* prevent "change" signal */
702                         replace_address_in_edit(entry, new, cursor_pos);
703                         g_free(new);
704                         completed = TRUE;
705                 }
706
707                 g_free(address);
708         }                                       
709
710         return completed;
711 }
712
713 static void address_completion_create_completion_window(GtkEntry *entry_)
714 {
715         static GtkWidget *completion_window;
716         gint x, y, height, width, depth;
717         GtkWidget *scroll, *clist;
718         GtkRequisition r;
719         guint count = 0;
720         GtkWidget *entry = GTK_WIDGET(entry_);
721
722         if (completion_window) {
723                 gtk_widget_destroy(completion_window);
724                 completion_window = NULL;
725         }
726
727         scroll = gtk_scrolled_window_new(NULL, NULL);
728         clist  = gtk_clist_new(1);
729         gtk_clist_set_selection_mode(GTK_CLIST(clist), GTK_SELECTION_SINGLE);
730         
731         completion_window = gtk_window_new(GTK_WINDOW_POPUP);
732
733         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
734                                        GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
735         gtk_container_add(GTK_CONTAINER(completion_window), scroll);
736         gtk_container_add(GTK_CONTAINER(scroll), clist);
737
738         /* set the unique data so we can always get back the entry and
739          * clist window to which this completion window has been attached */
740         gtk_object_set_data(GTK_OBJECT(completion_window),
741                             WINDOW_DATA_COMPL_ENTRY, entry_);
742         gtk_object_set_data(GTK_OBJECT(completion_window),
743                             WINDOW_DATA_COMPL_CLIST, clist);
744
745         gtk_signal_connect(GTK_OBJECT(clist), "select_row",
746                            GTK_SIGNAL_FUNC(completion_window_select_row),
747                            &completion_window);
748
749         for (count = 0; count < get_completion_count(); count++) {
750                 gchar *text[] = {NULL, NULL};
751
752                 text[0] = get_complete_address(count);
753                 gtk_clist_append(GTK_CLIST(clist), text);
754                 g_free(text[0]);
755         }
756
757         gdk_window_get_geometry(entry->window, &x, &y, &width, &height, &depth);
758         gdk_window_get_deskrelative_origin (entry->window, &x, &y);
759         y += height;
760         gtk_widget_set_uposition(completion_window, x, y);
761
762         gtk_widget_size_request(clist, &r);
763         gtk_widget_set_usize(completion_window, width, r.height);
764         gtk_widget_show_all(completion_window);
765         gtk_widget_size_request(clist, &r);
766
767         if ((y + r.height) > gdk_screen_height()) {
768                 gtk_window_set_policy(GTK_WINDOW(completion_window),
769                                       TRUE, FALSE, FALSE);
770                 gtk_widget_set_usize(completion_window, width,
771                                      gdk_screen_height () - y);
772         }
773
774         gtk_signal_connect(GTK_OBJECT(completion_window),
775                            "button-press-event",
776                            GTK_SIGNAL_FUNC(completion_window_button_press),
777                            &completion_window);
778         gtk_signal_connect(GTK_OBJECT(completion_window),
779                            "key-press-event",
780                            GTK_SIGNAL_FUNC(completion_window_key_press),
781                            &completion_window);
782         gdk_pointer_grab(completion_window->window, TRUE,
783                          GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK |
784                          GDK_BUTTON_RELEASE_MASK,
785                          NULL, NULL, GDK_CURRENT_TIME);
786         gtk_grab_add(completion_window);
787
788         /* this gets rid of the irritating focus rectangle that doesn't
789          * follow the selection */
790         GTK_WIDGET_UNSET_FLAGS(clist, GTK_CAN_FOCUS);
791         gtk_clist_select_row(GTK_CLIST(clist), 1, 0);
792 }
793
794
795 /* row selection sends completed address to entry.
796  * note: event is NULL if selected by anything else than a mouse button. */
797 static void completion_window_select_row(GtkCList *clist, gint row, gint col,
798                                          GdkEvent *event,
799                                          GtkWidget **completion_window)
800 {
801         GtkEntry *entry;
802
803         /* first check if it's anything but a mouse event. Mouse events
804          * accept the completion. Anything else is accepted by the
805          * completion_window_key_press() */
806         if (!event) {
807                 /* event == NULL if key press did the selection or just
808                  * event emitted with signal_emit_XXX(). This seems to 
809                  * be the case for the gtk versions I have seen */
810                 return;
811         }
812
813         /* however, a future version of GTK might pass the event type
814          * that triggered the select_row. since this event handler
815          * only wants mouse clicks, we check for that. */
816         if (event->type != GDK_BUTTON_RELEASE) {
817                 return;
818         }
819
820         g_return_if_fail(completion_window != NULL);
821         g_return_if_fail(*completion_window != NULL);
822
823         entry = GTK_ENTRY(gtk_object_get_data(GTK_OBJECT(*completion_window),
824                                               WINDOW_DATA_COMPL_ENTRY));
825         g_return_if_fail(entry != NULL);
826
827         completion_window_accept_selection(completion_window, clist, entry);    
828 }
829
830 /* completion_window_button_press() - check is mouse click is anywhere
831  * else (not in the completion window). in that case the completion
832  * window is destroyed, and the original prefix is restored */
833 static gboolean completion_window_button_press(GtkWidget *widget,
834                                                GdkEventButton *event,
835                                                GtkWidget **completion_window)
836 {
837         GtkWidget *event_widget, *entry;
838         gchar *prefix;
839         gint cursor_pos;
840         gboolean restore = TRUE;
841
842         g_return_val_if_fail(completion_window != NULL, FALSE);
843         g_return_val_if_fail(*completion_window != NULL, FALSE);
844
845         entry = GTK_WIDGET(gtk_object_get_data(GTK_OBJECT(*completion_window),
846                                                WINDOW_DATA_COMPL_ENTRY));
847         g_return_val_if_fail(entry != NULL, FALSE);
848
849         event_widget = gtk_get_event_widget((GdkEvent *)event);
850         if (event_widget != widget) {
851                 while (event_widget) {
852                         if (event_widget == widget)
853                                 return FALSE;
854                         else if (event_widget == entry) {
855                                 restore = FALSE;
856                                 break;
857                         }
858                     event_widget = event_widget->parent;
859                 }
860         }
861
862         if (restore) {
863                 prefix = get_complete_address(0);
864                 g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
865                 replace_address_in_edit(GTK_ENTRY(entry), prefix, cursor_pos);
866         }
867
868         gtk_widget_destroy(*completion_window);
869         *completion_window = NULL;
870
871         clear_completion_cache();
872         return TRUE;
873 }
874
875 static gboolean completion_window_key_press(GtkWidget *widget,
876                                             GdkEventKey *event,
877                                             GtkWidget **completion_window)
878 {
879         GdkEventKey tmp_event;
880         GtkWidget *entry;
881         gchar *prefix;
882         gint cursor_pos;
883         GtkWidget *clist;
884
885         g_return_val_if_fail(completion_window != NULL, FALSE);
886         g_return_val_if_fail(*completion_window != NULL, FALSE);
887
888         entry = GTK_WIDGET(gtk_object_get_data(GTK_OBJECT(*completion_window),
889                                                WINDOW_DATA_COMPL_ENTRY));
890         clist = GTK_WIDGET(gtk_object_get_data(GTK_OBJECT(*completion_window),
891                                                WINDOW_DATA_COMPL_CLIST));
892         g_return_val_if_fail(entry != NULL, FALSE);
893
894         /* allow keyboard navigation in the alternatives clist */
895         if (event->keyval == GDK_Up || event->keyval == GDK_Down ||
896             event->keyval == GDK_Page_Up || event->keyval == GDK_Page_Down) {
897                 completion_window_advance_selection
898                         (GTK_CLIST(clist),
899                          event->keyval == GDK_Down ||
900                          event->keyval == GDK_Page_Down ? TRUE : FALSE);
901                 return FALSE;
902         }               
903
904         /* also make tab / shift tab go to next previous completion entry. we're
905          * changing the key value */
906         if (event->keyval == GDK_Tab || event->keyval == GDK_ISO_Left_Tab) {
907                 event->keyval = (event->state & GDK_SHIFT_MASK)
908                         ? GDK_Up : GDK_Down;
909                 /* need to reset shift state if going up */
910                 if (event->state & GDK_SHIFT_MASK)
911                         event->state &= ~GDK_SHIFT_MASK;
912                 completion_window_advance_selection(GTK_CLIST(clist), 
913                         event->keyval == GDK_Down ? TRUE : FALSE);
914                 return FALSE;
915         }
916
917         /* look for presses that accept the selection */
918         if (event->keyval == GDK_Return || event->keyval == GDK_space) {
919                 completion_window_accept_selection(completion_window,
920                                                    GTK_CLIST(clist),
921                                                    GTK_ENTRY(entry));
922                 return FALSE;
923         }
924
925         /* key state keys should never be handled */
926         if (event->keyval == GDK_Shift_L
927                  || event->keyval == GDK_Shift_R
928                  || event->keyval == GDK_Control_L
929                  || event->keyval == GDK_Control_R
930                  || event->keyval == GDK_Caps_Lock
931                  || event->keyval == GDK_Shift_Lock
932                  || event->keyval == GDK_Meta_L
933                  || event->keyval == GDK_Meta_R
934                  || event->keyval == GDK_Alt_L
935                  || event->keyval == GDK_Alt_R) {
936                 return FALSE;
937         }
938
939         /* other key, let's restore the prefix (orignal text) */
940         prefix = get_complete_address(0);
941         g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
942         replace_address_in_edit(GTK_ENTRY(entry), prefix, cursor_pos);
943         g_free(prefix);
944         clear_completion_cache();
945
946         /* make sure anything we typed comes in the edit box */
947         tmp_event.type       = event->type;
948         tmp_event.window     = entry->window;
949         tmp_event.send_event = TRUE;
950         tmp_event.time       = event->time;
951         tmp_event.state      = event->state;
952         tmp_event.keyval     = event->keyval;
953         tmp_event.length     = event->length;
954         tmp_event.string     = event->string;
955         gtk_widget_event(entry, (GdkEvent *)&tmp_event);
956
957         /* and close the completion window */
958         gtk_widget_destroy(*completion_window);
959         *completion_window = NULL;
960
961         return TRUE;
962 }