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