8a1ee9502203e2fa6ee39dcbedd64ec1404744c5
[claws.git] / src / addr_compl.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  *
4  * Copyright (c) 2000-2003 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 #include "addritem.h"
47 #include "addrquery.h"
48 #include <pthread.h>
49
50 /* How it works:
51  *
52  * The address book is read into memory. We set up an address list
53  * containing all address book entries. Next we make the completion
54  * list, which contains all the completable strings, and store a
55  * reference to the address entry it belongs to.
56  * After calling the g_completion_complete(), we get a reference
57  * to a valid email address.  
58  *
59  * Completion is very simplified. We never complete on another searchTerm,
60  * i.e. we neglect the next smallest possible searchTerm for the current
61  * completion cache. This is simply done so we might break up the
62  * addresses a little more (e.g. break up alfons@proteus.demon.nl into
63  * something like alfons, proteus, demon, nl; and then completing on
64  * any of those words).
65  */
66
67 typedef struct _CompletionWindow CompletionWindow;
68 struct _CompletionWindow {
69         gint      listCount;
70         gchar     *searchTerm;
71         GtkWidget *window;
72         GtkWidget *entry;
73         GtkWidget *clist;
74 };
75
76 /**
77  * Current query ID.
78  */
79 static gint _queryID_ = 0;
80
81 /**
82  * Completion idle ID.
83  */
84 static gint _completionIdleID_ = 0;
85
86 /**
87  * Completion window.
88  */
89 static CompletionWindow *_compWindow_ = NULL;
90
91 /**
92  * Mutex to protect callback from multiple threads.
93  */
94 static pthread_mutex_t _completionMutex_ = PTHREAD_MUTEX_INITIALIZER;
95
96 /**
97  * Completion queue list.
98  */
99 static GList *_displayQueue_ = NULL;
100
101 /**
102  * Create a completion window object.
103  * \return Initialized completion window.
104  */
105 static CompletionWindow *addrcompl_create_window( void ) {
106         CompletionWindow *cw;
107
108         cw = g_new0( CompletionWindow, 1 );
109         cw->listCount = 0;
110         cw->searchTerm = NULL;
111         cw->window = NULL;
112         cw->entry = NULL;
113         cw->clist = NULL;
114
115         return cw;      
116 }
117
118 /**
119  * Destroy completion window.
120  * \param cw Window to destroy.
121  */
122 static void addrcompl_destroy_window( CompletionWindow *cw ) {
123         /* Remove idler function... or application may not terminate */
124         if( _completionIdleID_ != 0 ) {
125                 gtk_idle_remove( _completionIdleID_ );
126                 _completionIdleID_ = 0;
127         }
128
129         /* Now destroy window */        
130         if( cw ) {
131                 /* Clear references to widgets */
132                 cw->entry = NULL;
133                 cw->clist = NULL;
134
135                 /* Free objects */
136                 if( cw->window ) {
137                         gtk_widget_hide( cw->window );
138                         gtk_widget_destroy( cw->window );
139                 }
140                 cw->window = NULL;
141         }
142 }
143
144 /**
145  * Free up completion window.
146  * \param cw Window to free.
147  */
148 static void addrcompl_free_window( CompletionWindow *cw ) {
149         /* printf( "addrcompl_free_window...\n" ); */
150         if( cw ) {
151                 addrcompl_destroy_window( cw );
152
153                 g_free( cw->searchTerm );
154                 cw->searchTerm = NULL;
155
156                 /* Clear references */          
157                 cw->listCount = 0;
158
159                 /* Free object */               
160                 g_free( cw );
161         }
162         /* printf( "addrcompl_free_window...done\n" ); */
163 }
164
165 /**
166  * Retrieve a possible address (or a part) from an entry box. To make life
167  * easier, we only look at the last valid address component; address
168  * completion only works at the last string component in the entry box.
169  *
170  * \param entry Address entry field.
171  * \param start_pos Address of start position of address.
172  * \return Possible address.
173  */ 
174 static gchar *get_address_from_edit(GtkEntry *entry, gint *start_pos)
175 {
176         const gchar *edit_text;
177         gint cur_pos;
178         wchar_t *wtext;
179         wchar_t *wp;
180         wchar_t rfc_mail_sep;
181         wchar_t quote;
182         wchar_t lt;
183         wchar_t gt;
184         gboolean in_quote = FALSE;
185         gboolean in_bracket = FALSE;
186         gchar *str;
187
188         if (mbtowc(&rfc_mail_sep, ",", 1) < 0) return NULL;
189         if (mbtowc(&quote, "\"", 1) < 0) return NULL;
190         if (mbtowc(&lt, "<", 1) < 0) return NULL;
191         if (mbtowc(&gt, ">", 1) < 0) return NULL;
192
193         edit_text = gtk_entry_get_text(entry);
194         if (edit_text == NULL) return NULL;
195
196         wtext = strdup_mbstowcs(edit_text);
197         g_return_val_if_fail(wtext != NULL, NULL);
198
199         cur_pos = gtk_editable_get_position(GTK_EDITABLE(entry));
200
201         /* scan for a separator. doesn't matter if walk points at null byte. */
202         for (wp = wtext + cur_pos; wp > wtext; wp--) {
203                 if (*wp == quote)
204                         in_quote ^= TRUE;
205                 else if (!in_quote) {
206                         if (!in_bracket && *wp == rfc_mail_sep)
207                                 break;
208                         else if (*wp == gt)
209                                 in_bracket = TRUE;
210                         else if (*wp == lt)
211                                 in_bracket = FALSE;
212                 }
213         }
214
215         /* have something valid */
216         if (wcslen(wp) == 0) {
217                 g_free(wtext);
218                 return NULL;
219         }
220
221 #define IS_VALID_CHAR(x) \
222         (iswalnum(x) || (x) == quote || (x) == lt || ((x) > 0x7f))
223
224         /* now scan back until we hit a valid character */
225         for (; *wp && !IS_VALID_CHAR(*wp); wp++)
226                 ;
227
228 #undef IS_VALID_CHAR
229
230         if (wcslen(wp) == 0) {
231                 g_free(wtext);
232                 return NULL;
233         }
234
235         if (start_pos) *start_pos = wp - wtext;
236
237         str = strdup_wcstombs(wp);
238         g_free(wtext);
239
240         return str;
241 }
242
243 /**
244  * Replace text in entry field with specified address.
245  * \param entry     Address entry field.
246  * \param newtext   New text.
247  * \param start_pos Insertion point in entry field.
248  */
249 static void replace_address_in_edit(GtkEntry *entry, const gchar *newtext,
250                              gint start_pos)
251 {
252         if (!newtext) return;
253         gtk_editable_delete_text(GTK_EDITABLE(entry), start_pos, -1);
254         gtk_editable_insert_text(GTK_EDITABLE(entry), newtext, strlen(newtext),
255                                  &start_pos);
256         gtk_editable_set_position(GTK_EDITABLE(entry), -1);
257 }
258
259 /**
260  * Resize window to accommodate maximum number of address entries.
261  * \param cw Completion window.
262  */
263 static void addrcompl_resize_window( CompletionWindow *cw ) {
264         GtkRequisition r;
265         gint x, y, width, height, depth;
266
267         /* Get current geometry of window */
268         gdk_window_get_geometry( cw->window->window, &x, &y, &width, &height, &depth );
269
270         gtk_widget_size_request( cw->clist, &r );
271         gtk_widget_set_usize( cw->window, width, r.height );
272         gtk_widget_show_all( cw->window );
273         gtk_widget_size_request( cw->clist, &r );
274
275         /* Adjust window height to available screen space */
276         if( ( y + r.height ) > gdk_screen_height() ) {
277                 gtk_window_set_policy( GTK_WINDOW( cw->window ), TRUE, FALSE, FALSE );
278                 gtk_widget_set_usize( cw->window, width, gdk_screen_height() - y );
279         }
280 }
281
282 /**
283  * Add an address the completion window address list.
284  * \param cw Completion window.
285  * \param address Address to add.
286  */
287 static void addrcompl_add_entry( CompletionWindow *cw, gchar *address ) {
288         gchar *text[] = { NULL, NULL };
289
290         /* printf( "\t\tAdding :%s\n", address ); */
291         text[0] = address;
292         gtk_clist_append( GTK_CLIST(cw->clist), text );
293         cw->listCount++;
294
295         /* Resize window */
296         addrcompl_resize_window( cw );
297         gtk_grab_add( cw->window );
298
299         if( cw->listCount == 2 ) {
300                 /* Move off first row */
301                 gtk_clist_select_row( GTK_CLIST(cw->clist), 1, 0);
302         }
303 }
304
305 /**
306  * Completion idle function. This function is called by the main (UI) thread
307  * during UI idle time while an address search is in progress. Items from the
308  * display queue are processed and appended to the address list.
309  *
310  * \param data Target completion window to receive email addresses.
311  * \return <i>TRUE</i> to ensure that idle event do not get ignored.
312  */
313 static gboolean addrcompl_idle( gpointer data ) {
314         GList *node;
315         gchar *address;
316         CompletionWindow *cw;
317
318         /* Process all entries in display queue */
319         pthread_mutex_lock( & _completionMutex_ );
320         if( _displayQueue_ ) {
321                 cw = data;
322                 node = _displayQueue_;
323                 while( node ) {
324                         ItemEMail *email = node->data;
325                         /* printf( "email/address ::%s::\n", email->address ); */
326                         address = addritem_format_email( email );
327                         /* printf( "address ::: %s :::\n", address ); */
328                         addrcompl_add_entry( cw, address );
329                         g_free( address );
330                         node = g_list_next( node );
331                 }
332                 g_list_free( _displayQueue_ );
333                 _displayQueue_ = NULL;
334         }
335         pthread_mutex_unlock( & _completionMutex_ );
336
337         return TRUE;
338 }
339
340 /**
341  * Callback entry point. The background thread (if any) appends the address
342  * list to the display queue.
343  * \param queryID    Query ID of search request.
344  * \param listEMail  List of zero of more email objects that met search
345  *                   criteria.
346  * \param target     Target object to received data.
347  */
348 static gint addrcompl_callback(
349         gint queryID, GList *listEMail, gpointer target )
350 {
351         GList *node;
352         gchar *address;
353
354         pthread_mutex_lock( & _completionMutex_ );
355         if( queryID == _queryID_ ) {
356                 /* Append contents to end of display queue */
357                 node = listEMail;
358                 while( node ) {
359                         ItemEMail *email = node->data;
360                         if( target ) {
361                                 /*
362                                 printf( "\temail/address ::%s::\n", email->address );
363                                 */
364                                 _displayQueue_ = g_list_append( _displayQueue_, email );
365                         }
366                         node = g_list_next( node );
367                 }
368         }
369         pthread_mutex_unlock( & _completionMutex_ );
370 }
371
372 /**
373  * Start the search.
374  */
375 static void addrcompl_start_search( void ) {
376         gchar *searchTerm;
377
378         searchTerm = g_strdup( _compWindow_->searchTerm );
379
380         /* Clear out display queue */
381         pthread_mutex_lock( & _completionMutex_ );
382
383         g_list_free( _displayQueue_ );
384         _displayQueue_ = NULL;
385
386         pthread_mutex_unlock( & _completionMutex_ );
387
388         /* Setup the search */
389         _queryID_ = addressbook_setup_search(
390                 searchTerm, _compWindow_, addrcompl_callback );
391         g_free( searchTerm );
392
393         /* Sit back and wait until something happens */
394         _completionIdleID_ =
395                 gtk_idle_add( ( GtkFunction ) addrcompl_idle, _compWindow_ );
396         addressbook_start_search( _queryID_ );
397 }
398
399 /*
400  * address completion entry ui. the ui (completion list was inspired by galeon's
401  * auto completion list). remaining things powered by sylpheed's completion engine.
402  */
403
404 #define ENTRY_DATA_TAB_HOOK     "tab_hook"      /* used to lookup entry */
405
406 static gboolean address_completion_entry_key_pressed    (GtkEntry    *entry,
407                                                          GdkEventKey *ev,
408                                                          gpointer     data);
409 static gboolean address_completion_complete_address_in_entry
410                                                         (GtkEntry    *entry);
411
412 static void address_completion_create_completion_window (GtkEntry    *entry);
413
414 static void completion_window_select_row(GtkCList        *clist,
415                                          gint             row,
416                                          gint             col,
417                                          GdkEvent        *event,
418                                          CompletionWindow *compWin );
419
420 static gboolean completion_window_button_press
421                                         (GtkWidget       *widget,
422                                          GdkEventButton  *event,
423                                          CompletionWindow *compWin );
424
425 static gboolean completion_window_key_press
426                                         (GtkWidget       *widget,
427                                          GdkEventKey     *event,
428                                          CompletionWindow *compWin );
429
430
431 /**
432  * Advance selection to previous/next item in list.
433  * \param clist   List to process.
434  * \param forward Set to <i>TRUE</i> to select next or <i>FALSE</i> for
435  *                previous entry.
436  */
437 static void completion_window_advance_selection(GtkCList *clist, gboolean forward)
438 {
439         int row;
440
441         g_return_if_fail(clist != NULL);
442
443         if( clist->selection ) {
444                 row = GPOINTER_TO_INT(clist->selection->data);
445                 row = forward ? ( row + 1 ) : ( row - 1 );
446                 gtk_clist_freeze(clist);
447                 gtk_clist_select_row(clist, row, 0);
448                 gtk_clist_thaw(clist);
449         }
450 }
451
452 /**
453  * Apply the current selection in the list to the entry field. Focus is also
454  * moved to the next widget so that Tab key works correctly.
455  * \param clist List to process.
456  * \param entry Address entry field.
457  */
458 static void completion_window_apply_selection(GtkCList *clist, GtkEntry *entry)
459 {
460         gchar *address = NULL, *text = NULL;
461         gint   cursor_pos, row;
462         GtkWidget *parent;
463
464         g_return_if_fail(clist != NULL);
465         g_return_if_fail(entry != NULL);
466         g_return_if_fail(clist->selection != NULL);
467
468         /* First remove the idler */
469         if( _completionIdleID_ != 0 ) {
470                 gtk_idle_remove( _completionIdleID_ );
471                 _completionIdleID_ = 0;
472         }
473
474         /* Process selected item */
475         row = GPOINTER_TO_INT(clist->selection->data);
476
477         address = get_address_from_edit(entry, &cursor_pos);
478         g_free(address);
479         gtk_clist_get_text(clist, row, 0, &text);
480         replace_address_in_edit(entry, text, cursor_pos);
481
482         /* Move focus to next widget */
483         parent = GTK_WIDGET(entry)->parent;
484         if( parent ) {
485                 gtk_container_focus( GTK_CONTAINER(parent), GTK_DIR_TAB_FORWARD );
486         }
487
488 }
489
490 /**
491  * Listener that watches for tab or other keystroke in address entry field.
492  * \param entry Address entry field.
493  * \param ev    Event object.
494  * \param data  User data.
495  * \return <i>TRUE</i>.
496  */
497 static gboolean address_completion_entry_key_pressed(GtkEntry    *entry,
498                                                      GdkEventKey *ev,
499                                                      gpointer     data)
500 {
501         if (ev->keyval == GDK_Tab) {
502                 if (address_completion_complete_address_in_entry(entry)) {
503                         /* route a void character to the default handler */
504                         /* this is a dirty hack; we're actually changing a key
505                          * reported by the system. */
506                         ev->keyval = GDK_AudibleBell_Enable;
507                         ev->state &= ~GDK_SHIFT_MASK;
508                         gtk_signal_emit_stop_by_name(GTK_OBJECT(entry),
509                                                      "key_press_event");
510
511                         /* printf( "entry_key_pressed::create window\n" ); */
512                         address_completion_create_completion_window( entry );
513                         /* printf( "entry_key_pressed::create window...done\n" ); */
514                         addrcompl_start_search();
515                 }
516         }
517         return TRUE;
518 }
519
520 /**
521  * Initialize search term for address completion.
522  * \param entry Address entry field.
523  */
524 static gboolean address_completion_complete_address_in_entry( GtkEntry *entry )
525 {
526         gint cursor_pos;
527         gchar *searchTerm;
528
529         g_return_val_if_fail(entry != NULL, FALSE);
530
531         if (!GTK_WIDGET_HAS_FOCUS(entry)) return FALSE;
532
533         /* get an address component from the cursor */
534         searchTerm = get_address_from_edit( entry, &cursor_pos );
535         if (! searchTerm ) return FALSE;
536
537         /* Clear any existing search */
538         if( _compWindow_->searchTerm ) {
539                 g_free( _compWindow_->searchTerm );
540         }
541
542         /* Replace with new search term */
543         _compWindow_->searchTerm = searchTerm;
544
545         return TRUE;
546 }
547
548 /**
549  * Create new address completion window for specified entry.
550  * \param entry_ Entry widget to associate with window.
551  */
552 static void address_completion_create_completion_window( GtkEntry *entry_ )
553 {
554         gint x, y, height, width, depth;
555         GtkWidget *scroll, *clist;
556         GtkRequisition r;
557         GtkWidget *window;
558         GtkWidget *entry = GTK_WIDGET(entry_);
559         gchar *searchTerm;
560
561         /* Create new window and list */
562         window = gtk_window_new(GTK_WINDOW_POPUP);
563         clist  = gtk_clist_new(1);
564
565         /* Destroy any existing window */
566         addrcompl_destroy_window( _compWindow_ );
567
568         /* Create new object */
569         _compWindow_->window = window;
570         _compWindow_->entry = entry;
571         _compWindow_->clist = clist;
572         _compWindow_->listCount = 0;
573
574         scroll = gtk_scrolled_window_new(NULL, NULL);
575         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
576                                        GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
577         gtk_container_add(GTK_CONTAINER(window), scroll);
578         gtk_container_add(GTK_CONTAINER(scroll), clist);
579         gtk_clist_set_selection_mode(GTK_CLIST(clist), GTK_SELECTION_SINGLE);
580
581         /* Use entry widget to create initial window */
582         gdk_window_get_geometry(entry->window, &x, &y, &width, &height, &depth);
583         gdk_window_get_deskrelative_origin (entry->window, &x, &y);
584         y += height;
585         gtk_widget_set_uposition(window, x, y);
586
587         /* Resize window to fit initial (empty) address list */
588         gtk_widget_size_request( clist, &r );
589         gtk_widget_set_usize( window, width, r.height );
590         gtk_widget_show_all( window );
591         gtk_widget_size_request( clist, &r );
592
593         /* Setup handlers */
594         gtk_signal_connect(GTK_OBJECT(clist), "select_row",
595                            GTK_SIGNAL_FUNC(completion_window_select_row),
596                            _compWindow_ );
597         gtk_signal_connect(GTK_OBJECT(window),
598                            "button-press-event",
599                            GTK_SIGNAL_FUNC(completion_window_button_press),
600                            _compWindow_ );
601         gtk_signal_connect(GTK_OBJECT(window),
602                            "key-press-event",
603                            GTK_SIGNAL_FUNC(completion_window_key_press),
604                            _compWindow_ );
605         gdk_pointer_grab(window->window, TRUE,
606                          GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK |
607                          GDK_BUTTON_RELEASE_MASK,
608                          NULL, NULL, GDK_CURRENT_TIME);
609         gtk_grab_add( window );
610
611         /* this gets rid of the irritating focus rectangle that doesn't
612          * follow the selection */
613         GTK_WIDGET_UNSET_FLAGS(clist, GTK_CAN_FOCUS);
614
615         /* Add first entry into address list */
616         searchTerm = g_strdup( _compWindow_->searchTerm );
617         addrcompl_add_entry( _compWindow_, searchTerm );
618         gtk_clist_select_row(GTK_CLIST(clist), 0, 0);
619
620         g_free( searchTerm );
621 }
622
623 /**
624  * Respond to select row event in clist object. selection sends completed
625  * address to entry. Note: event is NULL if selected by anything else than a
626  * mouse button.
627  * \param widget   Window object.
628  * \param event    Event.
629  * \param compWind Reference to completion window.
630  */
631 static void completion_window_select_row(GtkCList *clist, gint row, gint col,
632                                          GdkEvent *event,
633                                          CompletionWindow *compWin )
634 {
635         GtkEntry *entry;
636
637         g_return_if_fail(compWin != NULL);
638
639         entry = GTK_ENTRY(compWin->entry);
640         g_return_if_fail(entry != NULL);
641
642         /* Don't update unless user actually selects ! */
643         if (!event || event->type != GDK_BUTTON_RELEASE)
644                 return;
645
646         /* User selected address by releasing the mouse in drop-down list*/
647         completion_window_apply_selection( clist, entry );
648
649         addrcompl_destroy_window( _compWindow_ );
650 }
651
652 /**
653  * Respond to button press in completion window. Check if mouse click is
654  * anywhere outside the completion window. In that case the completion
655  * window is destroyed, and the original searchTerm is restored.
656  *
657  * \param widget   Window object.
658  * \param event    Event.
659  * \param compWin  Reference to completion window.
660  */
661 static gboolean completion_window_button_press(GtkWidget *widget,
662                                                GdkEventButton *event,
663                                                CompletionWindow *compWin )
664
665 {
666         GtkWidget *event_widget, *entry;
667         gchar *searchTerm;
668         gint cursor_pos;
669         gboolean restore = TRUE;
670
671         g_return_val_if_fail(compWin != NULL, FALSE);
672
673         entry = compWin->entry;
674         g_return_val_if_fail(entry != NULL, FALSE);
675
676         /* Test where mouse was clicked */
677         event_widget = gtk_get_event_widget((GdkEvent *)event);
678         if (event_widget != widget) {
679                 while (event_widget) {
680                         if (event_widget == widget)
681                                 return FALSE;
682                         else if (event_widget == entry) {
683                                 restore = FALSE;
684                                 break;
685                         }
686                         event_widget = event_widget->parent;
687                 }
688         }
689
690         if (restore) {
691                 /* Clicked outside of completion window - restore */
692                 searchTerm = _compWindow_->searchTerm;
693                 g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
694                 replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos);
695         }
696
697         addrcompl_destroy_window( _compWindow_ );
698
699         return TRUE;
700 }
701
702 /**
703  * Respond to key press in completion window.
704  * \param widget   Window object.
705  * \param event    Event.
706  * \param compWind Reference to completion window.
707  */
708 static gboolean completion_window_key_press(GtkWidget *widget,
709                                             GdkEventKey *event,
710                                             CompletionWindow *compWin )
711 {
712         GdkEventKey tmp_event;
713         GtkWidget *entry;
714         gchar *searchTerm;
715         gint cursor_pos;
716         GtkWidget *clist;
717
718         g_return_val_if_fail(compWin != NULL, FALSE);
719
720         entry = compWin->entry;
721         clist = compWin->clist;
722         g_return_val_if_fail(entry != NULL, FALSE);
723
724         /* allow keyboard navigation in the alternatives clist */
725         if (event->keyval == GDK_Up || event->keyval == GDK_Down ||
726             event->keyval == GDK_Page_Up || event->keyval == GDK_Page_Down) {
727                 completion_window_advance_selection
728                         (GTK_CLIST(clist),
729                          event->keyval == GDK_Down ||
730                          event->keyval == GDK_Page_Down ? TRUE : FALSE);
731                 return FALSE;
732         }               
733
734         /* also make tab / shift tab go to next previous completion entry. we're
735          * changing the key value */
736         if (event->keyval == GDK_Tab || event->keyval == GDK_ISO_Left_Tab) {
737                 event->keyval = (event->state & GDK_SHIFT_MASK)
738                         ? GDK_Up : GDK_Down;
739                 /* need to reset shift state if going up */
740                 if (event->state & GDK_SHIFT_MASK)
741                         event->state &= ~GDK_SHIFT_MASK;
742                 completion_window_advance_selection(GTK_CLIST(clist), 
743                         event->keyval == GDK_Down ? TRUE : FALSE);
744                 return FALSE;
745         }
746
747         /* look for presses that accept the selection */
748         if (event->keyval == GDK_Return || event->keyval == GDK_space) {
749                 /* User selected address with a key press */
750
751                 /* Display selected address in entry field */           
752                 completion_window_apply_selection(
753                         GTK_CLIST(clist), GTK_ENTRY(entry) );
754
755                 /* Discard the window */
756                 addrcompl_destroy_window( _compWindow_ );
757                 return FALSE;
758         }
759
760         /* key state keys should never be handled */
761         if (event->keyval == GDK_Shift_L
762                  || event->keyval == GDK_Shift_R
763                  || event->keyval == GDK_Control_L
764                  || event->keyval == GDK_Control_R
765                  || event->keyval == GDK_Caps_Lock
766                  || event->keyval == GDK_Shift_Lock
767                  || event->keyval == GDK_Meta_L
768                  || event->keyval == GDK_Meta_R
769                  || event->keyval == GDK_Alt_L
770                  || event->keyval == GDK_Alt_R) {
771                 return FALSE;
772         }
773
774         /* some other key, let's restore the searchTerm (orignal text) */
775         searchTerm = _compWindow_->searchTerm;
776         g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
777         replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos);
778
779         /* make sure anything we typed comes in the edit box */
780         tmp_event.type       = event->type;
781         tmp_event.window     = entry->window;
782         tmp_event.send_event = TRUE;
783         tmp_event.time       = event->time;
784         tmp_event.state      = event->state;
785         tmp_event.keyval     = event->keyval;
786         tmp_event.length     = event->length;
787         tmp_event.string     = event->string;
788         gtk_widget_event(entry, (GdkEvent *)&tmp_event);
789
790         /* and close the completion window */
791         addrcompl_destroy_window( _compWindow_ );
792
793         return TRUE;
794 }
795
796 /*
797  * ============================================================================
798  * Publically accessible functions.
799  * ============================================================================
800  */
801 /**
802  * Setup completion object.
803  */
804 void addrcompl_initialize( void ) {
805         /* printf( "addrcompl_initialize...\n" ); */
806         if( ! _compWindow_ ) {
807                 _compWindow_ = addrcompl_create_window();
808         }
809         _queryID_ = 0;
810         _completionIdleID_ = 0;
811         /* printf( "addrcompl_initialize...done\n" ); */
812 }
813
814 /**
815  * Teardown completion object.
816  */
817 void addrcompl_teardown( void ) {
818         /* printf( "addrcompl_teardown...\n" ); */
819         addrcompl_free_window( _compWindow_ );
820         _compWindow_ = NULL;
821         if( _displayQueue_ ) {
822                 g_list_free( _displayQueue_ );
823         }
824         _displayQueue_ = NULL;
825         _completionIdleID_ = 0;
826         /* printf( "addrcompl_teardown...done\n" ); */
827 }
828
829 /**
830  * Start address completion operation.
831  */
832 gint start_address_completion(void)
833 {
834         if( ! _compWindow_ ) {
835                 addrcompl_initialize();
836         }
837         addressbook_read_all();
838         return 0;
839 }
840
841 /**
842  * Terminate addess completion.
843  */
844 gint end_address_completion(void)
845 {
846         return 0;
847 }
848
849 /**
850  * Start address completion. Should be called when creating the main window
851  * containing address completion entries. This originally cleared the cache.
852  * Function no longer required?
853  */
854 void address_completion_start(GtkWidget *mainwindow)
855 {
856         start_address_completion();
857 }
858
859 /**
860  * Need unique data to make unregistering signal handler possible for the auto
861  * completed entry.
862  */
863 #define COMPLETION_UNIQUE_DATA (GINT_TO_POINTER(0xfeefaa))
864
865 /**
866  * Register specified entry widget for address completion.
867  * \param entry Address entry field.
868  */
869 void address_completion_register_entry(GtkEntry *entry)
870 {
871         g_return_if_fail(entry != NULL);
872         g_return_if_fail(GTK_IS_ENTRY(entry));
873
874         /* add hooked property */
875         gtk_object_set_data(GTK_OBJECT(entry), ENTRY_DATA_TAB_HOOK, entry);
876
877         /* add keypress event */
878         gtk_signal_connect_full(GTK_OBJECT(entry), "key_press_event",
879                                 GTK_SIGNAL_FUNC(address_completion_entry_key_pressed),
880                                 NULL,
881                                 COMPLETION_UNIQUE_DATA,
882                                 NULL,
883                                 0,
884                                 0); /* magic */
885 }
886
887 /**
888  * Unregister specified entry widget from address completion operations.
889  * \param entry Address entry field.
890  */
891 void address_completion_unregister_entry(GtkEntry *entry)
892 {
893         GtkObject *entry_obj;
894
895         g_return_if_fail(entry != NULL);
896         g_return_if_fail(GTK_IS_ENTRY(entry));
897
898         entry_obj = gtk_object_get_data(GTK_OBJECT(entry), ENTRY_DATA_TAB_HOOK);
899         g_return_if_fail(entry_obj);
900         g_return_if_fail(entry_obj == GTK_OBJECT(entry));
901
902         /* has the hooked property? */
903         gtk_object_set_data(GTK_OBJECT(entry), ENTRY_DATA_TAB_HOOK, NULL);
904
905         /* remove the hook */
906         gtk_signal_disconnect_by_func(GTK_OBJECT(entry), 
907                 GTK_SIGNAL_FUNC(address_completion_entry_key_pressed),
908                 COMPLETION_UNIQUE_DATA);
909 }
910
911 /**
912  * End address completion. Should be called when main window with address
913  * completion entries terminates. NOTE: this function assumes that it is
914  * called upon destruction of the window.
915  */
916 void address_completion_end(GtkWidget *mainwindow)
917 {
918         /* if address_completion_end() is really called on closing the window,
919          * we don't need to unregister the set_focus_cb */
920         end_address_completion();
921 }
922
923 /*
924  * End of Source.
925  */
926