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