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