2012-11-15 [wwp] 3.9.0cvs3
[claws.git] / src / addr_compl.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  *
4  * Copyright (C) 2000-2012 by Alfons Hoogervorst & The Claws Mail 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 3 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, see <http://www.gnu.org/licenses/>.
18  * 
19  */
20
21 #ifdef HAVE_CONFIG_H
22 #  include "config.h"
23 #include "claws-features.h"
24 #endif
25 #include "defs.h"
26
27 #include <glib.h>
28 #include <glib/gi18n.h>
29 #include <gdk/gdkkeysyms.h>
30 #include <gtk/gtk.h>
31
32 #include <string.h>
33 #include <ctype.h>
34 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
35 #  include <wchar.h>
36 #  include <wctype.h>
37 #endif
38
39 #include "addr_compl.h"
40 #include "addritem.h"
41 #include "utils.h"
42 #include "prefs_common.h"
43 #include "claws.h"
44 #include "hooks.h"
45 #include "gtkutils.h"
46 #include "stock_pixmap.h"
47 #include <pthread.h>
48
49 #ifndef USE_NEW_ADDRBOOK
50         #include "addrindex.h"
51 #else
52         #include "addressbook-dbus.h"
53 #endif
54
55 /*!
56  *\brief        For the GtkListStore
57  */
58 enum {
59         ADDR_COMPL_ICON,
60         ADDR_COMPL_ADDRESS,
61         ADDR_COMPL_ISGROUP,
62         ADDR_COMPL_GROUPLIST,
63         N_ADDR_COMPL_COLUMNS
64 };
65
66 /*
67  * How it works:
68  *
69  * The address book is read into memory. We set up an address list
70  * containing all address book entries. Next we make the completion
71  * list, which contains all the completable strings, and store a
72  * reference to the address entry it belongs to.
73  * After calling the g_completion_complete(), we get a reference
74  * to a valid email address.  
75  *
76  * Completion is very simplified. We never complete on another prefix,
77  * i.e. we neglect the next smallest possible prefix for the current
78  * completion cache. This is simply done so we might break up the
79  * addresses a little more (e.g. break up alfons@proteus.demon.nl into
80  * something like alfons, proteus, demon, nl; and then completing on
81  * any of those words).
82  */
83
84 /**
85  * completion_entry - structure used to complete addresses, with a reference
86  * the the real address information.
87  */
88 typedef struct
89 {
90         gchar           *string; /* string to complete */
91         address_entry   *ref;    /* address the string belongs to  */
92 } completion_entry;
93
94 /*******************************************************************************/
95
96 static gint         g_ref_count;        /* list ref count */
97 static GList       *g_completion_list = NULL;   /* list of strings to be checked */
98 static GList       *g_address_list = NULL;      /* address storage */
99 static GCompletion *g_completion;       /* completion object */
100
101 static GHashTable *_groupAddresses_ = NULL;
102 static gboolean _allowCommas_ = TRUE;
103
104 /* To allow for continuing completion we have to keep track of the state
105  * using the following variables. No need to create a context object. */
106
107 static gint         g_completion_count;         /* nr of addresses incl. the prefix */
108 static gint         g_completion_next;          /* next prev address */
109 static GSList      *g_completion_addresses;     /* unique addresses found in the
110                                                    completion cache. */
111 static gchar       *g_completion_prefix;        /* last prefix. (this is cached here
112                                                  * because the prefix passed to g_completion
113                                                  * is g_utf8_strdown()'ed */
114
115 static gchar *completion_folder_path = NULL;
116
117 /*******************************************************************************/
118
119 /*
120  * Define the structure of the completion window.
121  */
122 typedef struct _CompletionWindow CompletionWindow;
123 struct _CompletionWindow {
124         gint      listCount;
125         gchar     *searchTerm;
126         GtkWidget *window;
127         GtkWidget *entry;
128         GtkWidget *list_view;
129
130         gboolean   in_mouse;    /*!< mouse press pending... */
131         gboolean   destroying;  /*!< destruction in progress */
132 };
133
134 static GtkListStore *addr_compl_create_store    (void);
135
136 static GtkWidget *addr_compl_list_view_create   (CompletionWindow *window);
137
138 static void addr_compl_create_list_view_columns (GtkWidget *list_view);
139
140 static gboolean list_view_button_press          (GtkWidget *widget, 
141                                                  GdkEventButton *event,
142                                                  CompletionWindow *window);
143
144 static gboolean list_view_button_release        (GtkWidget *widget, 
145                                                  GdkEventButton *event,
146                                                  CompletionWindow *window);
147
148 static gboolean addr_compl_selected             (GtkTreeSelection *selector,
149                                                  GtkTreeModel *model, 
150                                                  GtkTreePath *path,
151                                                  gboolean currently_selected,
152                                                  gpointer data);
153                                                  
154 static gboolean addr_compl_defer_select_destruct(CompletionWindow *window);
155
156 /**
157  * Function used by GTK to find the string data to be used for completion.
158  * \param data Pointer to data being processed.
159  */
160 static gchar *completion_func(gpointer data)
161 {
162         cm_return_val_if_fail(data != NULL, NULL);
163
164         return ((completion_entry *)data)->string;
165
166
167 /**
168  * Initialize all completion index data.
169  */
170 static void init_all(void)
171 {
172         g_completion = g_completion_new(completion_func);
173         cm_return_if_fail(g_completion != NULL);
174 }
175
176 static void free_all_addresses(void)
177 {
178         GList *walk;
179         if (!g_address_list)
180                 return;
181         walk = g_address_list;
182         for (; walk != NULL; walk = g_list_next(walk)) {
183                 address_entry *ae = (address_entry *) walk->data;
184                 g_free(ae->name);
185                 g_free(ae->address);
186                 g_list_free(ae->grp_emails);
187                 g_free(walk->data);
188         }
189         g_list_free(g_address_list);
190         g_address_list = NULL;
191         if (_groupAddresses_)
192                 g_hash_table_destroy(_groupAddresses_);
193         _groupAddresses_ = NULL;
194 }
195
196 static void clear_completion_cache(void);
197 static void free_completion_list(void)
198 {
199         GList *walk;
200         if (!g_completion_list)
201                 return;
202         
203         clear_completion_cache();
204         if (g_completion)
205                 g_completion_clear_items(g_completion);
206
207         walk = g_list_first(g_completion_list);
208         for (; walk != NULL; walk = g_list_next(walk)) {
209                 completion_entry *ce = (completion_entry *) walk->data;
210                 g_free(ce->string);
211                 g_free(walk->data);
212         }
213         g_list_free(g_completion_list);
214         g_completion_list = NULL;
215 }
216 /**
217  * Free up all completion index data.
218  */
219 static void free_all(void)
220 {
221         free_completion_list(); 
222         free_all_addresses();   
223         g_completion_free(g_completion);
224         g_completion = NULL;
225 }
226
227 /**
228  * Append specified address entry to the index.
229  * \param str Index string value.
230  * \param ae  Entry containing address data.
231  */
232 void addr_compl_add_address1(const char *str, address_entry *ae)
233 {
234         completion_entry *ce1;
235         ce1 = g_new0(completion_entry, 1),
236         /* GCompletion list is case sensitive */
237         ce1->string = g_utf8_strdown(str, -1);
238         ce1->ref = ae;
239
240         g_completion_list = g_list_prepend(g_completion_list, ce1);
241 }
242
243 /**
244  * Adds address to the completion list. This function looks complicated, but
245  * it's only allocation checks. Each value will be included in the index.
246  * \param name    Recipient name.
247  * \param address EMail address.
248  * \param alias   Alias to append.
249  * \param grp_emails the emails in case of a group. List should be freed later, 
250  * but not its strings
251  * \return <code>0</code> if entry appended successfully, or <code>-1</code>
252  *         if failure.
253  */
254 static gint add_address(const gchar *name, const gchar *address, 
255                         const gchar *nick, const gchar *alias, GList *grp_emails)
256 {
257         address_entry *ae;
258
259         if (!name || !address) {
260                 if (address || nick || alias || !grp_emails) 
261                         return -1;
262         }
263
264         ae = g_new0(address_entry, 1);
265
266         cm_return_val_if_fail(ae != NULL, -1);
267
268         ae->name    = g_strdup(name);
269         ae->address = g_strdup(address);
270         ae->grp_emails = grp_emails;
271         g_address_list = g_list_prepend(g_address_list, ae);
272
273         addr_compl_add_address1(name, ae);
274         if (address != NULL && *address != '\0')
275                 addr_compl_add_address1(address, ae);
276
277         if (nick != NULL && *nick != '\0')
278                 addr_compl_add_address1(nick, ae);
279
280         if ( alias != NULL && *alias != '\0') {
281                 addr_compl_add_address1(alias, ae);
282         }
283
284         return 0;
285 }
286
287 /**
288  * Read address book, creating all entries in the completion index.
289  */ 
290 static void read_address_book(gchar *folderpath) {
291         free_all_addresses();
292         free_completion_list();
293
294 #ifndef USE_NEW_ADDRBOOK
295         addrindex_load_completion( add_address, folderpath );
296 #else
297         GError* error = NULL;
298         
299         addrcompl_initialize();
300         if (! addrindex_dbus_load_completion(add_address, &error)) {
301                 g_warning("Failed to populate address completion list");
302         g_error_free(error);
303                 return;
304         }
305 #endif
306         /* plugins may hook in here to modify/extend the completion list */
307         hooks_invoke(ADDDRESS_COMPLETION_BUILD_ADDRESS_LIST_HOOKLIST, &g_address_list);
308
309         g_address_list = g_list_reverse(g_address_list);
310         g_completion_list = g_list_reverse(g_completion_list);
311         /* merge the completion entry list into g_completion */
312         if (g_completion_list) {
313                 g_completion_add_items(g_completion, g_completion_list);
314                 if (debug_get_mode())
315                         debug_print("read %d items in %s\n",
316                                 g_list_length(g_completion_list),
317                                 folderpath?folderpath:"(null)");
318         }
319 }
320
321 /**
322  * Test whether there is a completion pending.
323  * \return <code>TRUE</code> if pending.
324  */
325 static gboolean is_completion_pending(void)
326 {
327         /* check if completion pending, i.e. we might satisfy a request for the next
328          * or previous address */
329          return g_completion_count;
330 }
331
332 /**
333  * Clear the completion cache.
334  */
335 static void clear_completion_cache(void)
336 {
337         if (is_completion_pending()) {
338                 g_free(g_completion_prefix);
339
340                 if (g_completion_addresses) {
341                         g_slist_free(g_completion_addresses);
342                         g_completion_addresses = NULL;
343                 }
344
345                 g_completion_count = g_completion_next = 0;
346         }
347 }
348
349 /**
350  * Prepare completion index. This function should be called prior to attempting
351  * address completion.
352  * \return The number of addresses in the completion list.
353  */
354 gint start_address_completion(gchar *folderpath)
355 {
356         gboolean different_book = FALSE;
357         clear_completion_cache();
358
359         if (strcmp2(completion_folder_path,folderpath))
360                 different_book = TRUE;
361
362         g_free(completion_folder_path);
363         if (folderpath != NULL)
364                 completion_folder_path = g_strdup(folderpath);
365         else
366                 completion_folder_path = NULL;
367
368         if (!g_ref_count) {
369                 init_all();
370                 /* open the address book */
371                 read_address_book(folderpath);
372         } else if (different_book)
373                 read_address_book(folderpath);
374
375         g_ref_count++;
376         debug_print("start_address_completion(%s) ref count %d\n",
377                                 folderpath?folderpath:"(null)", g_ref_count);
378
379         return g_list_length(g_completion_list);
380 }
381
382 /**
383  * Retrieve a possible address (or a part) from an entry box. To make life
384  * easier, we only look at the last valid address component; address
385  * completion only works at the last string component in the entry box.
386  *
387  * \param entry Address entry field.
388  * \param start_pos Address of start position of address.
389  * \return Possible address.
390  */
391 static gchar *get_address_from_edit(GtkEntry *entry, gint *start_pos)
392 {
393         const gchar *edit_text, *p;
394         gint cur_pos;
395         gboolean in_quote = FALSE;
396         gboolean in_bracket = FALSE;
397         gchar *str;
398
399         edit_text = gtk_entry_get_text(entry);
400         if (edit_text == NULL) return NULL;
401
402         cur_pos = gtk_editable_get_position(GTK_EDITABLE(entry));
403
404         /* scan for a separator. doesn't matter if walk points at null byte. */
405         for (p = g_utf8_offset_to_pointer(edit_text, cur_pos);
406              p > edit_text;
407              p = g_utf8_prev_char(p)) {
408                 if (*p == '"') {
409                         in_quote = TRUE;
410                 } else if (!in_quote) {
411                         if (!in_bracket && *p == ',') {
412                                 break;
413                         } else if (*p == '<')
414                                 in_bracket = TRUE;
415                         else if (*p == '>')
416                                 in_bracket = FALSE;
417                 }
418         }
419
420         /* have something valid */
421         if (g_utf8_strlen(p, -1) == 0)
422                 return NULL;
423
424 #define IS_VALID_CHAR(x) \
425         (g_ascii_isalnum(x) || (x) == '"' || (x) == '<' || (((unsigned char)(x)) > 0x7f))
426
427         /* now scan back until we hit a valid character */
428         for (; *p && !IS_VALID_CHAR(*p); p = g_utf8_next_char(p))
429                 ;
430
431 #undef IS_VALID_CHAR
432
433         if (g_utf8_strlen(p, -1) == 0)
434                 return NULL;
435
436         if (start_pos) *start_pos = g_utf8_pointer_to_offset(edit_text, p);
437
438         str = g_strdup(p);
439
440         return str;
441
442
443 static gchar *get_complete_address_from_name_email(const gchar *name, const gchar *email)
444 {
445         gchar *address = NULL;
446         if (!name || name[0] == '\0')
447                 address = g_strdup_printf("<%s>", email);
448         else if (strchr_with_skip_quote(name, '"', ','))
449                 address = g_strdup_printf
450                         ("\"%s\" <%s>", name, email);
451         else
452                 address = g_strdup_printf
453                         ("%s <%s>", name, email);
454         return address;
455 }
456
457 /**
458  * Replace an incompleted address with a completed one.
459  * \param entry     Address entry field.
460  * \param newtext   New text.
461  * \param start_pos Insertion point in entry field.
462  */
463 static void replace_address_in_edit(GtkEntry *entry, const gchar *newtext,
464                              gint start_pos, gboolean is_group, GList *grp_emails)
465 {
466         if (!newtext) return;
467         gtk_editable_delete_text(GTK_EDITABLE(entry), start_pos, -1);
468         if (!is_group) {
469                 gtk_editable_insert_text(GTK_EDITABLE(entry), newtext, strlen(newtext),
470                                  &start_pos);
471         } else {
472                 gchar *addresses = NULL;
473                 GList *cur = grp_emails;
474                 for (; cur; cur = cur->next) {
475                         gchar *tmp;
476                         ItemEMail *email = (ItemEMail *)cur->data;
477                         ItemPerson *person = ( ItemPerson * ) ADDRITEM_PARENT(email);
478                         
479                         gchar *addr = get_complete_address_from_name_email(
480                                 ADDRITEM_NAME(person), email->address);
481                         if (addresses)
482                                 tmp = g_strdup_printf("%s, %s", addresses, addr);
483                         else
484                                 tmp = g_strdup_printf("%s", addr);
485                         g_free(addr);
486                         g_free(addresses);
487                         addresses = tmp;
488                 }
489                 gtk_editable_insert_text(GTK_EDITABLE(entry), addresses, strlen(addresses),
490                                  &start_pos);
491                 g_free(addresses);
492         }
493         gtk_editable_set_position(GTK_EDITABLE(entry), -1);
494 }
495
496 /**
497  * Attempt to complete an address, and returns the number of addresses found.
498  * Use <code>get_complete_address()</code> to get an entry from the index.
499  *
500  * \param  str Search string to find.
501  * \return Zero if no match was found, otherwise the number of addresses; the
502  *         original prefix (search string) will appear at index 0. 
503  */
504 guint complete_address(const gchar *str)
505 {
506         GList *result = NULL;
507         gchar *d = NULL;
508         guint  count = 0;
509         guint  cpl = 0;
510         completion_entry *ce = NULL;
511
512         cm_return_val_if_fail(str != NULL, 0);
513
514         /* g_completion is case sensitive */
515         d = g_utf8_strdown(str, -1);
516
517         clear_completion_cache();
518         g_completion_prefix = g_strdup(str);
519
520         result = g_completion_complete(g_completion, d, NULL);
521
522         count = g_list_length(result);
523         if (count) {
524                 /* create list with unique addresses  */
525                 for (cpl = 0, result = g_list_first(result);
526                      result != NULL;
527                      result = g_list_next(result)) {
528                         ce = (completion_entry *)(result->data);
529                         if (NULL == g_slist_find(g_completion_addresses,
530                                                  ce->ref)) {
531                                 cpl++;
532                                 g_completion_addresses =
533                                         g_slist_append(g_completion_addresses,
534                                                        ce->ref);
535                         }
536                 }
537                 count = cpl + 1;        /* index 0 is the original prefix */
538                 g_completion_next = 1;  /* we start at the first completed one */
539         } else {
540                 g_free(g_completion_prefix);
541                 g_completion_prefix = NULL;
542         }
543
544         g_completion_count = count;
545
546         g_free(d);
547
548         return count;
549 }
550
551 /**
552  * complete_matches_found() returns the number of matched addresses according
553  * to the completion mechanism. Unlike complete_address(), the returned value
554  * doesn't count str itself. If there's no match, it returns 0.
555  * To get a list of completion matches, see complete_address() instead.
556  */
557 guint complete_matches_found(const gchar *str)
558 {
559         GList *result = NULL;
560         gchar *d = NULL;
561
562         cm_return_val_if_fail(str != NULL, 0);
563
564         /* g_completion is case sensitive */
565         d = g_utf8_strdown(str, -1);
566
567         clear_completion_cache();
568         g_completion_prefix = g_strdup(str);
569
570         result = g_completion_complete(g_completion, d, NULL);
571
572         g_free(g_completion_prefix);
573         g_free(d);
574
575         return g_list_length(result);
576 }
577
578 /**
579  * Return a complete address from the index.
580  * \param index Index of entry that was found (by the previous call to
581  *              <code>complete_address()</code>
582  * \return Completed address string; this should be freed when done.
583  */
584 gchar *get_complete_address(gint index)
585 {
586         const address_entry *p;
587         gchar *address = NULL;
588
589         if (index < g_completion_count) {
590                 if (index == 0)
591                         address = g_strdup(g_completion_prefix);
592                 else {
593                         /* get something from the unique addresses */
594                         p = (address_entry *)g_slist_nth_data
595                                 (g_completion_addresses, index - 1);
596                         if (p != NULL && p->address != NULL) {
597                                 address = get_complete_address_from_name_email(p->name, p->address);
598                         } else if (p != NULL && p->address == NULL && p->name != NULL) {
599                                 /* that's a group */
600                                 address = g_strdup_printf("%s (%s) <!--___group___-->", p->name, _("Group"));
601                                 if (!_groupAddresses_) {
602                                         _groupAddresses_ = g_hash_table_new(NULL, g_direct_equal);
603                                 }
604                                 if (!g_hash_table_lookup(_groupAddresses_, GINT_TO_POINTER(g_str_hash(address)))) {
605                                         g_hash_table_insert(_groupAddresses_, GINT_TO_POINTER(g_str_hash(address)), p->grp_emails);
606
607                                 }
608                         }
609                 }
610         }
611
612         return address;
613 }
614
615 /**
616  * Return the next complete address match from the completion index.
617  * \return Completed address string; this should be freed when done.
618  */
619 static gchar *get_next_complete_address(void)
620 {
621         if (is_completion_pending()) {
622                 gchar *res;
623
624                 res = get_complete_address(g_completion_next);
625                 g_completion_next += 1;
626                 if (g_completion_next >= g_completion_count)
627                         g_completion_next = 0;
628
629                 return res;
630         } else
631                 return NULL;
632 }
633
634 /**
635  * Return a count of the completed matches in the completion index.
636  * \return Number of matched entries.
637  */
638 static guint get_completion_count(void)
639 {
640         if (is_completion_pending())
641                 return g_completion_count;
642         else
643                 return 0;
644 }
645
646 /**
647  * Invalidate address completion index. This function should be called whenever
648  * the address book changes. This forces data to be read into the completion
649  * data.
650  * \return Number of entries in index.
651  */
652 gint invalidate_address_completion(void)
653 {
654         if (g_ref_count) {
655                 /* simply the same as start_address_completion() */
656                 debug_print("Invalidation request for address completion\n");
657                 read_address_book(completion_folder_path);
658                 clear_completion_cache();
659         }
660
661         return g_list_length(g_completion_list);
662 }
663
664 /**
665  * Finished with completion index. This function should be called after
666  * matching addresses.
667  * \return Reference count.
668  */
669 gint end_address_completion(void)
670 {
671         gboolean different_folder = FALSE;
672         clear_completion_cache();
673
674         /* reset the folderpath to NULL */
675         if (completion_folder_path) {
676                 g_free(completion_folder_path);
677                 completion_folder_path = NULL;
678                 different_folder = TRUE;
679         }
680         if (0 == --g_ref_count)
681                 free_all();
682
683         debug_print("end_address_completion ref count %d\n", g_ref_count);
684         if (g_ref_count && different_folder) {
685                 debug_print("still ref'd, different folder\n");
686                 invalidate_address_completion();
687         }
688
689         return g_ref_count; 
690 }
691
692 /**
693  * Completion window.
694  */
695 static CompletionWindow *_compWindow_ = NULL;
696
697 /**
698  * Mutex to protect callback from multiple threads.
699  */
700 static pthread_mutex_t _completionMutex_ = PTHREAD_MUTEX_INITIALIZER;
701
702 /**
703  * Completion queue list.
704  */
705 static GList *_displayQueue_ = NULL;
706 /**
707  * Current query ID.
708  */
709 static gint _queryID_ = 0;
710
711 /**
712  * Completion idle ID.
713  */
714 static guint _completionIdleID_ = 0;
715
716 /*
717  * address completion entry ui. the ui (completion list was inspired by galeon's
718  * auto completion list). remaining things powered by claws's completion engine.
719  */
720
721 #define ENTRY_DATA_TAB_HOOK     "tab_hook"      /* used to lookup entry */
722 #define ENTRY_DATA_ALLOW_COMMAS "allowcommas"   /* used to know whether to present groups */
723
724 static void address_completion_mainwindow_set_focus     (GtkWindow   *window,
725                                                          GtkWidget   *widget,
726                                                          gpointer     data);
727 static gboolean address_completion_entry_key_pressed    (GtkEntry    *entry,
728                                                          GdkEventKey *ev,
729                                                          gpointer     data);
730 static gboolean address_completion_complete_address_in_entry
731                                                         (GtkEntry    *entry,
732                                                          gboolean     next);
733 static void address_completion_create_completion_window (GtkEntry    *entry);
734
735 static gboolean completion_window_button_press
736                                         (GtkWidget       *widget,
737                                          GdkEventButton  *event,
738                                          CompletionWindow *compWin );
739
740 static gboolean completion_window_key_press
741                                         (GtkWidget       *widget,
742                                          GdkEventKey     *event,
743                                          CompletionWindow *compWin );
744 static void address_completion_create_completion_window( GtkEntry *entry_ );
745
746 /**
747  * Create a completion window object.
748  * \return Initialized completion window.
749  */
750 static CompletionWindow *addrcompl_create_window( void ) {
751         CompletionWindow *cw;
752
753         cw = g_new0( CompletionWindow, 1 );
754         cw->listCount = 0;
755         cw->searchTerm = NULL;
756         cw->window = NULL;
757         cw->entry = NULL;
758         cw->list_view = NULL;
759         cw->in_mouse = FALSE;
760         cw->destroying = FALSE;
761
762         return cw;      
763 }
764
765 /**
766  * Destroy completion window.
767  * \param cw Window to destroy.
768  */
769 static void addrcompl_destroy_window( CompletionWindow *cw ) {
770         /* Stop all searches currently in progress */
771 #ifndef USE_NEW_ADDRBOOK
772         addrindex_stop_search( _queryID_ );
773 #endif
774         /* Remove idler function... or application may not terminate */
775         if( _completionIdleID_ != 0 ) {
776                 g_source_remove( _completionIdleID_ );
777                 _completionIdleID_ = 0;
778         }
779
780         /* Now destroy window */        
781         if( cw ) {
782                 /* Clear references to widgets */
783                 cw->entry = NULL;
784                 cw->list_view = NULL;
785
786                 /* Free objects */
787                 if( cw->window ) {
788                         gtk_widget_hide( cw->window );
789                         gtk_widget_destroy( cw->window );
790                 }
791                 cw->window = NULL;
792                 cw->destroying = FALSE;
793                 cw->in_mouse = FALSE;
794         }
795         
796 }
797
798 /**
799  * Free up completion window.
800  * \param cw Window to free.
801  */
802 static void addrcompl_free_window( CompletionWindow *cw ) {
803         if( cw ) {
804                 addrcompl_destroy_window( cw );
805
806                 g_free( cw->searchTerm );
807                 cw->searchTerm = NULL;
808
809                 /* Clear references */          
810                 cw->listCount = 0;
811
812                 /* Free object */               
813                 g_free( cw );
814         }
815 }
816
817 /**
818  * Advance selection to previous/next item in list.
819  * \param list_view List to process.
820  * \param forward Set to <i>TRUE</i> to select next or <i>FALSE</i> for
821  *                previous entry.
822  */
823 static void completion_window_advance_selection(GtkTreeView *list_view, gboolean forward)
824 {
825         GtkTreeSelection *selection;
826         GtkTreeIter iter;
827         GtkTreeModel *model;
828
829         cm_return_if_fail(list_view != NULL);
830
831         selection = gtk_tree_view_get_selection(list_view);
832         if (!gtk_tree_selection_get_selected(selection, &model, &iter))
833                 return;
834
835         if (forward) { 
836                 forward = gtk_tree_model_iter_next(model, &iter);
837                 if (forward) 
838                         gtk_tree_selection_select_iter(selection, &iter);
839         } else {
840                 GtkTreePath *prev;
841
842                 prev = gtk_tree_model_get_path(model, &iter);
843                 if (!prev) 
844                         return;
845
846                 if (gtk_tree_path_prev(prev))
847                         gtk_tree_selection_select_path(selection, prev);
848                 
849                 gtk_tree_path_free(prev);
850         }
851 }
852
853 /**
854  * Resize window to accommodate maximum number of address entries.
855  * \param cw Completion window.
856  */
857 static void addrcompl_resize_window( CompletionWindow *cw ) {
858         GtkRequisition r;
859         gint x, y, width, height, depth;
860
861         /* Get current geometry of window */
862         gdk_window_get_geometry( gtk_widget_get_window( cw->window ), &x, &y, &width, &height, &depth );
863
864         /* simple _hide breaks size requisition !? */
865         gtk_widget_hide_all( cw->window );
866         gtk_widget_show_all( cw->window );
867         gtk_widget_size_request( cw->list_view, &r );
868
869         /* Adjust window height to available screen space */
870         if( y + r.height > gdk_screen_height())
871                 r.height = gdk_screen_height() - y;
872
873         gtk_widget_set_size_request(cw->window, width, r.height);
874
875         gdk_pointer_grab(gtk_widget_get_window(cw->window), TRUE,
876                          GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK |
877                          GDK_BUTTON_RELEASE_MASK,
878                          NULL, NULL, GDK_CURRENT_TIME);
879         gdk_keyboard_grab(gtk_widget_get_window(cw->window), FALSE, GDK_CURRENT_TIME);
880         gtk_grab_add(cw->window);
881
882 }
883
884 static GdkPixbuf *group_pixbuf = NULL;
885 static GdkPixbuf *email_pixbuf = NULL;
886
887 /**
888  * Add an address the completion window address list.
889  * \param cw      Completion window.
890  * \param address Address to add.
891  */
892 static void addrcompl_add_entry( CompletionWindow *cw, gchar *address ) {
893         GtkListStore *store;
894         GtkTreeIter iter;
895         GtkTreeSelection *selection;
896         gboolean is_group = FALSE;
897         GList *grp_emails = NULL;
898         store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(cw->list_view)));
899         GdkPixbuf *pixbuf;
900         
901         if (!group_pixbuf) {
902                 stock_pixbuf_gdk(cw->list_view, STOCK_PIXMAP_ADDR_TWO, &group_pixbuf);
903                 g_object_ref(G_OBJECT(group_pixbuf));
904         }
905         if (!email_pixbuf) {
906                 stock_pixbuf_gdk(cw->list_view, STOCK_PIXMAP_ADDR_ONE, &email_pixbuf);
907                 g_object_ref(G_OBJECT(email_pixbuf));
908         }
909         /* g_print( "\t\tAdding :%s\n", address ); */
910         if (strstr(address, " <!--___group___-->")) {
911                 is_group = TRUE;
912                 if (_groupAddresses_)
913                         grp_emails = g_hash_table_lookup(_groupAddresses_, GINT_TO_POINTER(g_str_hash(address)));
914                 *(strstr(address, " <!--___group___-->")) = '\0';
915                 pixbuf = group_pixbuf;
916         } else if (strchr(address, '@') && strchr(address, '<') &&
917                    strchr(address, '>')) {
918                 pixbuf = email_pixbuf;
919         } else
920                 pixbuf = NULL;
921         
922         if (is_group && !_allowCommas_)
923                 return;
924         gtk_list_store_append(store, &iter);
925         gtk_list_store_set(store, &iter, 
926                                 ADDR_COMPL_ICON, pixbuf,
927                                 ADDR_COMPL_ADDRESS, address, 
928                                 ADDR_COMPL_ISGROUP, is_group, 
929                                 ADDR_COMPL_GROUPLIST, grp_emails,
930                                 -1);
931         cw->listCount++;
932
933         /* Resize window */
934         addrcompl_resize_window( cw );
935         gtk_grab_add( cw->window );
936
937         selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(cw->list_view));
938         gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store), &iter);
939
940         if( cw->listCount == 1 ) {
941                 /* Select first row for now */
942                 gtk_tree_selection_select_iter(selection, &iter);
943         }
944 #ifndef GENERIC_UMPC
945         else if( cw->listCount == 2 ) {
946                 gtk_tree_model_iter_next(GTK_TREE_MODEL(store), &iter);
947                 /* Move off first row */
948                 gtk_tree_selection_select_iter(selection, &iter);
949         }
950 #endif
951 }
952
953 /**
954  * Completion idle function. This function is called by the main (UI) thread
955  * during UI idle time while an address search is in progress. Items from the
956  * display queue are processed and appended to the address list.
957  *
958  * \param data Target completion window to receive email addresses.
959  * \return <i>TRUE</i> to ensure that idle event do not get ignored.
960  */
961 static gboolean addrcompl_idle( gpointer data ) {
962         GList *node;
963         gchar *address;
964
965         /* Process all entries in display queue */
966         pthread_mutex_lock( & _completionMutex_ );
967         if( _displayQueue_ ) {
968                 node = _displayQueue_;
969                 while( node ) {
970                         address = node->data;
971                         /* g_print( "address ::: %s :::\n", address ); */
972                         addrcompl_add_entry( _compWindow_, address );
973                         g_free( address );
974                         node = g_list_next( node );
975                 }
976                 g_list_free( _displayQueue_ );
977                 _displayQueue_ = NULL;
978         }
979         pthread_mutex_unlock( & _completionMutex_ );
980         claws_do_idle();
981
982         return TRUE;
983 }
984
985 /**
986  * Callback entry point. The background thread (if any) appends the address
987  * list to the display queue.
988  * \param sender     Sender of query.
989  * \param queryID    Query ID of search request.
990  * \param listEMail  List of zero of more email objects that met search
991  *                   criteria.
992  * \param data       Query data.
993  */
994 #ifndef USE_NEW_ADDRBOOK
995 static gint addrcompl_callback_entry(
996         gpointer sender, gint queryID, GList *listEMail, gpointer data )
997 {
998         GList *node;
999         gchar *address;
1000
1001         /* g_print( "addrcompl_callback_entry::queryID=%d\n", queryID ); */
1002         pthread_mutex_lock( & _completionMutex_ );
1003         if( queryID == _queryID_ ) {
1004                 /* Append contents to end of display queue */
1005                 node = listEMail;
1006                 while( node ) {
1007                         ItemEMail *email = node->data;
1008
1009                         address = addritem_format_email( email );
1010                         /* g_print( "\temail/address ::%s::\n", address ); */
1011                         _displayQueue_ = g_list_append( _displayQueue_, address );
1012                         node = g_list_next( node );
1013                 }
1014         }
1015         g_list_free( listEMail );
1016         pthread_mutex_unlock( & _completionMutex_ );
1017
1018         return 0;
1019 }
1020 #endif
1021
1022 /**
1023  * Clear the display queue.
1024  */
1025 static void addrcompl_clear_queue( void ) {
1026         /* Clear out display queue */
1027         pthread_mutex_lock( & _completionMutex_ );
1028
1029         g_list_free( _displayQueue_ );
1030         _displayQueue_ = NULL;
1031
1032         pthread_mutex_unlock( & _completionMutex_ );
1033 }
1034
1035 /**
1036  * Add a single address entry into the display queue.
1037  * \param address Address to append.
1038  */
1039 static void addrcompl_add_queue( gchar *address ) {
1040         pthread_mutex_lock( & _completionMutex_ );
1041         _displayQueue_ = g_list_append( _displayQueue_, address );
1042         pthread_mutex_unlock( & _completionMutex_ );
1043 }
1044
1045 /**
1046  * Load list with entries from local completion index.
1047  */
1048 static void addrcompl_load_local( void ) {
1049         guint count = 0;
1050
1051         for (count = 0; count < get_completion_count(); count++) {
1052                 gchar *address;
1053
1054                 address = get_complete_address( count );
1055                 /* g_print( "\taddress ::%s::\n", address ); */
1056
1057                 /* Append contents to end of display queue */
1058                 addrcompl_add_queue( address );
1059         }
1060 }
1061
1062 /**
1063  * Start the search.
1064  */
1065 static void addrcompl_start_search( void ) {
1066 #ifndef USE_NEW_ADDRBOOK
1067         gchar *searchTerm;
1068
1069         searchTerm = g_strdup( _compWindow_->searchTerm );
1070
1071         /* Setup the search */
1072         _queryID_ = addrindex_setup_search(
1073                 searchTerm, NULL, addrcompl_callback_entry );
1074         g_free( searchTerm );
1075 #endif
1076         /* g_print( "addrcompl_start_search::queryID=%d\n", _queryID_ ); */
1077
1078         /* Load local stuff */
1079         addrcompl_load_local();
1080
1081         /* Sit back and wait until something happens */
1082         _completionIdleID_ =
1083                 g_idle_add( (GSourceFunc) addrcompl_idle, NULL );
1084         /* g_print( "addrindex_start_search::queryID=%d\n", _queryID_ ); */
1085
1086 #ifndef USE_NEW_ADDRBOOK
1087         addrindex_start_search( _queryID_ );
1088 #else
1089         
1090 #endif
1091 }
1092
1093 /**
1094  * Apply the current selection in the list to the entry field. Focus is also
1095  * moved to the next widget so that Tab key works correctly.
1096  * \param list_view List to process.
1097  * \param entry Address entry field.
1098  * \param move_focus Move focus to the next widget ?
1099  */
1100 static void completion_window_apply_selection(GtkTreeView *list_view,
1101                                                 GtkEntry *entry,
1102                                                 gboolean move_focus)
1103 {
1104         gchar *address = NULL, *text = NULL;
1105         gint   cursor_pos;
1106         GtkWidget *parent;
1107         GtkTreeSelection *selection;
1108         GtkTreeModel *model;
1109         GtkTreeIter iter;
1110         gboolean is_group = FALSE;
1111         cm_return_if_fail(list_view != NULL);
1112         cm_return_if_fail(entry != NULL);
1113         GList *grp_emails = NULL;
1114
1115         selection = gtk_tree_view_get_selection(list_view);
1116         if (! gtk_tree_selection_get_selected(selection, &model, &iter))
1117                 return;
1118
1119         /* First remove the idler */
1120         if( _completionIdleID_ != 0 ) {
1121                 g_source_remove( _completionIdleID_ );
1122                 _completionIdleID_ = 0;
1123         }
1124
1125         /* Process selected item */
1126         gtk_tree_model_get(model, &iter, ADDR_COMPL_ADDRESS, &text, 
1127                                 ADDR_COMPL_ISGROUP, &is_group, 
1128                                 ADDR_COMPL_GROUPLIST, &grp_emails,
1129                                 -1);
1130
1131         address = get_address_from_edit(entry, &cursor_pos);
1132         g_free(address);
1133         replace_address_in_edit(entry, text, cursor_pos, is_group, grp_emails);
1134         g_free(text);
1135
1136         /* Move focus to next widget */
1137         parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1138         if( parent && move_focus) {
1139                 gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1140         }
1141 }
1142
1143 /**
1144  * Start address completion. Should be called when creating the main window
1145  * containing address completion entries.
1146  * \param mainwindow Main window.
1147  */
1148 void address_completion_start(GtkWidget *mainwindow)
1149 {
1150         start_address_completion(NULL);
1151
1152         /* register focus change hook */
1153         g_signal_connect(G_OBJECT(mainwindow), "set_focus",
1154                          G_CALLBACK(address_completion_mainwindow_set_focus),
1155                          mainwindow);
1156 }
1157
1158 /**
1159  * Need unique data to make unregistering signal handler possible for the auto
1160  * completed entry.
1161  */
1162 #define COMPLETION_UNIQUE_DATA (GINT_TO_POINTER(0xfeefaa))
1163
1164 /**
1165  * Register specified entry widget for address completion.
1166  * \param entry Address entry field.
1167  */
1168 void address_completion_register_entry(GtkEntry *entry, gboolean allow_commas)
1169 {
1170         cm_return_if_fail(entry != NULL);
1171         cm_return_if_fail(GTK_IS_ENTRY(entry));
1172
1173         /* add hooked property */
1174         g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, entry);
1175         g_object_set_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS, GINT_TO_POINTER(allow_commas));
1176
1177         /* add keypress event */
1178         g_signal_connect_closure
1179                 (G_OBJECT(entry), "key_press_event",
1180                  g_cclosure_new(G_CALLBACK(address_completion_entry_key_pressed),
1181                                 COMPLETION_UNIQUE_DATA,
1182                                 NULL),
1183                  FALSE); /* magic */
1184 }
1185
1186 /**
1187  * Unregister specified entry widget from address completion operations.
1188  * \param entry Address entry field.
1189  */
1190 void address_completion_unregister_entry(GtkEntry *entry)
1191 {
1192         GObject *entry_obj;
1193
1194         cm_return_if_fail(entry != NULL);
1195         cm_return_if_fail(GTK_IS_ENTRY(entry));
1196
1197         entry_obj = g_object_get_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK);
1198         cm_return_if_fail(entry_obj);
1199         cm_return_if_fail(G_OBJECT(entry_obj) == G_OBJECT(entry));
1200
1201         /* has the hooked property? */
1202         g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, NULL);
1203
1204         /* remove the hook */
1205         g_signal_handlers_disconnect_by_func(G_OBJECT(entry), 
1206                         G_CALLBACK(address_completion_entry_key_pressed),
1207                         COMPLETION_UNIQUE_DATA);
1208 }
1209
1210 /**
1211  * End address completion. Should be called when main window with address
1212  * completion entries terminates. NOTE: this function assumes that it is
1213  * called upon destruction of the window.
1214  * \param mainwindow Main window.
1215  */
1216 void address_completion_end(GtkWidget *mainwindow)
1217 {
1218         /* if address_completion_end() is really called on closing the window,
1219          * we don't need to unregister the set_focus_cb */
1220         end_address_completion();
1221 }
1222
1223 /* if focus changes to another entry, then clear completion cache */
1224 static void address_completion_mainwindow_set_focus(GtkWindow *window,
1225                                                     GtkWidget *widget,
1226                                                     gpointer   data)
1227 {
1228         
1229         if (widget && GTK_IS_ENTRY(widget) &&
1230             g_object_get_data(G_OBJECT(widget), ENTRY_DATA_TAB_HOOK)) {
1231                 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), ENTRY_DATA_ALLOW_COMMAS));
1232                 clear_completion_cache();
1233         }
1234 }
1235
1236 /**
1237  * Listener that watches for tab or other keystroke in address entry field.
1238  * \param entry Address entry field.
1239  * \param ev    Event object.
1240  * \param data  User data.
1241  * \return <i>TRUE</i>.
1242  */
1243 static gboolean address_completion_entry_key_pressed(GtkEntry    *entry,
1244                                                      GdkEventKey *ev,
1245                                                      gpointer     data)
1246 {
1247         if (ev->keyval == GDK_KEY_Tab) {
1248                 addrcompl_clear_queue();
1249                 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS));
1250                 if( address_completion_complete_address_in_entry( entry, TRUE ) ) {
1251                         /* route a void character to the default handler */
1252                         /* this is a dirty hack; we're actually changing a key
1253                          * reported by the system. */
1254                         ev->keyval = GDK_KEY_AudibleBell_Enable;
1255                         ev->state &= ~GDK_SHIFT_MASK;
1256
1257                         /* Create window */                     
1258                         address_completion_create_completion_window(entry);
1259
1260                         /* Start remote queries */
1261                         addrcompl_start_search();
1262
1263                         return TRUE;
1264                 }
1265                 else {
1266                         /* old behaviour */
1267                 }
1268         } else if (ev->keyval == GDK_KEY_Shift_L
1269                 || ev->keyval == GDK_KEY_Shift_R
1270                 || ev->keyval == GDK_KEY_Control_L
1271                 || ev->keyval == GDK_KEY_Control_R
1272                 || ev->keyval == GDK_KEY_Caps_Lock
1273                 || ev->keyval == GDK_KEY_Shift_Lock
1274                 || ev->keyval == GDK_KEY_Meta_L
1275                 || ev->keyval == GDK_KEY_Meta_R
1276                 || ev->keyval == GDK_KEY_Alt_L
1277                 || ev->keyval == GDK_KEY_Alt_R) {
1278                 /* these buttons should not clear the cache... */
1279         } else
1280                 clear_completion_cache();
1281
1282         return FALSE;
1283 }
1284 /**
1285  * Initialize search term for address completion.
1286  * \param entry Address entry field.
1287  */
1288 static gboolean address_completion_complete_address_in_entry(GtkEntry *entry,
1289                                                              gboolean  next)
1290 {
1291         gint ncount, cursor_pos;
1292         gchar *searchTerm, *new = NULL;
1293
1294         cm_return_val_if_fail(entry != NULL, FALSE);
1295
1296         if (!gtk_widget_has_focus(GTK_WIDGET(entry))) return FALSE;
1297
1298         /* get an address component from the cursor */
1299         searchTerm = get_address_from_edit( entry, &cursor_pos );
1300         if( ! searchTerm ) return FALSE;
1301         /* g_print( "search for :::%s:::\n", searchTerm ); */
1302
1303         /* Clear any existing search */
1304         g_free( _compWindow_->searchTerm );
1305         _compWindow_->searchTerm = g_strdup( searchTerm );
1306
1307         /* Perform search on local completion index */
1308         ncount = complete_address( searchTerm );
1309         if( 0 < ncount ) {
1310                 new = get_next_complete_address();
1311                 g_free( new );
1312         }
1313 #if (!defined(USE_LDAP) && !defined(GENERIC_UMPC))
1314         /* Select the address if there is only one match */
1315         if (ncount == 2) {
1316                 /* Display selected address in entry field */           
1317                 gchar *addr = get_complete_address(1);
1318                 if (addr && !strstr(addr, " <!--___group___-->")) {
1319                         replace_address_in_edit(entry, addr, cursor_pos, FALSE, NULL);
1320                         /* Discard the window */
1321                         clear_completion_cache();
1322                 } 
1323                 g_free(addr);
1324         }
1325         /* Make sure that drop-down appears uniform! */
1326         else 
1327 #endif
1328         if( ncount == 0 ) {
1329                 addrcompl_add_queue( g_strdup( searchTerm ) );
1330         }
1331         g_free( searchTerm );
1332
1333         return TRUE;
1334 }
1335
1336 /**
1337  * Create new address completion window for specified entry.
1338  * \param entry_ Entry widget to associate with window.
1339  */
1340 static void address_completion_create_completion_window( GtkEntry *entry_ )
1341 {
1342         gint x, y, height, width, depth;
1343         GtkWidget *scroll, *list_view;
1344         GtkRequisition r;
1345         GtkWidget *window;
1346         GtkWidget *entry = GTK_WIDGET(entry_);
1347         GdkWindow *gdkwin;
1348
1349         /* Create new window and list */
1350         window = gtk_window_new(GTK_WINDOW_POPUP);
1351         list_view  = addr_compl_list_view_create(_compWindow_);
1352
1353         /* Destroy any existing window */
1354         addrcompl_destroy_window( _compWindow_ );
1355
1356         /* Create new object */
1357         _compWindow_->window    = window;
1358         _compWindow_->entry     = entry;
1359         _compWindow_->list_view = list_view;
1360         _compWindow_->listCount = 0;
1361         _compWindow_->in_mouse  = FALSE;
1362
1363         scroll = gtk_scrolled_window_new(NULL, NULL);
1364         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
1365                                        GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
1366         gtk_container_add(GTK_CONTAINER(window), scroll);
1367         gtk_container_add(GTK_CONTAINER(scroll), list_view);
1368         gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll),
1369                 GTK_SHADOW_OUT);
1370         /* Use entry widget to create initial window */
1371         gdkwin = gtk_widget_get_window(entry),
1372         gdk_window_get_geometry(gdkwin, &x, &y, &width, &height, &depth);
1373         gdk_window_get_origin (gdkwin, &x, &y);
1374         y += height;
1375         gtk_window_move(GTK_WINDOW(window), x, y);
1376
1377         /* Resize window to fit initial (empty) address list */
1378         gtk_widget_size_request( list_view, &r );
1379         gtk_widget_set_size_request( window, width, r.height );
1380         gtk_widget_show_all( window );
1381         gtk_widget_size_request( list_view, &r );
1382
1383         /* Setup handlers */
1384         g_signal_connect(G_OBJECT(list_view), "button_press_event",
1385                          G_CALLBACK(list_view_button_press),
1386                          _compWindow_);
1387                          
1388         g_signal_connect(G_OBJECT(list_view), "button_release_event",
1389                          G_CALLBACK(list_view_button_release),
1390                          _compWindow_);
1391         
1392         g_signal_connect(G_OBJECT(window),
1393                          "button-press-event",
1394                          G_CALLBACK(completion_window_button_press),
1395                          _compWindow_ );
1396         g_signal_connect(G_OBJECT(window),
1397                          "key-press-event",
1398                          G_CALLBACK(completion_window_key_press),
1399                          _compWindow_ );
1400         gdk_pointer_grab(gtk_widget_get_window(window), TRUE,
1401                          GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK |
1402                          GDK_BUTTON_RELEASE_MASK,
1403                          NULL, NULL, GDK_CURRENT_TIME);
1404         gdk_keyboard_grab(gtk_widget_get_window(window), FALSE, GDK_CURRENT_TIME);
1405         gtk_grab_add( window );
1406 }
1407
1408 /**
1409  * Respond to button press in completion window. Check if mouse click is
1410  * anywhere outside the completion window. In that case the completion
1411  * window is destroyed, and the original searchTerm is restored.
1412  *
1413  * \param widget   Window object.
1414  * \param event    Event.
1415  * \param compWin  Reference to completion window.
1416  */
1417 static gboolean completion_window_button_press(GtkWidget *widget,
1418                                                GdkEventButton *event,
1419                                                CompletionWindow *compWin )
1420 {
1421         GtkWidget *event_widget, *entry;
1422         gchar *searchTerm;
1423         gint cursor_pos;
1424         gboolean restore = TRUE;
1425
1426         cm_return_val_if_fail(compWin != NULL, FALSE);
1427
1428         entry = compWin->entry;
1429         cm_return_val_if_fail(entry != NULL, FALSE);
1430
1431         /* Test where mouse was clicked */
1432         event_widget = gtk_get_event_widget((GdkEvent *)event);
1433         if (event_widget != widget) {
1434                 while (event_widget) {
1435                         if (event_widget == widget)
1436                                 return FALSE;
1437                         else if (event_widget == entry) {
1438                                 restore = FALSE;
1439                                 break;
1440                         }
1441                         event_widget = gtk_widget_get_parent(event_widget);
1442                 }
1443         }
1444
1445         if (restore) {
1446                 /* Clicked outside of completion window - restore */
1447                 searchTerm = _compWindow_->searchTerm;
1448                 g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1449                 replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos, FALSE, NULL);
1450         }
1451
1452         clear_completion_cache();
1453         addrcompl_destroy_window( _compWindow_ );
1454
1455         return TRUE;
1456 }
1457
1458 /**
1459  * Respond to key press in completion window.
1460  * \param widget   Window object.
1461  * \param event    Event.
1462  * \param compWind Reference to completion window.
1463  */
1464 static gboolean completion_window_key_press(GtkWidget *widget,
1465                                             GdkEventKey *event,
1466                                             CompletionWindow *compWin )
1467 {
1468         GdkEventKey tmp_event;
1469         GtkWidget *entry;
1470         gchar *searchTerm;
1471         gint cursor_pos;
1472         GtkWidget *list_view;
1473         GtkWidget *parent;
1474         cm_return_val_if_fail(compWin != NULL, FALSE);
1475
1476         entry = compWin->entry;
1477         list_view = compWin->list_view;
1478         cm_return_val_if_fail(entry != NULL, FALSE);
1479
1480         /* allow keyboard navigation in the alternatives tree view */
1481         if (event->keyval == GDK_KEY_Up || event->keyval == GDK_KEY_Down ||
1482             event->keyval == GDK_KEY_Page_Up || event->keyval == GDK_KEY_Page_Down) {
1483                 completion_window_advance_selection
1484                         (GTK_TREE_VIEW(list_view),
1485                          event->keyval == GDK_KEY_Down ||
1486                          event->keyval == GDK_KEY_Page_Down ? TRUE : FALSE);
1487                 return FALSE;
1488         }               
1489
1490         /* make tab move to next field */
1491         if( event->keyval == GDK_KEY_Tab ) {
1492                 /* Reference to parent */
1493                 parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1494
1495                 /* Discard the window */
1496                 clear_completion_cache();
1497                 addrcompl_destroy_window( _compWindow_ );
1498
1499                 /* Move focus to next widget */
1500                 if( parent ) {
1501                         gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1502                 }
1503                 return FALSE;
1504         }
1505
1506         /* make backtab move to previous field */
1507         if( event->keyval == GDK_KEY_ISO_Left_Tab ) {
1508                 /* Reference to parent */
1509                 parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1510
1511                 /* Discard the window */
1512                 clear_completion_cache();
1513                 addrcompl_destroy_window( _compWindow_ );
1514
1515                 /* Move focus to previous widget */
1516                 if( parent ) {
1517                         gtk_widget_child_focus( parent, GTK_DIR_TAB_BACKWARD );
1518                 }
1519                 return FALSE;
1520         }
1521         _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS));
1522
1523         /* look for presses that accept the selection */
1524         if (event->keyval == GDK_KEY_Return || event->keyval == GDK_KEY_space ||
1525                         event->keyval == GDK_KEY_KP_Enter ||
1526                         (_allowCommas_ && event->keyval == GDK_KEY_comma)) {
1527                 /* User selected address with a key press */
1528
1529                 /* Display selected address in entry field */           
1530                 completion_window_apply_selection(
1531                         GTK_TREE_VIEW(list_view), GTK_ENTRY(entry),
1532                         event->keyval != GDK_KEY_comma);
1533
1534                 if (event->keyval == GDK_KEY_comma) {
1535                         gint pos = gtk_editable_get_position(GTK_EDITABLE(entry));
1536                         gtk_editable_insert_text(GTK_EDITABLE(entry), ", ", 2, &pos);
1537                         gtk_editable_set_position(GTK_EDITABLE(entry), pos + 1);
1538                 }
1539
1540                 /* Discard the window */
1541                 clear_completion_cache();
1542                 addrcompl_destroy_window( _compWindow_ );
1543                 return FALSE;
1544         }
1545
1546         /* key state keys should never be handled */
1547         if (event->keyval == GDK_KEY_Shift_L
1548                  || event->keyval == GDK_KEY_Shift_R
1549                  || event->keyval == GDK_KEY_Control_L
1550                  || event->keyval == GDK_KEY_Control_R
1551                  || event->keyval == GDK_KEY_Caps_Lock
1552                  || event->keyval == GDK_KEY_Shift_Lock
1553                  || event->keyval == GDK_KEY_Meta_L
1554                  || event->keyval == GDK_KEY_Meta_R
1555                  || event->keyval == GDK_KEY_Alt_L
1556                  || event->keyval == GDK_KEY_Alt_R) {
1557                 return FALSE;
1558         }
1559
1560         /* some other key, let's restore the searchTerm (orignal text) */
1561         searchTerm = _compWindow_->searchTerm;
1562         g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1563         replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos, FALSE, NULL);
1564
1565         /* make sure anything we typed comes in the edit box */
1566         tmp_event.type       = event->type;
1567         tmp_event.window     = gtk_widget_get_window(GTK_WIDGET(entry));
1568         tmp_event.send_event = TRUE;
1569         tmp_event.time       = event->time;
1570         tmp_event.state      = event->state;
1571         tmp_event.keyval     = event->keyval;
1572         tmp_event.length     = event->length;
1573         tmp_event.string     = event->string;
1574         gtk_widget_event(entry, (GdkEvent *)&tmp_event);
1575
1576         /* and close the completion window */
1577         clear_completion_cache();
1578         addrcompl_destroy_window( _compWindow_ );
1579
1580         return TRUE;
1581 }
1582
1583 /*
1584  * ============================================================================
1585  * Publically accessible functions.
1586  * ============================================================================
1587  */
1588
1589 /**
1590  * Setup completion object.
1591  */
1592 void addrcompl_initialize( void ) {
1593         /* g_print( "addrcompl_initialize...\n" ); */
1594         if( ! _compWindow_ ) {
1595                 _compWindow_ = addrcompl_create_window();
1596         }
1597         _queryID_ = 0;
1598         _completionIdleID_ = 0;
1599         /* g_print( "addrcompl_initialize...done\n" ); */
1600 }
1601
1602 /**
1603  * Teardown completion object.
1604  */
1605 void addrcompl_teardown( void ) {
1606         /* g_print( "addrcompl_teardown...\n" ); */
1607         addrcompl_free_window( _compWindow_ );
1608         _compWindow_ = NULL;
1609         if( _displayQueue_ ) {
1610                 g_list_free( _displayQueue_ );
1611         }
1612         _displayQueue_ = NULL;
1613         _completionIdleID_ = 0;
1614         /* g_print( "addrcompl_teardown...done\n" ); */
1615 }
1616
1617 /*
1618  * tree view functions
1619  */
1620
1621 static GtkListStore *addr_compl_create_store(void)
1622 {
1623         return gtk_list_store_new(N_ADDR_COMPL_COLUMNS,
1624                                   GDK_TYPE_PIXBUF,
1625                                   G_TYPE_STRING,
1626                                   G_TYPE_BOOLEAN,
1627                                   G_TYPE_POINTER,
1628                                   -1);
1629 }
1630                                              
1631 static GtkWidget *addr_compl_list_view_create(CompletionWindow *window)
1632 {
1633         GtkTreeView *list_view;
1634         GtkTreeSelection *selector;
1635         GtkTreeModel *model;
1636
1637         model = GTK_TREE_MODEL(addr_compl_create_store());
1638         list_view = GTK_TREE_VIEW(gtk_tree_view_new_with_model(model));
1639         g_object_unref(model);  
1640         
1641         gtk_tree_view_set_rules_hint(list_view, prefs_common.use_stripes_everywhere);
1642         gtk_tree_view_set_headers_visible(list_view, FALSE);
1643         
1644         selector = gtk_tree_view_get_selection(list_view);
1645         gtk_tree_selection_set_mode(selector, GTK_SELECTION_BROWSE);
1646         gtk_tree_selection_set_select_function(selector, addr_compl_selected,
1647                                                window, NULL);
1648
1649         /* create the columns */
1650         addr_compl_create_list_view_columns(GTK_WIDGET(list_view));
1651
1652         return GTK_WIDGET(list_view);
1653 }
1654
1655 static void addr_compl_create_list_view_columns(GtkWidget *list_view)
1656 {
1657         GtkTreeViewColumn *column;
1658         GtkCellRenderer *renderer;
1659
1660         renderer = gtk_cell_renderer_pixbuf_new();
1661         column = gtk_tree_view_column_new_with_attributes
1662                 ("", renderer,
1663                  "pixbuf", ADDR_COMPL_ICON, NULL);
1664         gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);          
1665         renderer = gtk_cell_renderer_text_new();
1666         column = gtk_tree_view_column_new_with_attributes
1667                 ("", renderer, "text", ADDR_COMPL_ADDRESS, NULL);
1668         gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);          
1669 }
1670
1671 static gboolean list_view_button_press(GtkWidget *widget, GdkEventButton *event,
1672                                        CompletionWindow *window)
1673 {
1674         if (window && event && event->type == GDK_BUTTON_PRESS) {
1675                 window->in_mouse = TRUE;
1676         }
1677         return FALSE;
1678 }
1679
1680 static gboolean list_view_button_release(GtkWidget *widget, GdkEventButton *event,
1681                                          CompletionWindow *window)
1682 {
1683         if (window && event && event->type == GDK_BUTTON_RELEASE) {
1684                 window->in_mouse = FALSE;
1685         }
1686         return FALSE;
1687 }
1688
1689 static gboolean addr_compl_selected(GtkTreeSelection *selector,
1690                                     GtkTreeModel *model, 
1691                                     GtkTreePath *path,
1692                                     gboolean currently_selected,
1693                                     gpointer data)
1694 {
1695         CompletionWindow *window = data;
1696
1697         if (currently_selected)
1698                 return TRUE;
1699         
1700         if (!window->in_mouse)
1701                 return TRUE;
1702
1703         /* XXX: select the entry and kill window later... select is called before
1704          * any other mouse events handlers including the tree view internal one;
1705          * not using a time out would result in a crash. if this doesn't work
1706          * safely, maybe we should set variables when receiving button presses
1707          * in the tree view. */
1708         if (!window->destroying) {
1709                 window->destroying = TRUE;
1710                 g_idle_add((GSourceFunc) addr_compl_defer_select_destruct, data);
1711         }
1712
1713         return TRUE;
1714 }
1715
1716 static gboolean addr_compl_defer_select_destruct(CompletionWindow *window)
1717 {
1718         GtkEntry *entry = GTK_ENTRY(window->entry);
1719
1720         completion_window_apply_selection(GTK_TREE_VIEW(window->list_view), 
1721                                           entry, TRUE);
1722
1723         clear_completion_cache();
1724
1725         addrcompl_destroy_window(window);
1726         return FALSE;
1727 }
1728
1729
1730 /*
1731  * End of Source.
1732  */
1733