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