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