inital gtk2 patch
[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 <pthread.h>
47
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 /**
67  * Reference to address index.
68  */
69 static AddressIndex *_addressIndex_ = NULL;
70
71 /**
72  * address_entry - structure which refers to the original address entry in the
73  * address book .
74  */
75 typedef struct
76 {
77         gchar *name;
78         gchar *address;
79 } address_entry;
80
81 /**
82  * completion_entry - structure used to complete addresses, with a reference
83  * the the real address information.
84  */
85 typedef struct
86 {
87         gchar           *string; /* string to complete */
88         address_entry   *ref;    /* address the string belongs to  */
89 } completion_entry;
90
91 /*******************************************************************************/
92
93 static gint         g_ref_count;        /* list ref count */
94 static GList       *g_completion_list;  /* list of strings to be checked */
95 static GList       *g_address_list;     /* address storage */
96 static GCompletion *g_completion;       /* completion object */
97
98 /* To allow for continuing completion we have to keep track of the state
99  * using the following variables. No need to create a context object. */
100
101 static gint         g_completion_count;         /* nr of addresses incl. the prefix */
102 static gint         g_completion_next;          /* next prev address */
103 static GSList      *g_completion_addresses;     /* unique addresses found in the
104                                                    completion cache. */
105 static gchar       *g_completion_prefix;        /* last prefix. (this is cached here
106                                                  * because the prefix passed to g_completion
107                                                  * is g_strdown()'ed */
108
109 /*******************************************************************************/
110
111 /**
112  * Function used by GTK to find the string data to be used for completion.
113  * \param data Pointer to data being processed.
114  */
115 static gchar *completion_func(gpointer data)
116 {
117         g_return_val_if_fail(data != NULL, NULL);
118
119         return ((completion_entry *)data)->string;
120
121
122 /**
123  * Initialize all completion index data.
124  */
125 static void init_all(void)
126 {
127         g_completion = g_completion_new(completion_func);
128         g_return_if_fail(g_completion != NULL);
129 }
130
131 /**
132  * Free up all completion index data.
133  */
134 static void free_all(void)
135 {
136         GList *walk;
137         
138         walk = g_list_first(g_completion_list);
139         for (; walk != NULL; walk = g_list_next(walk)) {
140                 completion_entry *ce = (completion_entry *) walk->data;
141                 g_free(ce->string);
142                 g_free(walk->data);
143         }
144         g_list_free(g_completion_list);
145         g_completion_list = NULL;
146         
147         walk = g_address_list;
148         for (; walk != NULL; walk = g_list_next(walk)) {
149                 address_entry *ae = (address_entry *) walk->data;
150                 g_free(ae->name);
151                 g_free(ae->address);
152                 g_free(walk->data);
153         }
154         g_list_free(g_address_list);
155         g_address_list = NULL;
156         
157         g_completion_free(g_completion);
158         g_completion = NULL;
159 }
160
161 /**
162  * Append specified address entry to the index.
163  * \param str Index string value.
164  * \param ae  Entry containing address data.
165  */
166 static void add_address1(const char *str, address_entry *ae)
167 {
168         completion_entry *ce1;
169         ce1 = g_new0(completion_entry, 1),
170         ce1->string = g_utf8_strdown(str, -1);
171         /* GCompletion list is case sensitive */
172         g_strdown(ce1->string);
173         ce1->ref = ae;
174
175         g_completion_list = g_list_prepend(g_completion_list, ce1);
176 }
177
178 /**
179  * Adds address to the completion list. This function looks complicated, but
180  * it's only allocation checks. Each value will be included in the index.
181  * \param name    Recipient name.
182  * \param address EMail address.
183  * \param alias   Alias to append.
184  * \return <code>0</code> if entry appended successfully, or <code>-1</code>
185  *         if failure.
186  */
187 static gint add_address(const gchar *name, const gchar *address, const gchar *alias)
188 {
189         address_entry    *ae;
190
191         if (!name || !address) return -1;
192
193         ae = g_new0(address_entry, 1);
194
195         g_return_val_if_fail(ae != NULL, -1);
196
197         ae->name    = g_strdup(name);
198         ae->address = g_strdup(address);                
199
200         g_address_list = g_list_prepend(g_address_list, ae);
201
202         add_address1(name, ae);
203         add_address1(address, ae);
204         add_address1(alias, ae);
205
206         return 0;
207 }
208
209 /**
210  * Read address book, creating all entries in the completion index.
211  */ 
212 static void read_address_book(void) {   
213         addrindex_load_completion( _addressIndex_, add_address );
214         g_address_list = g_list_reverse(g_address_list);
215         g_completion_list = g_list_reverse(g_completion_list);
216 }
217
218 /**
219  * Test whether there is a completion pending.
220  * \return <code>TRUE</code> if pending.
221  */
222 static gboolean is_completion_pending(void)
223 {
224         /* check if completion pending, i.e. we might satisfy a request for the next
225          * or previous address */
226          return g_completion_count;
227 }
228
229 /**
230  * Clear the completion cache.
231  */
232 static void clear_completion_cache(void)
233 {
234         if (is_completion_pending()) {
235                 if (g_completion_prefix)
236                         g_free(g_completion_prefix);
237
238                 if (g_completion_addresses) {
239                         g_slist_free(g_completion_addresses);
240                         g_completion_addresses = NULL;
241                 }
242
243                 g_completion_count = g_completion_next = 0;
244         }
245 }
246
247 /**
248  * Prepare completion index. This function should be called prior to attempting
249  * address completion.
250  * \return The number of addresses in the completion list.
251  */
252 gint start_address_completion(void)
253 {
254         clear_completion_cache();
255         if (!g_ref_count) {
256                 init_all();
257                 /* open the address book */
258                 read_address_book();
259                 /* merge the completion entry list into g_completion */
260                 if (g_completion_list)
261                         g_completion_add_items(g_completion, g_completion_list);
262         }
263         g_ref_count++;
264         debug_print("start_address_completion ref count %d\n", g_ref_count);
265
266         return g_list_length(g_completion_list);
267 }
268
269 /**
270  * Retrieve a possible address (or a part) from an entry box. To make life
271  * easier, we only look at the last valid address component; address
272  * completion only works at the last string component in the entry box.
273  *
274  * \param entry Address entry field.
275  * \param start_pos Address of start position of address.
276  * \return Possible address.
277  */
278 static gchar *get_address_from_edit(GtkEntry *entry, gint *start_pos)
279 {
280         const gchar *edit_text, *p;
281         gint cur_pos;
282         gboolean in_quote = FALSE;
283         gboolean in_bracket = FALSE;
284         gchar *str;
285
286         edit_text = gtk_entry_get_text(entry);
287         if (edit_text == NULL) return NULL;
288
289         cur_pos = gtk_editable_get_position(GTK_EDITABLE(entry));
290
291         /* scan for a separator. doesn't matter if walk points at null byte. */
292         for (p = g_utf8_offset_to_pointer(edit_text, cur_pos);
293              p > edit_text;
294              p = g_utf8_prev_char(p)) {
295                 if (*p == '"') {
296                         in_quote = TRUE;
297                 } else if (!in_quote) {
298                         if (!in_bracket && *p == ',') {
299                                 break;
300                         } else if (*p == '<')
301                                 in_bracket = TRUE;
302                         else if (*p == '>')
303                                 in_bracket = FALSE;
304                 }
305         }
306
307         /* have something valid */
308         if (g_utf8_strlen(p, -1) == 0)
309                 return NULL;
310
311 #define IS_VALID_CHAR(x) \
312         (isalnum(x) || (x) == '"' || (x) == '<' || (((unsigned char)(x)) > 0x7f))
313
314         /* now scan back until we hit a valid character */
315         for (; *p && !IS_VALID_CHAR(*p); p = g_utf8_next_char(p))
316                 ;
317
318 #undef IS_VALID_CHAR
319
320         if (g_utf8_strlen(p, -1) == 0)
321                 return NULL;
322
323         if (start_pos) *start_pos = g_utf8_pointer_to_offset(edit_text, p);
324
325         str = g_strdup(p);
326
327         return str;
328
329
330 /**
331  * Replace an incompleted address with a completed one.
332  * \param entry     Address entry field.
333  * \param newtext   New text.
334  * \param start_pos Insertion point in entry field.
335  */
336 static void replace_address_in_edit(GtkEntry *entry, const gchar *newtext,
337                              gint start_pos)
338 {
339         if (!newtext) return;
340         gtk_editable_delete_text(GTK_EDITABLE(entry), start_pos, -1);
341         gtk_editable_insert_text(GTK_EDITABLE(entry), newtext, strlen(newtext),
342                                  &start_pos);
343         gtk_editable_set_position(GTK_EDITABLE(entry), -1);
344 }
345
346 /**
347  * Attempt to complete an address, and returns the number of addresses found.
348  * Use <code>get_complete_address()</code> to get an entry from the index.
349  *
350  * \param  str Search string to find.
351  * \return Zero if no match was found, otherwise the number of addresses; the
352  *         original prefix (search string) will appear at index 0. 
353  */
354 guint complete_address(const gchar *str)
355 {
356         GList *result;
357         gchar *d;
358         guint  count, cpl;
359         completion_entry *ce;
360
361         g_return_val_if_fail(str != NULL, 0);
362
363         /* g_completion is case sensitive */
364         d = g_utf8_strdown(str, -1);
365
366         clear_completion_cache();
367         g_completion_prefix = g_strdup(str);
368
369         result = g_completion_complete(g_completion, d, NULL);
370
371         count = g_list_length(result);
372         if (count) {
373                 /* create list with unique addresses  */
374                 for (cpl = 0, result = g_list_first(result);
375                      result != NULL;
376                      result = g_list_next(result)) {
377                         ce = (completion_entry *)(result->data);
378                         if (NULL == g_slist_find(g_completion_addresses,
379                                                  ce->ref)) {
380                                 cpl++;
381                                 g_completion_addresses =
382                                         g_slist_append(g_completion_addresses,
383                                                        ce->ref);
384                         }
385                 }
386                 count = cpl + 1;        /* index 0 is the original prefix */
387                 g_completion_next = 1;  /* we start at the first completed one */
388         } else {
389                 g_free(g_completion_prefix);
390                 g_completion_prefix = NULL;
391         }
392
393         g_completion_count = count;
394
395         g_free(d);
396
397         return count;
398 }
399
400 /**
401  * Return a complete address from the index.
402  * \param index Index of entry that was found (by the previous call to
403  *              <code>complete_address()</code>
404  * \return Completed address string; this should be freed when done.
405  */
406 gchar *get_complete_address(gint index)
407 {
408         const address_entry *p;
409         gchar *address = NULL;
410
411         if (index < g_completion_count) {
412                 if (index == 0)
413                         address = g_strdup(g_completion_prefix);
414                 else {
415                         /* get something from the unique addresses */
416                         p = (address_entry *)g_slist_nth_data
417                                 (g_completion_addresses, index - 1);
418                         if (p != NULL) {
419                                 if (!p->name || p->name[0] == '\0')
420                                         address = g_strdup_printf(p->address);
421                                 else if (strchr_with_skip_quote(p->name, '"', ','))
422                                         address = g_strdup_printf
423                                                 ("\"%s\" <%s>", p->name, p->address);
424                                 else
425                                         address = g_strdup_printf
426                                                 ("%s <%s>", p->name, p->address);
427                         }
428                 }
429         }
430
431         return address;
432 }
433
434 /**
435  * Return the next complete address match from the completion index.
436  * \return Completed address string; this should be freed when done.
437  */
438 static gchar *get_next_complete_address(void)
439 {
440         if (is_completion_pending()) {
441                 gchar *res;
442
443                 res = get_complete_address(g_completion_next);
444                 g_completion_next += 1;
445                 if (g_completion_next >= g_completion_count)
446                         g_completion_next = 0;
447
448                 return res;
449         } else
450                 return NULL;
451 }
452
453 /**
454  * Return a count of the completed matches in the completion index.
455  * \return Number of matched entries.
456  */
457 static guint get_completion_count(void)
458 {
459         if (is_completion_pending())
460                 return g_completion_count;
461         else
462                 return 0;
463 }
464
465 /**
466  * Invalidate address completion index. This function should be called whenever
467  * the address book changes. This forces data to be read into the completion
468  * data.
469  * \return Number of entries in index.
470  */
471 gint invalidate_address_completion(void)
472 {
473         if (g_ref_count) {
474                 /* simply the same as start_address_completion() */
475                 debug_print("Invalidation request for address completion\n");
476                 free_all();
477                 init_all();
478                 read_address_book();
479                 g_completion_add_items(g_completion, g_completion_list);
480                 clear_completion_cache();
481         }
482
483         return g_list_length(g_completion_list);
484 }
485
486 /**
487  * Finished with completion index. This function should be called after
488  * matching addresses.
489  * \return Reference count.
490  */
491 gint end_address_completion(void)
492 {
493         clear_completion_cache();
494
495         if (0 == --g_ref_count)
496                 free_all();
497
498         debug_print("end_address_completion ref count %d\n", g_ref_count);
499
500         return g_ref_count; 
501 }
502
503 /*
504  * Define the structure of the completion window.
505  */
506 typedef struct _CompletionWindow CompletionWindow;
507 struct _CompletionWindow {
508         gint      listCount;
509         gchar     *searchTerm;
510         GtkWidget *window;
511         GtkWidget *entry;
512         GtkWidget *clist;
513 };
514
515 /**
516  * Completion window.
517  */
518 static CompletionWindow *_compWindow_ = NULL;
519
520 /**
521  * Mutex to protect callback from multiple threads.
522  */
523 static pthread_mutex_t _completionMutex_ = PTHREAD_MUTEX_INITIALIZER;
524
525 /**
526  * Completion queue list.
527  */
528 static GList *_displayQueue_ = NULL;
529
530 /**
531  * Current query ID.
532  */
533 static gint _queryID_ = 0;
534
535 /**
536  * Completion idle ID.
537  */
538 static guint _completionIdleID_ = 0;
539
540 /*
541  * address completion entry ui. the ui (completion list was inspired by galeon's
542  * auto completion list). remaining things powered by sylpheed's completion engine.
543  */
544
545 #define ENTRY_DATA_TAB_HOOK     "tab_hook"      /* used to lookup entry */
546
547 static void address_completion_mainwindow_set_focus     (GtkWindow   *window,
548                                                          GtkWidget   *widget,
549                                                          gpointer     data);
550 static gboolean address_completion_entry_key_pressed    (GtkEntry    *entry,
551                                                          GdkEventKey *ev,
552                                                          gpointer     data);
553 static gboolean address_completion_complete_address_in_entry
554                                                         (GtkEntry    *entry,
555                                                          gboolean     next);
556 static void address_completion_create_completion_window (GtkEntry    *entry);
557
558 static void completion_window_select_row(GtkCList        *clist,
559                                          gint             row,
560                                          gint             col,
561                                          GdkEvent        *event,
562                                          CompletionWindow *compWin );
563
564 static gboolean completion_window_button_press
565                                         (GtkWidget       *widget,
566                                          GdkEventButton  *event,
567                                          CompletionWindow *compWin );
568
569 static gboolean completion_window_key_press
570                                         (GtkWidget       *widget,
571                                          GdkEventKey     *event,
572                                          CompletionWindow *compWin );
573 static void address_completion_create_completion_window( GtkEntry *entry_ );
574
575 /**
576  * Create a completion window object.
577  * \return Initialized completion window.
578  */
579 static CompletionWindow *addrcompl_create_window( void ) {
580         CompletionWindow *cw;
581
582         cw = g_new0( CompletionWindow, 1 );
583         cw->listCount = 0;
584         cw->searchTerm = NULL;
585         cw->window = NULL;
586         cw->entry = NULL;
587         cw->clist = NULL;
588
589         return cw;      
590 }
591
592 /**
593  * Destroy completion window.
594  * \param cw Window to destroy.
595  */
596 static void addrcompl_destroy_window( CompletionWindow *cw ) {
597         /* Remove idler function... or application may not terminate */
598         if( _completionIdleID_ != 0 ) {
599                 gtk_idle_remove( _completionIdleID_ );
600                 _completionIdleID_ = 0;
601         }
602
603         /* Now destroy window */        
604         if( cw ) {
605                 /* Clear references to widgets */
606                 cw->entry = NULL;
607                 cw->clist = NULL;
608
609                 /* Free objects */
610                 if( cw->window ) {
611                         gtk_widget_hide( cw->window );
612                         gtk_widget_destroy( cw->window );
613                 }
614                 cw->window = NULL;
615         }
616 }
617
618 /**
619  * Free up completion window.
620  * \param cw Window to free.
621  */
622 static void addrcompl_free_window( CompletionWindow *cw ) {
623         if( cw ) {
624                 addrcompl_destroy_window( cw );
625
626                 g_free( cw->searchTerm );
627                 cw->searchTerm = NULL;
628
629                 /* Clear references */          
630                 cw->listCount = 0;
631
632                 /* Free object */               
633                 g_free( cw );
634         }
635 }
636
637 /**
638  * Advance selection to previous/next item in list.
639  * \param clist   List to process.
640  * \param forward Set to <i>TRUE</i> to select next or <i>FALSE</i> for
641  *                previous entry.
642  */
643 static void completion_window_advance_selection(GtkCList *clist, gboolean forward)
644 {
645         int row;
646
647         g_return_if_fail(clist != NULL);
648
649         if( clist->selection ) {
650                 row = GPOINTER_TO_INT(clist->selection->data);
651                 row = forward ? ( row + 1 ) : ( row - 1 );
652                 gtk_clist_freeze(clist);
653                 gtk_clist_select_row(clist, row, 0);
654                 gtk_clist_thaw(clist);
655         }
656 }
657
658 #if 0
659 /* completion_window_accept_selection() - accepts the current selection in the
660  * clist, and destroys the window */
661 static void completion_window_accept_selection(GtkWidget **window,
662                                                GtkCList *clist,
663                                                GtkEntry *entry)
664 {
665         gchar *address = NULL, *text = NULL;
666         gint   cursor_pos, row;
667
668         g_return_if_fail(window != NULL);
669         g_return_if_fail(*window != NULL);
670         g_return_if_fail(clist != NULL);
671         g_return_if_fail(entry != NULL);
672         g_return_if_fail(clist->selection != NULL);
673
674         /* FIXME: I believe it's acceptable to access the selection member directly  */
675         row = GPOINTER_TO_INT(clist->selection->data);
676
677         /* we just need the cursor position */
678         address = get_address_from_edit(entry, &cursor_pos);
679         g_free(address);
680         gtk_clist_get_text(clist, row, 0, &text);
681         replace_address_in_edit(entry, text, cursor_pos);
682
683         clear_completion_cache();
684         gtk_widget_destroy(*window);
685         *window = NULL;
686 }
687 #endif
688
689 /**
690  * Resize window to accommodate maximum number of address entries.
691  * \param cw Completion window.
692  */
693 static void addrcompl_resize_window( CompletionWindow *cw ) {
694         GtkRequisition r;
695         gint x, y, width, height, depth;
696
697         /* Get current geometry of window */
698         gdk_window_get_geometry( cw->window->window, &x, &y, &width, &height, &depth );
699
700         gtk_widget_size_request( cw->clist, &r );
701         gtk_widget_set_size_request( cw->window, width, r.height );
702         gtk_widget_show_all( cw->window );
703         gtk_widget_size_request( cw->clist, &r );
704
705         /* Adjust window height to available screen space */
706         if( ( y + r.height ) > gdk_screen_height() ) {
707                 gtk_window_set_policy( GTK_WINDOW( cw->window ), TRUE, FALSE, FALSE );
708                 gtk_widget_set_size_request( cw->window, width, gdk_screen_height() - y );
709         }
710 }
711
712 /**
713  * Add an address the completion window address list.
714  * \param cw      Completion window.
715  * \param address Address to add.
716  */
717 static void addrcompl_add_entry( CompletionWindow *cw, gchar *address ) {
718         gchar *text[] = { NULL, NULL };
719
720         /* printf( "\t\tAdding :%s\n", address ); */
721         text[0] = address;
722         gtk_clist_append( GTK_CLIST(cw->clist), text );
723         cw->listCount++;
724
725         /* Resize window */
726         addrcompl_resize_window( cw );
727         gtk_grab_add( cw->window );
728
729         if( cw->listCount == 1 ) {
730                 /* Select first row for now */
731                 gtk_clist_select_row( GTK_CLIST(cw->clist), 0, 0);
732         }
733         else if( cw->listCount == 2 ) {
734                 /* Move off first row */
735                 gtk_clist_select_row( GTK_CLIST(cw->clist), 1, 0);
736         }
737 }
738
739 /**
740  * Completion idle function. This function is called by the main (UI) thread
741  * during UI idle time while an address search is in progress. Items from the
742  * display queue are processed and appended to the address list.
743  *
744  * \param data Target completion window to receive email addresses.
745  * \return <i>TRUE</i> to ensure that idle event do not get ignored.
746  */
747 static gboolean addrcompl_idle( gpointer data ) {
748         GList *node;
749         gchar *address;
750         CompletionWindow *cw;
751
752         /* Process all entries in display queue */
753         pthread_mutex_lock( & _completionMutex_ );
754         if( _displayQueue_ ) {
755                 cw = data;
756                 node = _displayQueue_;
757                 while( node ) {
758                         address = node->data;
759                         /* printf( "address ::: %s :::\n", address ); */
760                         addrcompl_add_entry( cw, address );
761                         g_free( address );
762                         node = g_list_next( node );
763                 }
764                 g_list_free( _displayQueue_ );
765                 _displayQueue_ = NULL;
766         }
767         pthread_mutex_unlock( & _completionMutex_ );
768
769         return TRUE;
770 }
771
772 /**
773  * Callback entry point. The background thread (if any) appends the address
774  * list to the display queue.
775  * \param queryID    Query ID of search request.
776  * \param listEMail  List of zero of more email objects that met search
777  *                   criteria.
778  * \param target     Target object to received data.
779  */
780 static gint addrcompl_callback(
781         gint queryID, GList *listEMail, gpointer target )
782 {
783         GList *node;
784         gchar *address;
785
786         /* printf( "addrcompl_callback::queryID=%d\n", queryID ); */
787         pthread_mutex_lock( & _completionMutex_ );
788         if( target ) {
789                 if( queryID == _queryID_ ) {
790                         /* Append contents to end of display queue */
791                         node = listEMail;
792                         while( node ) {
793                                 ItemEMail *email = node->data;
794
795                                 address = addritem_format_email( email );
796                                 /* printf( "\temail/address ::%s::\n", address ); */
797                                 _displayQueue_ = g_list_append( _displayQueue_, address );
798                                 node = g_list_next( node );
799                         }
800                 }
801         }
802         pthread_mutex_unlock( & _completionMutex_ );
803         /* printf( "addrcompl_callback...done\n" ); */
804
805         return 0;
806 }
807
808 /**
809  * Clear the display queue.
810  */
811 static void addrcompl_clear_queue( void ) {
812         /* Clear out display queue */
813         pthread_mutex_lock( & _completionMutex_ );
814
815         g_list_free( _displayQueue_ );
816         _displayQueue_ = NULL;
817
818         pthread_mutex_unlock( & _completionMutex_ );
819 }
820
821 /**
822  * Add a single address entry into the display queue.
823  * \param address Address to append.
824  */
825 static void addrcompl_add_queue( gchar *address ) {
826         pthread_mutex_lock( & _completionMutex_ );
827         _displayQueue_ = g_list_append( _displayQueue_, address );
828         pthread_mutex_unlock( & _completionMutex_ );
829 }
830
831 /**
832  * Load list with entries from local completion index.
833  * \param cw Completion window.
834  */
835 static void addrcompl_load_local( CompletionWindow *cw ) {
836         guint count = 0;
837
838         for (count = 0; count < get_completion_count(); count++) {
839                 gchar *address;
840
841                 address = get_complete_address( count );
842                 /* printf( "\taddress ::%s::\n", address ); */
843
844                 /* Append contents to end of display queue */
845                 addrcompl_add_queue( address );
846         }
847 }
848
849 /**
850  * Start the search.
851  */
852 static void addrcompl_start_search( void ) {
853         gchar *searchTerm;
854
855         searchTerm = g_strdup( _compWindow_->searchTerm );
856
857         /* Setup the search */
858         _queryID_ = addrindex_setup_search(
859                 _addressIndex_, searchTerm, _compWindow_, addrcompl_callback );
860         g_free( searchTerm );
861         /* printf( "addrcompl_start_search::queryID=%d\n", _queryID_ ); */
862
863         /* Load local stuff */
864         addrcompl_load_local( _compWindow_ );
865
866         /* Sit back and wait until something happens */
867         _completionIdleID_ =
868                 gtk_idle_add( ( GtkFunction ) addrcompl_idle, _compWindow_ );
869         /* printf( "addrindex_start_search::queryID=%d\n", _queryID_ ); */
870
871         addrindex_start_search( _addressIndex_, _queryID_ );
872 }
873
874 /**
875  * Apply the current selection in the list to the entry field. Focus is also
876  * moved to the next widget so that Tab key works correctly.
877  * \param clist List to process.
878  * \param entry Address entry field.
879  */
880 static void completion_window_apply_selection(GtkCList *clist, GtkEntry *entry)
881 {
882         gchar *address = NULL, *text = NULL;
883         gint   cursor_pos, row;
884         GtkWidget *parent;
885
886         g_return_if_fail(clist != NULL);
887         g_return_if_fail(entry != NULL);
888         g_return_if_fail(clist->selection != NULL);
889
890         /* First remove the idler */
891         if( _completionIdleID_ != 0 ) {
892                 gtk_idle_remove( _completionIdleID_ );
893                 _completionIdleID_ = 0;
894         }
895
896         /* Process selected item */
897         row = GPOINTER_TO_INT(clist->selection->data);
898
899         address = get_address_from_edit(entry, &cursor_pos);
900         g_free(address);
901         gtk_clist_get_text(clist, row, 0, &text);
902         replace_address_in_edit(entry, text, cursor_pos);
903
904         /* Move focus to next widget */
905         parent = GTK_WIDGET(entry)->parent;
906         if( parent ) {
907                 gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
908         }
909 }
910
911 /**
912  * Start address completion. Should be called when creating the main window
913  * containing address completion entries.
914  * \param mainwindow Main window.
915  */
916 void address_completion_start(GtkWidget *mainwindow)
917 {
918         start_address_completion();
919
920         /* register focus change hook */
921         g_signal_connect(G_OBJECT(mainwindow), "set_focus",
922                          G_CALLBACK(address_completion_mainwindow_set_focus),
923                          mainwindow);
924 }
925
926 /**
927  * Need unique data to make unregistering signal handler possible for the auto
928  * completed entry.
929  */
930 #define COMPLETION_UNIQUE_DATA (GINT_TO_POINTER(0xfeefaa))
931
932 /**
933  * Register specified entry widget for address completion.
934  * \param entry Address entry field.
935  */
936 void address_completion_register_entry(GtkEntry *entry)
937 {
938         g_return_if_fail(entry != NULL);
939         g_return_if_fail(GTK_IS_ENTRY(entry));
940
941         /* add hooked property */
942         g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, entry);
943
944         /* add keypress event */
945         g_signal_connect_closure
946                 (GTK_OBJECT(entry), "key_press_event",
947                  g_cclosure_new(G_CALLBACK(address_completion_entry_key_pressed),
948                                 COMPLETION_UNIQUE_DATA,
949                                 NULL),
950                  FALSE); /* magic */
951 }
952
953 /**
954  * Unregister specified entry widget from address completion operations.
955  * \param entry Address entry field.
956  */
957 void address_completion_unregister_entry(GtkEntry *entry)
958 {
959         GtkObject *entry_obj;
960
961         g_return_if_fail(entry != NULL);
962         g_return_if_fail(GTK_IS_ENTRY(entry));
963
964         entry_obj = g_object_get_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK);
965         g_return_if_fail(entry_obj);
966         g_return_if_fail(entry_obj == GTK_OBJECT(entry));
967
968         /* has the hooked property? */
969         g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, NULL);
970
971         /* remove the hook */
972         g_signal_handlers_disconnect_by_func(G_OBJECT(entry), 
973                         G_CALLBACK(address_completion_entry_key_pressed),
974                         COMPLETION_UNIQUE_DATA);
975 }
976
977 /**
978  * End address completion. Should be called when main window with address
979  * completion entries terminates. NOTE: this function assumes that it is
980  * called upon destruction of the window.
981  * \param mainwindow Main window.
982  */
983 void address_completion_end(GtkWidget *mainwindow)
984 {
985         /* if address_completion_end() is really called on closing the window,
986          * we don't need to unregister the set_focus_cb */
987         end_address_completion();
988 }
989
990 /* if focus changes to another entry, then clear completion cache */
991 static void address_completion_mainwindow_set_focus(GtkWindow *window,
992                                                     GtkWidget *widget,
993                                                     gpointer   data)
994 {
995         
996         if (widget && GTK_IS_ENTRY(widget) &&
997             g_object_get_data(G_OBJECT(widget), ENTRY_DATA_TAB_HOOK)) {
998                 clear_completion_cache();
999         }
1000 }
1001
1002 /**
1003  * Listener that watches for tab or other keystroke in address entry field.
1004  * \param entry Address entry field.
1005  * \param ev    Event object.
1006  * \param data  User data.
1007  * \return <i>TRUE</i>.
1008  */
1009 static gboolean address_completion_entry_key_pressed(GtkEntry    *entry,
1010                                                      GdkEventKey *ev,
1011                                                      gpointer     data)
1012 {
1013         if (ev->keyval == GDK_Tab) {
1014                 addrcompl_clear_queue();
1015
1016                 if( address_completion_complete_address_in_entry( entry, TRUE ) ) {
1017                         /* route a void character to the default handler */
1018                         /* this is a dirty hack; we're actually changing a key
1019                          * reported by the system. */
1020                         ev->keyval = GDK_AudibleBell_Enable;
1021                         ev->state &= ~GDK_SHIFT_MASK;
1022
1023                         /* Create window */                     
1024                         address_completion_create_completion_window(entry);
1025
1026                         /* Start remote queries */
1027                         addrcompl_start_search();
1028
1029                         return TRUE;
1030                 }
1031                 else {
1032                         /* old behaviour */
1033                 }
1034         } else if (ev->keyval == GDK_Shift_L
1035                 || ev->keyval == GDK_Shift_R
1036                 || ev->keyval == GDK_Control_L
1037                 || ev->keyval == GDK_Control_R
1038                 || ev->keyval == GDK_Caps_Lock
1039                 || ev->keyval == GDK_Shift_Lock
1040                 || ev->keyval == GDK_Meta_L
1041                 || ev->keyval == GDK_Meta_R
1042                 || ev->keyval == GDK_Alt_L
1043                 || ev->keyval == GDK_Alt_R) {
1044                 /* these buttons should not clear the cache... */
1045         } else
1046                 clear_completion_cache();
1047
1048         return FALSE;
1049 }
1050 /**
1051  * Initialize search term for address completion.
1052  * \param entry Address entry field.
1053  */
1054 static gboolean address_completion_complete_address_in_entry(GtkEntry *entry,
1055                                                              gboolean  next)
1056 {
1057         gint ncount, cursor_pos;
1058         gchar *searchTerm, *new = NULL;
1059
1060         g_return_val_if_fail(entry != NULL, FALSE);
1061
1062         if (!GTK_WIDGET_HAS_FOCUS(entry)) return FALSE;
1063
1064         /* get an address component from the cursor */
1065         searchTerm = get_address_from_edit( entry, &cursor_pos );
1066         if( ! searchTerm ) return FALSE;
1067         /* printf( "search for :::%s:::\n", searchTerm ); */
1068
1069         /* Clear any existing search */
1070         if( _compWindow_->searchTerm ) {
1071                 g_free( _compWindow_->searchTerm );
1072         }
1073         _compWindow_->searchTerm = g_strdup( searchTerm );
1074
1075         /* Perform search on local completion index */
1076         ncount = complete_address( searchTerm );
1077         if( 0 < ncount ) {
1078                 new = get_next_complete_address();
1079                 g_free( new );
1080         }
1081
1082         /* Make sure that drop-down appears uniform! */
1083         if( ncount == 0 ) {
1084                 addrcompl_add_queue( g_strdup( searchTerm ) );
1085         }
1086         g_free( searchTerm );
1087
1088         return TRUE;
1089 }
1090
1091 /**
1092  * Create new address completion window for specified entry.
1093  * \param entry_ Entry widget to associate with window.
1094  */
1095 static void address_completion_create_completion_window( GtkEntry *entry_ )
1096 {
1097         gint x, y, height, width, depth;
1098         GtkWidget *scroll, *clist;
1099         GtkRequisition r;
1100         GtkWidget *window;
1101         GtkWidget *entry = GTK_WIDGET(entry_);
1102
1103         /* Create new window and list */
1104         window = gtk_window_new(GTK_WINDOW_POPUP);
1105         clist  = gtk_clist_new(1);
1106
1107         /* Destroy any existing window */
1108         addrcompl_destroy_window( _compWindow_ );
1109
1110         /* Create new object */
1111         _compWindow_->window = window;
1112         _compWindow_->entry = entry;
1113         _compWindow_->clist = clist;
1114         _compWindow_->listCount = 0;
1115
1116         scroll = gtk_scrolled_window_new(NULL, NULL);
1117         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
1118                                        GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
1119         gtk_container_add(GTK_CONTAINER(window), scroll);
1120         gtk_container_add(GTK_CONTAINER(scroll), clist);
1121         gtk_clist_set_selection_mode(GTK_CLIST(clist), GTK_SELECTION_SINGLE);
1122
1123         /* Use entry widget to create initial window */
1124         gdk_window_get_geometry(entry->window, &x, &y, &width, &height, &depth);
1125         gdk_window_get_deskrelative_origin (entry->window, &x, &y);
1126         y += height;
1127         gtk_window_move(GTK_WINDOW(window), x, y);
1128
1129         /* Resize window to fit initial (empty) address list */
1130         gtk_widget_size_request( clist, &r );
1131         gtk_widget_set_size_request( window, width, r.height );
1132         gtk_widget_show_all( window );
1133         gtk_widget_size_request( clist, &r );
1134
1135         /* Setup handlers */
1136         g_signal_connect(G_OBJECT(clist), "select_row",
1137                          G_CALLBACK(completion_window_select_row),
1138                          _compWindow_ );
1139         g_signal_connect(G_OBJECT(window),
1140                          "button-press-event",
1141                          G_CALLBACK(completion_window_button_press),
1142                          _compWindow_ );
1143         g_signal_connect(G_OBJECT(window),
1144                          "key-press-event",
1145                          G_CALLBACK(completion_window_key_press),
1146                          _compWindow_ );
1147         gdk_pointer_grab(window->window, TRUE,
1148                          GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK |
1149                          GDK_BUTTON_RELEASE_MASK,
1150                          NULL, NULL, GDK_CURRENT_TIME);
1151         gtk_grab_add( window );
1152
1153         /* this gets rid of the irritating focus rectangle that doesn't
1154          * follow the selection */
1155         GTK_WIDGET_UNSET_FLAGS(clist, GTK_CAN_FOCUS);
1156 }
1157
1158 /**
1159  * Respond to select row event in clist object. selection sends completed
1160  * address to entry. Note: event is NULL if selected by anything else than a
1161  * mouse button.
1162  * \param widget   Window object.
1163  * \param event    Event.
1164  * \param compWind Reference to completion window.
1165  */
1166 static void completion_window_select_row(GtkCList *clist, gint row, gint col,
1167                                          GdkEvent *event,
1168                                          CompletionWindow *compWin )
1169 {
1170         GtkEntry *entry;
1171
1172         g_return_if_fail(compWin != NULL);
1173
1174         entry = GTK_ENTRY(compWin->entry);
1175         g_return_if_fail(entry != NULL);
1176
1177         /* Don't update unless user actually selects ! */
1178         if (!event || event->type != GDK_BUTTON_RELEASE)
1179                 return;
1180
1181         /* User selected address by releasing the mouse in drop-down list*/
1182         completion_window_apply_selection( clist, entry );
1183
1184         clear_completion_cache();
1185         addrcompl_destroy_window( _compWindow_ );
1186 }
1187
1188 /**
1189  * Respond to button press in completion window. Check if mouse click is
1190  * anywhere outside the completion window. In that case the completion
1191  * window is destroyed, and the original searchTerm is restored.
1192  *
1193  * \param widget   Window object.
1194  * \param event    Event.
1195  * \param compWin  Reference to completion window.
1196  */
1197 static gboolean completion_window_button_press(GtkWidget *widget,
1198                                                GdkEventButton *event,
1199                                                CompletionWindow *compWin )
1200 {
1201         GtkWidget *event_widget, *entry;
1202         gchar *searchTerm;
1203         gint cursor_pos;
1204         gboolean restore = TRUE;
1205
1206         g_return_val_if_fail(compWin != NULL, FALSE);
1207
1208         entry = compWin->entry;
1209         g_return_val_if_fail(entry != NULL, FALSE);
1210
1211         /* Test where mouse was clicked */
1212         event_widget = gtk_get_event_widget((GdkEvent *)event);
1213         if (event_widget != widget) {
1214                 while (event_widget) {
1215                         if (event_widget == widget)
1216                                 return FALSE;
1217                         else if (event_widget == entry) {
1218                                 restore = FALSE;
1219                                 break;
1220                         }
1221                         event_widget = event_widget->parent;
1222                 }
1223         }
1224
1225         if (restore) {
1226                 /* Clicked outside of completion window - restore */
1227                 searchTerm = _compWindow_->searchTerm;
1228                 g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1229                 replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos);
1230         }
1231
1232         clear_completion_cache();
1233         addrcompl_destroy_window( _compWindow_ );
1234
1235         return TRUE;
1236 }
1237
1238 /**
1239  * Respond to key press in completion window.
1240  * \param widget   Window object.
1241  * \param event    Event.
1242  * \param compWind Reference to completion window.
1243  */
1244 static gboolean completion_window_key_press(GtkWidget *widget,
1245                                             GdkEventKey *event,
1246                                             CompletionWindow *compWin )
1247 {
1248         GdkEventKey tmp_event;
1249         GtkWidget *entry;
1250         gchar *searchTerm;
1251         gint cursor_pos;
1252         GtkWidget *clist;
1253         GtkWidget *parent;
1254
1255         g_return_val_if_fail(compWin != NULL, FALSE);
1256
1257         entry = compWin->entry;
1258         clist = compWin->clist;
1259         g_return_val_if_fail(entry != NULL, FALSE);
1260
1261         /* allow keyboard navigation in the alternatives clist */
1262         if (event->keyval == GDK_Up || event->keyval == GDK_Down ||
1263             event->keyval == GDK_Page_Up || event->keyval == GDK_Page_Down) {
1264                 completion_window_advance_selection
1265                         (GTK_CLIST(clist),
1266                          event->keyval == GDK_Down ||
1267                          event->keyval == GDK_Page_Down ? TRUE : FALSE);
1268                 return FALSE;
1269         }               
1270
1271 #if 0   
1272         /* also make tab / shift tab go to next previous completion entry. we're
1273          * changing the key value */
1274         if (event->keyval == GDK_Tab || event->keyval == GDK_ISO_Left_Tab) {
1275                 event->keyval = (event->state & GDK_SHIFT_MASK)
1276                         ? GDK_Up : GDK_Down;
1277                 /* need to reset shift state if going up */
1278                 if (event->state & GDK_SHIFT_MASK)
1279                         event->state &= ~GDK_SHIFT_MASK;
1280                 completion_window_advance_selection(GTK_CLIST(clist), 
1281                         event->keyval == GDK_Down ? TRUE : FALSE);
1282                 return FALSE;
1283         }
1284 #endif
1285
1286         /* make tab move to next field */
1287         if( event->keyval == GDK_Tab ) {
1288                 /* Reference to parent */
1289                 parent = GTK_WIDGET(entry)->parent;
1290
1291                 /* Discard the window */
1292                 clear_completion_cache();
1293                 addrcompl_destroy_window( _compWindow_ );
1294
1295                 /* Move focus to next widget */
1296                 if( parent ) {
1297                         gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1298                 }
1299                 return FALSE;
1300         }
1301
1302         /* make backtab move to previous field */
1303         if( event->keyval == GDK_ISO_Left_Tab ) {
1304                 /* Reference to parent */
1305                 parent = GTK_WIDGET(entry)->parent;
1306
1307                 /* Discard the window */
1308                 clear_completion_cache();
1309                 addrcompl_destroy_window( _compWindow_ );
1310
1311                 /* Move focus to previous widget */
1312                 if( parent ) {
1313                         gtk_widget_child_focus( parent, GTK_DIR_TAB_BACKWARD );
1314                 }
1315                 return FALSE;
1316         }
1317
1318         /* look for presses that accept the selection */
1319         if (event->keyval == GDK_Return || event->keyval == GDK_space) {
1320                 /* User selected address with a key press */
1321
1322                 /* Display selected address in entry field */           
1323                 completion_window_apply_selection(
1324                         GTK_CLIST(clist), GTK_ENTRY(entry) );
1325
1326                 /* Discard the window */
1327                 clear_completion_cache();
1328                 addrcompl_destroy_window( _compWindow_ );
1329                 return FALSE;
1330         }
1331
1332         /* key state keys should never be handled */
1333         if (event->keyval == GDK_Shift_L
1334                  || event->keyval == GDK_Shift_R
1335                  || event->keyval == GDK_Control_L
1336                  || event->keyval == GDK_Control_R
1337                  || event->keyval == GDK_Caps_Lock
1338                  || event->keyval == GDK_Shift_Lock
1339                  || event->keyval == GDK_Meta_L
1340                  || event->keyval == GDK_Meta_R
1341                  || event->keyval == GDK_Alt_L
1342                  || event->keyval == GDK_Alt_R) {
1343                 return FALSE;
1344         }
1345
1346         /* some other key, let's restore the searchTerm (orignal text) */
1347         searchTerm = _compWindow_->searchTerm;
1348         g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1349         replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos);
1350
1351         /* make sure anything we typed comes in the edit box */
1352         tmp_event.type       = event->type;
1353         tmp_event.window     = entry->window;
1354         tmp_event.send_event = TRUE;
1355         tmp_event.time       = event->time;
1356         tmp_event.state      = event->state;
1357         tmp_event.keyval     = event->keyval;
1358         tmp_event.length     = event->length;
1359         tmp_event.string     = event->string;
1360         gtk_widget_event(entry, (GdkEvent *)&tmp_event);
1361
1362         /* and close the completion window */
1363         clear_completion_cache();
1364         addrcompl_destroy_window( _compWindow_ );
1365
1366         return TRUE;
1367 }
1368
1369 /*
1370  * ============================================================================
1371  * Publically accessible functions.
1372  * ============================================================================
1373  */
1374
1375 /**
1376  * Setup completion object.
1377  * \param addrIndex Address index object.
1378  */
1379 void addrcompl_initialize( AddressIndex *addrIndex ) {
1380         g_return_if_fail( addrIndex != NULL );
1381         _addressIndex_ = addrIndex;
1382
1383         /* printf( "addrcompl_initialize...\n" ); */
1384         if( ! _compWindow_ ) {
1385                 _compWindow_ = addrcompl_create_window();
1386         }
1387         _queryID_ = 0;
1388         _completionIdleID_ = 0;
1389         /* printf( "addrcompl_initialize...done\n" ); */
1390 }
1391
1392 /**
1393  * Teardown completion object.
1394  */
1395 void addrcompl_teardown( void ) {
1396         /* printf( "addrcompl_teardown...\n" ); */
1397         addrcompl_free_window( _compWindow_ );
1398         _compWindow_ = NULL;
1399         if( _displayQueue_ ) {
1400                 g_list_free( _displayQueue_ );
1401         }
1402         _displayQueue_ = NULL;
1403         _completionIdleID_ = 0;
1404         _addressIndex_ = NULL;
1405         /* printf( "addrcompl_teardown...done\n" ); */
1406 }
1407
1408 /*
1409  * End of Source.
1410  */
1411