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