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