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