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