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