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