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