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