remove M_WANT_SYNC, it has way too much overhead just for menu item sensitivity
[claws.git] / src / addr_compl.c
blobeede0ac6a146cdfbe12ac2eb02878ebc8e801757
1 /*
2 * Claws Mail -- a GTK based, lightweight, and fast e-mail client
4 * Copyright (C) 2000-2024 the Claws Mail team and Alfons Hoogervorst
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.
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.
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/>.
20 #ifdef HAVE_CONFIG_H
21 # include "config.h"
22 #include "claws-features.h"
23 #endif
24 #include "defs.h"
26 #include <glib.h>
27 #include <glib/gi18n.h>
28 #include <gdk/gdkkeysyms.h>
29 #include <gtk/gtk.h>
31 #include <string.h>
32 #include <ctype.h>
33 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
34 # include <wchar.h>
35 # include <wctype.h>
36 #endif
38 #include "addr_compl.h"
39 #include "addritem.h"
40 #include "utils.h"
41 #include "prefs_common.h"
42 #include "claws.h"
43 #include "hooks.h"
44 #include "gtkutils.h"
45 #include "stock_pixmap.h"
46 #include <pthread.h>
48 #ifndef USE_ALT_ADDRBOOK
49 #include "addrindex.h"
50 #else
51 #include "addressbook-dbus.h"
52 #endif
54 /*!
55 *\brief For the GtkListStore
57 enum {
58 ADDR_COMPL_ICON,
59 ADDR_COMPL_ADDRESS,
60 ADDR_COMPL_ISGROUP,
61 ADDR_COMPL_GROUPLIST,
62 N_ADDR_COMPL_COLUMNS
66 * How it works:
68 * The address book is read into memory. We set up an address list
69 * containing all address book entries. Next we make the completion
70 * list, which contains all the completable strings, and store a
71 * reference to the address entry it belongs to.
72 * After calling the g_completion_complete(), we get a reference
73 * to a valid email address.
75 * Completion is very simplified. We never complete on another prefix,
76 * i.e. we neglect the next smallest possible prefix for the current
77 * completion cache. This is simply done so we might break up the
78 * addresses a little more (e.g. break up alfons@proteus.demon.nl into
79 * something like alfons, proteus, demon, nl; and then completing on
80 * any of those words).
83 /**
84 * completion_entry - structure used to complete addresses, with a reference
85 * the the real address information.
87 typedef struct
89 gchar *string; /* string to complete */
90 address_entry *ref; /* address the string belongs to */
91 } completion_entry;
93 /*******************************************************************************/
95 static gint g_ref_count; /* list ref count */
96 static GList *g_completion_list = NULL; /* list of strings to be checked */
97 static GList *g_address_list = NULL; /* address storage */
98 static GCompletion *g_completion; /* completion object */
100 static GHashTable *_groupAddresses_ = NULL;
101 static gboolean _allowCommas_ = TRUE;
103 /* To allow for continuing completion we have to keep track of the state
104 * using the following variables. No need to create a context object. */
106 static gint g_completion_count; /* nr of addresses incl. the prefix */
107 static gint g_completion_next; /* next prev address */
108 static GSList *g_completion_addresses; /* unique addresses found in the
109 completion cache. */
110 static gchar *g_completion_prefix; /* last prefix. (this is cached here
111 * because the prefix passed to g_completion
112 * is g_utf8_strdown()'ed */
114 static gchar *completion_folder_path = NULL;
116 /*******************************************************************************/
119 * Define the structure of the completion window.
121 typedef struct _CompletionWindow CompletionWindow;
122 struct _CompletionWindow {
123 gint listCount;
124 gchar *searchTerm;
125 GtkWidget *window;
126 GtkWidget *entry;
127 GtkWidget *list_view;
129 gboolean in_mouse; /*!< mouse press pending... */
130 gboolean destroying; /*!< destruction in progress */
133 static GtkListStore *addr_compl_create_store (void);
135 static GtkWidget *addr_compl_list_view_create (CompletionWindow *window);
137 static void addr_compl_create_list_view_columns (GtkWidget *list_view);
139 static gboolean list_view_button_press (GtkWidget *widget,
140 GdkEventButton *event,
141 CompletionWindow *window);
143 static gboolean list_view_button_release (GtkWidget *widget,
144 GdkEventButton *event,
145 CompletionWindow *window);
147 static gboolean addr_compl_selected (GtkTreeSelection *selector,
148 GtkTreeModel *model,
149 GtkTreePath *path,
150 gboolean currently_selected,
151 gpointer data);
153 static gboolean addr_compl_defer_select_destruct(CompletionWindow *window);
156 * Function used by GTK to find the string data to be used for completion.
157 * \param data Pointer to data being processed.
159 static gchar *completion_func(gpointer data)
161 cm_return_val_if_fail(data != NULL, NULL);
163 return ((completion_entry *)data)->string;
166 static gint addr_completion_func(const gchar *needle, const gchar *haystack,
167 gsize n)
169 if (needle == NULL || haystack == NULL)
170 return 1;
172 return (strcasestr(haystack, needle) != NULL ? 0 : 1);
176 * Function used by GTK to compare elements for sorting
177 * name match beginning > name match after space > email address
178 * match beginning and full match before @ > email adress
179 * match beginning. Otherwise match position in string.
180 * \param a first element in comparsion
181 * \param b second element in comparison
183 static gint weight_addr_match(const address_entry* addr)
185 gint n_weight = addr->name ? strlen(addr->name): 0;
186 gint a_weight = addr->address ? strlen(addr->address) : n_weight;
187 gchar* match = NULL;
189 if (addr->name)
190 match = strcasestr(addr->name, g_completion_prefix);
192 if (match != NULL) {
193 if (match == addr->name)
194 n_weight = -4;
195 else if (match > addr->name && *(match - 1) == ' ')
196 n_weight = -3;
197 else
198 n_weight = match - addr->name;
201 if (addr->address) {
202 match = strcasestr(addr->address, g_completion_prefix);
203 if (match != NULL) {
204 if (match == addr->address)
205 a_weight = -1;
206 else
207 a_weight = match - addr->address;
209 if (strlen(match) > strlen(g_completion_prefix)
210 && *(match + strlen(g_completion_prefix)) == '@')
211 a_weight--;
215 if (n_weight == -4 && a_weight < 0)
216 n_weight = -5;
218 return MIN(a_weight, n_weight);
221 static gint addr_comparison_func(gconstpointer a, gconstpointer b)
223 const address_entry* a_ref = (const address_entry*)a;
224 const address_entry* b_ref = (const address_entry*)b;
225 gint a_weight = weight_addr_match(a_ref);
226 gint b_weight = weight_addr_match(b_ref);
227 gint cmp;
229 if (a_weight < b_weight)
230 return -1;
231 else if (a_weight > b_weight)
232 return 1;
233 else {
234 if (!a_ref->name || !b_ref->name)
235 cmp = !!a_ref->name - !!b_ref->name;
236 else
237 cmp = strcmp(a_ref->name, b_ref->name);
238 if (!cmp)
240 if (!a_ref->address || !b_ref->address)
241 cmp = !!a_ref->address - !!b_ref->address;
242 else
243 cmp = g_strcmp0(a_ref->address, b_ref->address);
245 return cmp;
250 * Initialize all completion index data.
252 static void init_all(void)
254 g_completion = g_completion_new(completion_func);
255 cm_return_if_fail(g_completion != NULL);
259 * set the compare function (default is strncmp)
261 static void set_match_any_part(const gboolean any_part)
263 if (any_part && prefs_common.address_search_wildcard)
264 g_completion_set_compare(g_completion, addr_completion_func);
265 else
266 g_completion_set_compare(g_completion, strncmp);
269 static void free_all_addresses(void)
271 GList *walk;
272 if (!g_address_list)
273 return;
274 walk = g_address_list;
275 for (; walk != NULL; walk = g_list_next(walk)) {
276 address_entry *ae = (address_entry *) walk->data;
277 g_free(ae->name);
278 g_free(ae->address);
279 g_list_free(ae->grp_emails);
280 g_free(walk->data);
282 g_list_free(g_address_list);
283 g_address_list = NULL;
284 if (_groupAddresses_)
285 g_hash_table_destroy(_groupAddresses_);
286 _groupAddresses_ = NULL;
289 static void clear_completion_cache(void);
290 static void free_completion_list(void)
292 GList *walk;
293 if (!g_completion_list)
294 return;
296 clear_completion_cache();
297 if (g_completion)
298 g_completion_clear_items(g_completion);
300 walk = g_list_first(g_completion_list);
301 for (; walk != NULL; walk = g_list_next(walk)) {
302 completion_entry *ce = (completion_entry *) walk->data;
303 g_free(ce->string);
304 g_free(walk->data);
306 g_list_free(g_completion_list);
307 g_completion_list = NULL;
310 * Free up all completion index data.
312 static void free_all(void)
314 free_completion_list();
315 free_all_addresses();
316 g_completion_free(g_completion);
317 g_completion = NULL;
321 * Append specified address entry to the index.
322 * \param str Index string value.
323 * \param ae Entry containing address data.
325 void addr_compl_add_address1(const char *str, address_entry *ae)
327 completion_entry *ce1;
328 ce1 = g_new0(completion_entry, 1),
329 /* GCompletion list is case sensitive */
330 ce1->string = g_utf8_strdown(str, -1);
331 ce1->ref = ae;
333 g_completion_list = g_list_prepend(g_completion_list, ce1);
337 * Adds address to the completion list. This function looks complicated, but
338 * it's only allocation checks. Each value will be included in the index.
339 * \param name Recipient name.
340 * \param address EMail address.
341 * \param alias Alias to append.
342 * \param grp_emails the emails in case of a group. List should be freed later,
343 * but not its strings
344 * \return <code>0</code> if entry appended successfully, or <code>-1</code>
345 * if failure.
347 static gint add_address(const gchar *name, const gchar *address,
348 const gchar *nick, const gchar *alias, GList *grp_emails)
350 address_entry *ae;
352 if (!address && !grp_emails)
353 return -1;
355 if (!name)
356 name = "";
358 ae = g_new0(address_entry, 1);
359 cm_return_val_if_fail(ae != NULL, -1);
361 ae->name = g_strdup(name);
362 ae->address = g_strdup(address);
363 ae->grp_emails = grp_emails;
364 g_address_list = g_list_prepend(g_address_list, ae);
366 addr_compl_add_address1(name, ae);
368 if (address != NULL && *address != '\0')
369 addr_compl_add_address1(address, ae);
371 if (nick != NULL && *nick != '\0')
372 addr_compl_add_address1(nick, ae);
374 if (alias != NULL && *alias != '\0')
375 addr_compl_add_address1(alias, ae);
377 return 0;
381 * Read address book, creating all entries in the completion index.
383 static void read_address_book(gchar *folderpath) {
384 free_all_addresses();
385 free_completion_list();
387 #ifndef USE_ALT_ADDRBOOK
388 addrindex_load_completion( add_address, folderpath );
389 #else
390 GError* error = NULL;
392 addrcompl_initialize();
393 if (! addrindex_dbus_load_completion(add_address, &error)) {
394 g_warning("failed to populate address completion list");
395 g_error_free(error);
396 return;
398 #endif
399 /* plugins may hook in here to modify/extend the completion list */
400 if(!folderpath) {
401 hooks_invoke(ADDDRESS_COMPLETION_BUILD_ADDRESS_LIST_HOOKLIST, &g_address_list);
404 g_address_list = g_list_reverse(g_address_list);
405 g_completion_list = g_list_reverse(g_completion_list);
406 /* merge the completion entry list into g_completion */
407 if (g_completion_list) {
408 g_completion_add_items(g_completion, g_completion_list);
409 if (debug_get_mode())
410 debug_print("read %d items in %s\n",
411 g_list_length(g_completion_list),
412 folderpath?folderpath:"(null)");
417 * Test whether there is a completion pending.
418 * \return <code>TRUE</code> if pending.
420 static gboolean is_completion_pending(void)
422 /* check if completion pending, i.e. we might satisfy a request for the next
423 * or previous address */
424 return g_completion_count;
428 * Clear the completion cache.
430 static void clear_completion_cache(void)
432 if (is_completion_pending()) {
433 g_free(g_completion_prefix);
435 if (g_completion_addresses) {
436 g_slist_free(g_completion_addresses);
437 g_completion_addresses = NULL;
440 g_completion_count = g_completion_next = 0;
445 * Prepare completion index. This function should be called prior to attempting
446 * address completion.
447 * \return The number of addresses in the completion list.
449 guint start_address_completion(gchar *folderpath)
451 gboolean different_book = FALSE;
452 clear_completion_cache();
454 if (g_strcmp0(completion_folder_path,folderpath))
455 different_book = TRUE;
457 g_free(completion_folder_path);
458 if (folderpath != NULL)
459 completion_folder_path = g_strdup(folderpath);
460 else
461 completion_folder_path = NULL;
463 if (!g_ref_count) {
464 init_all();
465 /* open the address book */
466 read_address_book(folderpath);
467 } else if (different_book)
468 read_address_book(folderpath);
470 g_ref_count++;
471 debug_print("start_address_completion(%s) ref count %d\n",
472 folderpath?folderpath:"(null)", g_ref_count);
474 return g_list_length(g_completion_list);
478 * Retrieve a possible address (or a part) from an entry box. To make life
479 * easier, we only look at the last valid address component; address
480 * completion only works at the last string component in the entry box.
482 * \param entry Address entry field.
483 * \param start_pos Address of start position of address.
484 * \return Possible address.
486 static gchar *get_address_from_edit(GtkEntry *entry, gint *start_pos)
488 const gchar *edit_text, *p;
489 gint cur_pos;
490 gboolean in_quote = FALSE;
491 gboolean in_bracket = FALSE;
492 gchar *str;
494 edit_text = gtk_entry_get_text(entry);
495 if (edit_text == NULL) return NULL;
497 cur_pos = gtk_editable_get_position(GTK_EDITABLE(entry));
499 /* scan for a separator. doesn't matter if walk points at null byte. */
500 for (p = g_utf8_offset_to_pointer(edit_text, cur_pos);
501 p > edit_text;
502 p = g_utf8_prev_char(p)) {
503 if (*p == '"') {
504 in_quote = TRUE;
505 } else if (!in_quote) {
506 if (!in_bracket && *p == ',') {
507 break;
508 } else if (*p == '<')
509 in_bracket = TRUE;
510 else if (*p == '>')
511 in_bracket = FALSE;
515 /* have something valid */
516 if (g_utf8_strlen(p, -1) == 0)
517 return NULL;
519 #define IS_VALID_CHAR(x) \
520 (g_ascii_isalnum(x) || (x) == '"' || (x) == '<' || (((unsigned char)(x)) > 0x7f))
522 /* now scan back until we hit a valid character */
523 for (; *p && !IS_VALID_CHAR(*p); p = g_utf8_next_char(p))
526 #undef IS_VALID_CHAR
528 if (g_utf8_strlen(p, -1) == 0)
529 return NULL;
531 if (start_pos) *start_pos = g_utf8_pointer_to_offset(edit_text, p);
533 str = g_strdup(p);
535 return str;
538 static gchar *get_complete_address_from_name_email(const gchar *name, const gchar *email)
540 gchar *address = NULL;
541 if (!name || name[0] == '\0')
542 address = g_strdup_printf("<%s>", email);
543 else if (strchr_with_skip_quote(name, '"', ','))
544 address = g_strdup_printf
545 ("\"%s\" <%s>", name, email);
546 else
547 address = g_strdup_printf
548 ("%s <%s>", name, email);
549 return address;
553 * Replace an incompleted address with a completed one.
554 * \param entry Address entry field.
555 * \param newtext New text.
556 * \param start_pos Insertion point in entry field.
558 static void replace_address_in_edit(GtkEntry *entry, const gchar *newtext,
559 gint start_pos, gboolean is_group, GList *grp_emails)
561 if (!newtext) return;
562 gtk_editable_delete_text(GTK_EDITABLE(entry), start_pos, -1);
563 if (!is_group) {
564 gtk_editable_insert_text(GTK_EDITABLE(entry), newtext, strlen(newtext),
565 &start_pos);
566 } else {
567 gchar *addresses = NULL;
568 GList *cur = grp_emails;
569 for (; cur; cur = cur->next) {
570 gchar *tmp;
571 ItemEMail *email = (ItemEMail *)cur->data;
572 ItemPerson *person = ( ItemPerson * ) ADDRITEM_PARENT(email);
574 gchar *addr = get_complete_address_from_name_email(
575 ADDRITEM_NAME(person), email->address);
576 if (addresses)
577 tmp = g_strdup_printf("%s, %s", addresses, addr);
578 else
579 tmp = g_strdup_printf("%s", addr);
580 g_free(addr);
581 g_free(addresses);
582 addresses = tmp;
584 gtk_editable_insert_text(GTK_EDITABLE(entry), addresses, strlen(addresses),
585 &start_pos);
586 g_free(addresses);
588 gtk_editable_set_position(GTK_EDITABLE(entry), -1);
592 * Attempt to complete an address, and returns the number of addresses found.
593 * Use <code>get_complete_address()</code> to get an entry from the index.
595 * \param str Search string to find.
596 * \return Zero if no match was found, otherwise the number of addresses; the
597 * original prefix (search string) will appear at index 0.
599 guint complete_address(const gchar *str)
601 GList *result = NULL;
602 gchar *d = NULL;
603 guint count = 0;
604 guint cpl = 0;
605 completion_entry *ce = NULL;
607 cm_return_val_if_fail(str != NULL, 0);
609 /* g_completion is case sensitive */
610 d = g_utf8_strdown(str, -1);
612 clear_completion_cache();
613 g_completion_prefix = g_strdup(str);
615 result = g_completion_complete(g_completion, d, NULL);
617 count = g_list_length(result);
618 if (count) {
619 /* create list with unique addresses */
620 for (cpl = 0, result = g_list_first(result);
621 result != NULL;
622 result = g_list_next(result)) {
623 ce = (completion_entry *)(result->data);
624 if (NULL == g_slist_find(g_completion_addresses,
625 ce->ref)) {
626 cpl++;
627 g_completion_addresses =
628 g_slist_append(g_completion_addresses,
629 ce->ref);
632 count = cpl + 1; /* index 0 is the original prefix */
633 g_completion_next = 1; /* we start at the first completed one */
634 if (prefs_common.address_search_wildcard)
635 g_completion_addresses = g_slist_sort(g_completion_addresses,
636 addr_comparison_func);
637 } else {
638 g_free(g_completion_prefix);
639 g_completion_prefix = NULL;
642 g_completion_count = count;
644 g_free(d);
646 return count;
650 * complete_matches_found() returns the number of matched addresses according
651 * to the completion mechanism. Unlike complete_address(), the returned value
652 * doesn't count str itself. If there's no match, it returns 0.
653 * To get a list of completion matches, see complete_address() instead.
655 guint complete_matches_found(const gchar *str)
657 GList *result = NULL;
658 gchar *d = NULL;
660 cm_return_val_if_fail(str != NULL, 0);
662 /* g_completion is case sensitive */
663 d = g_utf8_strdown(str, -1);
665 clear_completion_cache();
666 g_completion_prefix = g_strdup(str);
668 result = g_completion_complete(g_completion, d, NULL);
670 g_free(g_completion_prefix);
671 g_free(d);
673 return g_list_length(result);
677 * Return a complete address from the index.
678 * \param index Index of entry that was found (by the previous call to
679 * <code>complete_address()</code>
680 * \return Completed address string; this should be freed when done.
682 gchar *get_complete_address(gint index)
684 const address_entry *p;
685 gchar *address = NULL;
687 if (index < g_completion_count) {
688 if (index == 0)
689 address = g_strdup(g_completion_prefix);
690 else {
691 /* get something from the unique addresses */
692 p = (address_entry *)g_slist_nth_data
693 (g_completion_addresses, index - 1);
694 if (p != NULL && p->address != NULL) {
695 address = get_complete_address_from_name_email(p->name, p->address);
696 } else if (p != NULL && p->address == NULL && p->name != NULL) {
697 /* that's a group */
698 address = g_strdup_printf("%s (%s) <!--___group___-->", p->name, _("Group"));
699 if (!_groupAddresses_) {
700 _groupAddresses_ = g_hash_table_new(NULL, g_direct_equal);
702 if (!g_hash_table_lookup(_groupAddresses_, GINT_TO_POINTER(g_str_hash(address)))) {
703 g_hash_table_insert(_groupAddresses_, GINT_TO_POINTER(g_str_hash(address)), p->grp_emails);
710 return address;
714 * Return the next complete address match from the completion index.
715 * \return Completed address string; this should be freed when done.
717 static gchar *get_next_complete_address(void)
719 if (is_completion_pending()) {
720 gchar *res;
722 res = get_complete_address(g_completion_next);
723 g_completion_next += 1;
724 if (g_completion_next >= g_completion_count)
725 g_completion_next = 0;
727 return res;
728 } else
729 return NULL;
733 * Return a count of the completed matches in the completion index.
734 * \return Number of matched entries.
736 static guint get_completion_count(void)
738 if (is_completion_pending())
739 return g_completion_count;
740 else
741 return 0;
745 * Invalidate address completion index. This function should be called whenever
746 * the address book changes. This forces data to be read into the completion
747 * data.
748 * \return Number of entries in index.
750 gint invalidate_address_completion(void)
752 if (g_ref_count) {
753 /* simply the same as start_address_completion() */
754 debug_print("Invalidation request for address completion\n");
755 read_address_book(completion_folder_path);
756 clear_completion_cache();
759 return g_list_length(g_completion_list);
763 * Finished with completion index. This function should be called after
764 * matching addresses.
765 * \return Reference count.
767 gint end_address_completion(void)
769 gboolean different_folder = FALSE;
770 clear_completion_cache();
772 /* reset the folderpath to NULL */
773 if (completion_folder_path) {
774 g_free(completion_folder_path);
775 completion_folder_path = NULL;
776 different_folder = TRUE;
778 if (0 == --g_ref_count)
779 free_all();
781 debug_print("end_address_completion ref count %d\n", g_ref_count);
782 if (g_ref_count && different_folder) {
783 debug_print("still ref'd, different folder\n");
784 invalidate_address_completion();
787 return g_ref_count;
791 * Completion window.
793 static CompletionWindow *_compWindow_ = NULL;
796 * Mutex to protect callback from multiple threads.
798 static pthread_mutex_t _completionMutex_ = PTHREAD_MUTEX_INITIALIZER;
801 * Completion queue list.
803 static GList *_displayQueue_ = NULL;
805 * Current query ID.
807 static gint _queryID_ = 0;
810 * Completion idle ID.
812 static guint _completionIdleID_ = 0;
815 * address completion entry ui. the ui (completion list was inspired by galeon's
816 * auto completion list). remaining things powered by claws's completion engine.
819 #define ENTRY_DATA_TAB_HOOK "tab_hook" /* used to lookup entry */
820 #define ENTRY_DATA_ALLOW_COMMAS "allowcommas" /* used to know whether to present groups */
822 static void address_completion_mainwindow_set_focus (GtkWindow *window,
823 GtkWidget *widget,
824 gpointer data);
825 static gboolean address_completion_entry_key_pressed (GtkEntry *entry,
826 GdkEventKey *ev,
827 gpointer data);
828 static gboolean address_completion_complete_address_in_entry
829 (GtkEntry *entry,
830 gboolean next);
831 static void address_completion_create_completion_window (GtkEntry *entry);
833 static gboolean completion_window_button_press
834 (GtkWidget *widget,
835 GdkEventButton *event,
836 CompletionWindow *compWin );
838 static gboolean completion_window_key_press
839 (GtkWidget *widget,
840 GdkEventKey *event,
841 CompletionWindow *compWin );
842 static void address_completion_create_completion_window( GtkEntry *entry_ );
845 * Create a completion window object.
846 * \return Initialized completion window.
848 static CompletionWindow *addrcompl_create_window( void ) {
849 CompletionWindow *cw;
851 cw = g_new0( CompletionWindow, 1 );
852 cw->listCount = 0;
853 cw->searchTerm = NULL;
854 cw->window = NULL;
855 cw->entry = NULL;
856 cw->list_view = NULL;
857 cw->in_mouse = FALSE;
858 cw->destroying = FALSE;
860 return cw;
864 * Destroy completion window.
865 * \param cw Window to destroy.
867 static void addrcompl_destroy_window( CompletionWindow *cw ) {
868 GdkDisplay *display;
869 GdkSeat *seat;
871 display = gdk_display_get_default();
872 seat = gdk_display_get_default_seat(display);
873 /* Stop all searches currently in progress */
874 #ifndef USE_ALT_ADDRBOOK
875 addrindex_stop_search( _queryID_ );
876 #endif
877 /* Remove idler function... or application may not terminate */
878 if( _completionIdleID_ != 0 ) {
879 g_source_remove( _completionIdleID_ );
880 _completionIdleID_ = 0;
883 /* Now destroy window */
884 if( cw ) {
885 /* Clear references to widgets */
886 cw->entry = NULL;
887 cw->list_view = NULL;
889 /* Free objects */
890 if( cw->window ) {
891 gtk_widget_hide( cw->window );
892 gtk_widget_destroy( cw->window );
894 cw->window = NULL;
895 cw->destroying = FALSE;
896 cw->in_mouse = FALSE;
899 /* Re-enable keyboard, required at least for Gtk3/Win32 */
900 gdk_seat_ungrab(seat);
904 * Free up completion window.
905 * \param cw Window to free.
907 static void addrcompl_free_window( CompletionWindow *cw ) {
908 if( cw ) {
909 addrcompl_destroy_window( cw );
911 g_free( cw->searchTerm );
912 cw->searchTerm = NULL;
914 /* Clear references */
915 cw->listCount = 0;
917 /* Free object */
918 g_free( cw );
923 * Advance selection to previous/next item in list.
924 * \param list_view List to process.
925 * \param forward Set to <i>TRUE</i> to select next or <i>FALSE</i> for
926 * previous entry.
928 static void completion_window_advance_selection(GtkTreeView *list_view, gboolean forward)
930 GtkTreeSelection *selection;
931 GtkTreeIter iter;
932 GtkTreeModel *model;
934 cm_return_if_fail(list_view != NULL);
936 selection = gtk_tree_view_get_selection(list_view);
937 if (!gtk_tree_selection_get_selected(selection, &model, &iter))
938 return;
940 if (forward) {
941 forward = gtk_tree_model_iter_next(model, &iter);
942 if (forward)
943 gtk_tree_selection_select_iter(selection, &iter);
944 } else {
945 GtkTreePath *prev;
947 prev = gtk_tree_model_get_path(model, &iter);
948 if (!prev)
949 return;
951 if (gtk_tree_path_prev(prev))
952 gtk_tree_selection_select_path(selection, prev);
954 gtk_tree_path_free(prev);
959 * Resize window to accommodate maximum number of address entries.
960 * \param cw Completion window.
962 static void addrcompl_resize_window( CompletionWindow *cw ) {
963 GdkDisplay *display;
964 GtkRequisition r;
965 GdkGrabStatus status;
966 gint x, y, width;
967 GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(cw->list_view));
968 GtkTreeIter iter;
969 GdkRectangle cell_rect;
970 gint extra_height = 0;
972 gdk_window_get_position(gtk_widget_get_window(cw->window), &x, &y);
973 width = gdk_window_get_width(gtk_widget_get_window(cw->window));
975 gtk_widget_queue_resize_no_redraw(cw->list_view);
976 gtk_widget_get_preferred_size(cw->list_view, &r, NULL);
978 if (model && gtk_tree_model_get_iter_first(model, &iter)) {
979 GtkTreePath *path = gtk_tree_model_get_path(model, &iter);
981 gtk_tree_view_get_cell_area(GTK_TREE_VIEW(cw->list_view), path, NULL, &cell_rect);
982 gtk_tree_path_free(path);
983 extra_height = cell_rect.height + 4;
985 gtk_widget_set_size_request(cw->window, width, r.height + extra_height);
987 display = gdk_display_get_default();
988 status = gdk_seat_grab(gdk_display_get_default_seat(display),
989 gtk_widget_get_window(cw->window),
990 GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK |
991 GDK_BUTTON_RELEASE_MASK,
992 TRUE, NULL, NULL, NULL, NULL);
993 if (status != GDK_GRAB_SUCCESS)
994 g_warning("gdk_seat_grab failed with status %d", status);
995 gtk_grab_add(cw->window);
999 static GdkPixbuf *group_pixbuf = NULL;
1000 static GdkPixbuf *email_pixbuf = NULL;
1003 * Add an address the completion window address list.
1004 * \param cw Completion window.
1005 * \param address Address to add.
1007 static void addrcompl_add_entry( CompletionWindow *cw, gchar *address ) {
1008 GtkListStore *store;
1009 GtkTreeIter iter;
1010 GtkTreeSelection *selection;
1011 gboolean is_group = FALSE;
1012 GList *grp_emails = NULL;
1013 store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(cw->list_view)));
1014 GdkPixbuf *pixbuf;
1016 if (!group_pixbuf) {
1017 stock_pixbuf_gdk(STOCK_PIXMAP_ADDR_TWO, &group_pixbuf);
1018 g_object_ref(G_OBJECT(group_pixbuf));
1020 if (!email_pixbuf) {
1021 stock_pixbuf_gdk(STOCK_PIXMAP_ADDR_ONE, &email_pixbuf);
1022 g_object_ref(G_OBJECT(email_pixbuf));
1024 /* g_print( "\t\tAdding :%s\n", address ); */
1025 if (strstr(address, " <!--___group___-->")) {
1026 is_group = TRUE;
1027 if (_groupAddresses_)
1028 grp_emails = g_hash_table_lookup(_groupAddresses_, GINT_TO_POINTER(g_str_hash(address)));
1029 *(strstr(address, " <!--___group___-->")) = '\0';
1030 pixbuf = group_pixbuf;
1031 } else if (strchr(address, '@') && strchr(address, '<') &&
1032 strchr(address, '>')) {
1033 pixbuf = email_pixbuf;
1034 } else
1035 pixbuf = NULL;
1037 if (is_group && !_allowCommas_)
1038 return;
1039 gtk_list_store_append(store, &iter);
1040 gtk_list_store_set(store, &iter,
1041 ADDR_COMPL_ICON, pixbuf,
1042 ADDR_COMPL_ADDRESS, address,
1043 ADDR_COMPL_ISGROUP, is_group,
1044 ADDR_COMPL_GROUPLIST, grp_emails,
1045 -1);
1046 cw->listCount++;
1048 /* Resize window */
1049 addrcompl_resize_window( cw );
1050 gtk_grab_add( cw->window );
1052 selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(cw->list_view));
1053 if (!gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store), &iter))
1054 return;
1056 if (cw->listCount == 1) {
1057 /* Select first row for now */
1058 gtk_tree_selection_select_iter(selection, &iter);
1062 void addrcompl_reflect_prefs_pixmap_theme(void) {
1063 if (group_pixbuf) {
1064 g_object_unref(G_OBJECT(group_pixbuf));
1065 group_pixbuf = NULL;
1067 if (email_pixbuf) {
1068 g_object_unref(G_OBJECT(email_pixbuf));
1069 email_pixbuf = NULL;
1074 * Completion idle function. This function is called by the main (UI) thread
1075 * during UI idle time while an address search is in progress. Items from the
1076 * display queue are processed and appended to the address list.
1078 * \param data Target completion window to receive email addresses.
1079 * \return <i>TRUE</i> to ensure that idle event do not get ignored.
1081 static gboolean addrcompl_idle( gpointer data ) {
1082 GList *node;
1083 gchar *address;
1085 /* Process all entries in display queue */
1086 pthread_mutex_lock( & _completionMutex_ );
1087 if( _displayQueue_ ) {
1088 node = _displayQueue_;
1089 node = g_list_next(node); /* skip search term */
1090 while( node ) {
1091 address = node->data;
1092 /* g_print( "address ::: %s :::\n", address ); */
1093 addrcompl_add_entry( _compWindow_, address );
1094 g_free( address );
1095 node = g_list_next( node );
1097 g_list_free( _displayQueue_ );
1098 _displayQueue_ = NULL;
1100 pthread_mutex_unlock( & _completionMutex_ );
1101 claws_do_idle();
1103 return TRUE;
1107 * Callback entry point. The background thread (if any) appends the address
1108 * list to the display queue.
1109 * \param sender Sender of query.
1110 * \param queryID Query ID of search request.
1111 * \param listEMail List of zero of more email objects that met search
1112 * criteria.
1113 * \param data Query data.
1115 #ifndef USE_ALT_ADDRBOOK
1116 static gint addrcompl_callback_entry(
1117 gpointer sender, gint queryID, GList *listEMail, gpointer data )
1119 GList *node;
1120 gchar *address;
1122 /* g_print( "addrcompl_callback_entry::queryID=%d\n", queryID ); */
1123 pthread_mutex_lock( & _completionMutex_ );
1124 if( queryID == _queryID_ ) {
1125 /* Append contents to end of display queue */
1126 node = listEMail;
1127 while( node ) {
1128 ItemEMail *email = node->data;
1130 address = addritem_format_email( email );
1131 /* g_print( "\temail/address ::%s::\n", address ); */
1132 _displayQueue_ = g_list_append( _displayQueue_, address );
1133 node = g_list_next( node );
1136 g_list_free( listEMail );
1137 pthread_mutex_unlock( & _completionMutex_ );
1139 return 0;
1141 #endif
1144 * Clear the display queue.
1146 static void addrcompl_clear_queue( void ) {
1147 /* Clear out display queue */
1148 pthread_mutex_lock( & _completionMutex_ );
1150 g_list_free_full( _displayQueue_, g_free );
1151 _displayQueue_ = NULL;
1153 pthread_mutex_unlock( & _completionMutex_ );
1157 * Add a single address entry into the display queue.
1158 * \param address Address to append.
1160 static void addrcompl_add_queue( gchar *address ) {
1161 pthread_mutex_lock( & _completionMutex_ );
1162 _displayQueue_ = g_list_append( _displayQueue_, address );
1163 pthread_mutex_unlock( & _completionMutex_ );
1167 * Load list with entries from local completion index.
1169 static void addrcompl_load_local( void ) {
1170 guint count = 0;
1172 for (count = 0; count < get_completion_count(); count++) {
1173 gchar *address;
1175 address = get_complete_address( count );
1176 /* g_print( "\taddress ::%s::\n", address ); */
1178 /* Append contents to end of display queue */
1179 addrcompl_add_queue( address );
1184 * Start the search.
1186 static void addrcompl_start_search( void ) {
1187 #ifndef USE_ALT_ADDRBOOK
1188 gchar *searchTerm;
1190 searchTerm = g_strdup( _compWindow_->searchTerm );
1192 /* Setup the search */
1193 _queryID_ = addrindex_setup_search(
1194 searchTerm, NULL, addrcompl_callback_entry );
1195 g_free( searchTerm );
1196 #endif
1197 /* g_print( "addrcompl_start_search::queryID=%d\n", _queryID_ ); */
1199 /* Load local stuff */
1200 addrcompl_load_local();
1202 /* Sit back and wait until something happens */
1203 _completionIdleID_ =
1204 g_idle_add( (GSourceFunc) addrcompl_idle, NULL );
1205 /* g_print( "addrindex_start_search::queryID=%d\n", _queryID_ ); */
1207 #ifndef USE_ALT_ADDRBOOK
1208 addrindex_start_search( _queryID_ );
1209 #else
1211 #endif
1215 * Apply the current selection in the list to the entry field. Focus is also
1216 * moved to the next widget so that Tab key works correctly.
1217 * \param list_view List to process.
1218 * \param entry Address entry field.
1219 * \param move_focus Move focus to the next widget ?
1221 static void completion_window_apply_selection(GtkTreeView *list_view,
1222 GtkEntry *entry,
1223 gboolean move_focus)
1225 gchar *address = NULL, *text = NULL;
1226 gint cursor_pos;
1227 GtkWidget *parent;
1228 GtkTreeSelection *selection;
1229 GtkTreeModel *model;
1230 GtkTreeIter iter;
1231 gboolean is_group = FALSE;
1232 cm_return_if_fail(list_view != NULL);
1233 cm_return_if_fail(entry != NULL);
1234 GList *grp_emails = NULL;
1236 selection = gtk_tree_view_get_selection(list_view);
1237 if (!gtk_tree_selection_get_selected(selection, &model, &iter))
1238 return;
1240 /* First remove the idler */
1241 if( _completionIdleID_ != 0 ) {
1242 g_source_remove( _completionIdleID_ );
1243 _completionIdleID_ = 0;
1246 /* Process selected item */
1247 gtk_tree_model_get(model, &iter, ADDR_COMPL_ADDRESS, &text,
1248 ADDR_COMPL_ISGROUP, &is_group,
1249 ADDR_COMPL_GROUPLIST, &grp_emails,
1250 -1);
1252 address = get_address_from_edit(entry, &cursor_pos);
1253 g_free(address);
1254 replace_address_in_edit(entry, text, cursor_pos, is_group, grp_emails);
1255 g_free(text);
1257 /* Move focus to next widget */
1258 parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1259 if( parent && move_focus) {
1260 gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1265 * Start address completion. Should be called when creating the main window
1266 * containing address completion entries.
1267 * \param mainwindow Main window.
1269 void address_completion_start(GtkWidget *mainwindow)
1271 start_address_completion(NULL);
1272 set_match_any_part(TRUE);
1274 /* register focus change hook */
1275 g_signal_connect(G_OBJECT(mainwindow), "set_focus",
1276 G_CALLBACK(address_completion_mainwindow_set_focus),
1277 mainwindow);
1281 * Need unique data to make unregistering signal handler possible for the auto
1282 * completed entry.
1284 #define COMPLETION_UNIQUE_DATA (GINT_TO_POINTER(0xfeefaa))
1287 * Register specified entry widget for address completion.
1288 * \param entry Address entry field.
1290 void address_completion_register_entry(GtkEntry *entry, gboolean allow_commas)
1292 cm_return_if_fail(entry != NULL);
1293 cm_return_if_fail(GTK_IS_ENTRY(entry));
1295 /* add hooked property */
1296 g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, entry);
1297 g_object_set_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS, GINT_TO_POINTER(allow_commas));
1299 /* add keypress event */
1300 g_signal_connect_closure
1301 (G_OBJECT(entry), "key_press_event",
1302 g_cclosure_new(G_CALLBACK(address_completion_entry_key_pressed),
1303 COMPLETION_UNIQUE_DATA,
1304 NULL),
1305 FALSE); /* magic */
1309 * Unregister specified entry widget from address completion operations.
1310 * \param entry Address entry field.
1312 void address_completion_unregister_entry(GtkEntry *entry)
1314 GObject *entry_obj;
1316 cm_return_if_fail(entry != NULL);
1317 cm_return_if_fail(GTK_IS_ENTRY(entry));
1319 entry_obj = g_object_get_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK);
1320 cm_return_if_fail(entry_obj);
1321 cm_return_if_fail(G_OBJECT(entry_obj) == G_OBJECT(entry));
1323 /* has the hooked property? */
1324 g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, NULL);
1326 /* remove the hook */
1327 g_signal_handlers_disconnect_by_func(G_OBJECT(entry),
1328 G_CALLBACK(address_completion_entry_key_pressed),
1329 COMPLETION_UNIQUE_DATA);
1333 * End address completion. Should be called when main window with address
1334 * completion entries terminates. NOTE: this function assumes that it is
1335 * called upon destruction of the window.
1336 * \param mainwindow Main window.
1338 void address_completion_end(GtkWidget *mainwindow)
1340 /* if address_completion_end() is really called on closing the window,
1341 * we don't need to unregister the set_focus_cb */
1342 end_address_completion();
1345 /* if focus changes to another entry, then clear completion cache */
1346 static void address_completion_mainwindow_set_focus(GtkWindow *window,
1347 GtkWidget *widget,
1348 gpointer data)
1351 if (widget && GTK_IS_ENTRY(widget) &&
1352 g_object_get_data(G_OBJECT(widget), ENTRY_DATA_TAB_HOOK)) {
1353 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), ENTRY_DATA_ALLOW_COMMAS));
1354 clear_completion_cache();
1359 * Listener that watches for tab or other keystroke in address entry field.
1360 * \param entry Address entry field.
1361 * \param ev Event object.
1362 * \param data User data.
1363 * \return <i>TRUE</i>.
1365 static gboolean address_completion_entry_key_pressed(GtkEntry *entry,
1366 GdkEventKey *ev,
1367 gpointer data)
1369 if (ev->keyval == GDK_KEY_Tab) {
1370 addrcompl_clear_queue();
1371 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS));
1372 if( address_completion_complete_address_in_entry( entry, TRUE ) ) {
1373 /* route a void character to the default handler */
1374 /* this is a dirty hack; we're actually changing a key
1375 * reported by the system. */
1376 ev->keyval = GDK_KEY_AudibleBell_Enable;
1377 ev->state &= ~GDK_SHIFT_MASK;
1379 /* Create window */
1380 address_completion_create_completion_window(entry);
1382 /* Start remote queries */
1383 addrcompl_start_search();
1385 return TRUE;
1387 else {
1388 /* old behaviour */
1390 } else if (ev->keyval == GDK_KEY_Shift_L
1391 || ev->keyval == GDK_KEY_Shift_R
1392 || ev->keyval == GDK_KEY_Control_L
1393 || ev->keyval == GDK_KEY_Control_R
1394 || ev->keyval == GDK_KEY_Caps_Lock
1395 || ev->keyval == GDK_KEY_Shift_Lock
1396 || ev->keyval == GDK_KEY_Meta_L
1397 || ev->keyval == GDK_KEY_Meta_R
1398 || ev->keyval == GDK_KEY_Alt_L
1399 || ev->keyval == GDK_KEY_Alt_R) {
1400 /* these buttons should not clear the cache... */
1401 } else
1402 clear_completion_cache();
1404 return FALSE;
1407 * Initialize search term for address completion.
1408 * \param entry Address entry field.
1410 static gboolean address_completion_complete_address_in_entry(GtkEntry *entry,
1411 gboolean next)
1413 gint ncount, cursor_pos;
1414 gchar *searchTerm, *new = NULL;
1416 cm_return_val_if_fail(entry != NULL, FALSE);
1418 if (!gtk_widget_has_focus(GTK_WIDGET(entry))) return FALSE;
1420 /* get an address component from the cursor */
1421 searchTerm = get_address_from_edit( entry, &cursor_pos );
1422 if( ! searchTerm ) return FALSE;
1423 /* g_print( "search for :::%s:::\n", searchTerm ); */
1425 /* Clear any existing search */
1426 g_free( _compWindow_->searchTerm );
1427 _compWindow_->searchTerm = g_strdup( searchTerm );
1429 /* Perform search on local completion index */
1430 ncount = complete_address( searchTerm );
1431 if( 0 < ncount ) {
1432 new = get_next_complete_address();
1433 g_free( new );
1435 #if (!defined(USE_LDAP) && !defined(GENERIC_UMPC))
1436 /* Select the address if there is only one match */
1437 if (ncount == 2) {
1438 /* Display selected address in entry field */
1439 gchar *addr = get_complete_address(1);
1440 if (addr && !strstr(addr, " <!--___group___-->")) {
1441 replace_address_in_edit(entry, addr, cursor_pos, FALSE, NULL);
1442 /* Discard the window */
1443 clear_completion_cache();
1445 g_free(addr);
1447 /* Make sure that drop-down appears uniform! */
1448 else
1449 #endif
1450 if( ncount == 0 ) {
1451 addrcompl_add_queue( searchTerm );
1452 } else {
1453 g_free( searchTerm );
1456 return TRUE;
1460 * Create new address completion window for specified entry.
1461 * \param entry_ Entry widget to associate with window.
1463 static void address_completion_create_completion_window( GtkEntry *entry_ )
1465 gint x, y;
1466 GdkRectangle rect;
1467 GtkWidget *scroll, *list_view;
1468 GdkGrabStatus status;
1469 GdkDisplay *display;
1470 GtkRequisition r;
1471 GtkWidget *window;
1472 GtkWidget *entry = GTK_WIDGET(entry_);
1474 /* Create new window and list */
1475 window = gtk_window_new(GTK_WINDOW_POPUP);
1476 list_view = addr_compl_list_view_create(_compWindow_);
1478 /* Destroy any existing window */
1479 addrcompl_destroy_window( _compWindow_ );
1481 /* Create new object */
1482 _compWindow_->window = window;
1483 _compWindow_->entry = entry;
1484 _compWindow_->list_view = list_view;
1485 _compWindow_->listCount = 0;
1486 _compWindow_->in_mouse = FALSE;
1488 scroll = gtk_scrolled_window_new(NULL, NULL);
1489 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
1490 GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
1491 gtk_container_add(GTK_CONTAINER(window), scroll);
1492 gtk_container_add(GTK_CONTAINER(scroll), list_view);
1493 gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll),
1494 GTK_SHADOW_OUT);
1496 /* Use entry widget to position initial window */
1497 gtk_widget_get_allocation(entry, &rect);
1499 /* rect.x and rect.y are relative to parent of our GtkEntry,
1500 * we need to convert them to absolute coordinates */
1501 gdk_window_get_root_coords(
1502 gtk_widget_get_window(gtk_widget_get_parent(entry)),
1503 rect.x, rect.y, &x, &y);
1505 /* Move the window to just below the GtkEntry */
1506 gtk_window_move(GTK_WINDOW(window), x, y + rect.height);
1508 /* Resize window to fit initial (empty) address list */
1509 gtk_widget_get_preferred_size(list_view, &r, NULL);
1510 gtk_widget_set_size_request(window, rect.width, r.height);
1511 gtk_widget_show_all(window);
1513 /* Setup handlers */
1514 g_signal_connect(G_OBJECT(list_view), "button_press_event",
1515 G_CALLBACK(list_view_button_press),
1516 _compWindow_);
1518 g_signal_connect(G_OBJECT(list_view), "button_release_event",
1519 G_CALLBACK(list_view_button_release),
1520 _compWindow_);
1522 g_signal_connect(G_OBJECT(window),
1523 "button-press-event",
1524 G_CALLBACK(completion_window_button_press),
1525 _compWindow_ );
1526 g_signal_connect(G_OBJECT(window),
1527 "key-press-event",
1528 G_CALLBACK(completion_window_key_press),
1529 _compWindow_ );
1530 display = gdk_display_get_default();
1531 status = gdk_seat_grab(gdk_display_get_default_seat(display),
1532 gtk_widget_get_window(window),
1533 GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK |
1534 GDK_BUTTON_RELEASE_MASK,
1535 TRUE, NULL, NULL, NULL, NULL);
1536 if (status != GDK_GRAB_SUCCESS)
1537 g_warning("gdk_seat_grab failed with status %d", status);
1538 gtk_grab_add( window );
1542 * Respond to button press in completion window. Check if mouse click is
1543 * anywhere outside the completion window. In that case the completion
1544 * window is destroyed, and the original searchTerm is restored.
1546 * \param widget Window object.
1547 * \param event Event.
1548 * \param compWin Reference to completion window.
1550 static gboolean completion_window_button_press(GtkWidget *widget,
1551 GdkEventButton *event,
1552 CompletionWindow *compWin )
1554 GtkWidget *event_widget, *entry;
1555 gchar *searchTerm;
1556 gint cursor_pos;
1557 gboolean restore = TRUE;
1559 cm_return_val_if_fail(compWin != NULL, FALSE);
1561 entry = compWin->entry;
1562 cm_return_val_if_fail(entry != NULL, FALSE);
1564 /* Test where mouse was clicked */
1565 event_widget = gtk_get_event_widget((GdkEvent *)event);
1566 if (event_widget != widget) {
1567 while (event_widget) {
1568 if (event_widget == widget)
1569 return FALSE;
1570 else if (event_widget == entry) {
1571 restore = FALSE;
1572 break;
1574 event_widget = gtk_widget_get_parent(event_widget);
1578 if (restore) {
1579 /* Clicked outside of completion window - restore */
1580 searchTerm = _compWindow_->searchTerm;
1581 g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1582 replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos, FALSE, NULL);
1585 clear_completion_cache();
1586 addrcompl_destroy_window( _compWindow_ );
1588 return TRUE;
1592 * Respond to key press in completion window.
1593 * \param widget Window object.
1594 * \param event Event.
1595 * \param compWind Reference to completion window.
1597 static gboolean completion_window_key_press(GtkWidget *widget,
1598 GdkEventKey *event,
1599 CompletionWindow *compWin )
1601 GdkEventKey tmp_event;
1602 GtkWidget *entry;
1603 gchar *searchTerm;
1604 gint cursor_pos;
1605 GtkWidget *list_view;
1606 GtkWidget *parent;
1607 cm_return_val_if_fail(compWin != NULL, FALSE);
1609 entry = compWin->entry;
1610 list_view = compWin->list_view;
1611 cm_return_val_if_fail(entry != NULL, FALSE);
1613 /* allow keyboard navigation in the alternatives tree view */
1614 if (event->keyval == GDK_KEY_Up || event->keyval == GDK_KEY_Down ||
1615 event->keyval == GDK_KEY_Page_Up || event->keyval == GDK_KEY_Page_Down) {
1616 completion_window_advance_selection
1617 (GTK_TREE_VIEW(list_view),
1618 event->keyval == GDK_KEY_Down ||
1619 event->keyval == GDK_KEY_Page_Down ? TRUE : FALSE);
1620 return TRUE;
1623 /* make tab move to next field */
1624 if( event->keyval == GDK_KEY_Tab ) {
1625 /* Reference to parent */
1626 parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1628 /* Discard the window */
1629 clear_completion_cache();
1630 addrcompl_destroy_window( _compWindow_ );
1632 /* Move focus to next widget */
1633 if( parent ) {
1634 gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1636 return FALSE;
1639 /* make backtab move to previous field */
1640 if( event->keyval == GDK_KEY_ISO_Left_Tab ) {
1641 /* Reference to parent */
1642 parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1644 /* Discard the window */
1645 clear_completion_cache();
1646 addrcompl_destroy_window( _compWindow_ );
1648 /* Move focus to previous widget */
1649 if( parent ) {
1650 gtk_widget_child_focus( parent, GTK_DIR_TAB_BACKWARD );
1652 return FALSE;
1654 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS));
1656 /* look for presses that accept the selection */
1657 if (event->keyval == GDK_KEY_Return || event->keyval == GDK_KEY_space ||
1658 event->keyval == GDK_KEY_KP_Enter ||
1659 (_allowCommas_ && event->keyval == GDK_KEY_comma)) {
1660 /* User selected address with a key press */
1662 /* Display selected address in entry field */
1663 completion_window_apply_selection(
1664 GTK_TREE_VIEW(list_view), GTK_ENTRY(entry),
1665 event->keyval != GDK_KEY_comma);
1667 if (event->keyval == GDK_KEY_comma) {
1668 gint pos = gtk_editable_get_position(GTK_EDITABLE(entry));
1669 gtk_editable_insert_text(GTK_EDITABLE(entry), ", ", 2, &pos);
1670 gtk_editable_set_position(GTK_EDITABLE(entry), pos + 1);
1673 /* Discard the window */
1674 clear_completion_cache();
1675 addrcompl_destroy_window( _compWindow_ );
1676 return FALSE;
1679 /* key state keys should never be handled */
1680 if (event->keyval == GDK_KEY_Shift_L
1681 || event->keyval == GDK_KEY_Shift_R
1682 || event->keyval == GDK_KEY_Control_L
1683 || event->keyval == GDK_KEY_Control_R
1684 || event->keyval == GDK_KEY_Caps_Lock
1685 || event->keyval == GDK_KEY_Shift_Lock
1686 || event->keyval == GDK_KEY_Meta_L
1687 || event->keyval == GDK_KEY_Meta_R
1688 || event->keyval == GDK_KEY_Alt_L
1689 || event->keyval == GDK_KEY_Alt_R) {
1690 return FALSE;
1693 /* some other key, let's restore the searchTerm (orignal text) */
1694 searchTerm = _compWindow_->searchTerm;
1695 g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1696 replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos, FALSE, NULL);
1698 /* make sure anything we typed comes in the edit box */
1699 tmp_event.type = event->type;
1700 tmp_event.window = gtk_widget_get_window(GTK_WIDGET(entry));
1701 tmp_event.send_event = TRUE;
1702 tmp_event.time = event->time;
1703 tmp_event.state = event->state;
1704 tmp_event.keyval = event->keyval;
1705 tmp_event.length = event->length;
1706 tmp_event.string = event->string;
1707 gtk_widget_event(entry, (GdkEvent *)&tmp_event);
1709 /* and close the completion window */
1710 clear_completion_cache();
1711 addrcompl_destroy_window( _compWindow_ );
1713 return TRUE;
1717 * ============================================================================
1718 * Publically accessible functions.
1719 * ============================================================================
1723 * Setup completion object.
1725 void addrcompl_initialize( void ) {
1726 /* g_print( "addrcompl_initialize...\n" ); */
1727 if( ! _compWindow_ ) {
1728 _compWindow_ = addrcompl_create_window();
1730 _queryID_ = 0;
1731 _completionIdleID_ = 0;
1732 /* g_print( "addrcompl_initialize...done\n" ); */
1736 * Teardown completion object.
1738 void addrcompl_teardown( void ) {
1739 /* g_print( "addrcompl_teardown...\n" ); */
1740 addrcompl_free_window( _compWindow_ );
1741 _compWindow_ = NULL;
1743 addrcompl_clear_queue();
1745 _completionIdleID_ = 0;
1746 /* g_print( "addrcompl_teardown...done\n" ); */
1750 * tree view functions
1753 static GtkListStore *addr_compl_create_store(void)
1755 return gtk_list_store_new(N_ADDR_COMPL_COLUMNS,
1756 GDK_TYPE_PIXBUF,
1757 G_TYPE_STRING,
1758 G_TYPE_BOOLEAN,
1759 G_TYPE_POINTER,
1760 -1);
1763 static GtkWidget *addr_compl_list_view_create(CompletionWindow *window)
1765 GtkTreeView *list_view;
1766 GtkTreeSelection *selector;
1767 GtkTreeModel *model;
1769 model = GTK_TREE_MODEL(addr_compl_create_store());
1770 list_view = GTK_TREE_VIEW(gtk_tree_view_new_with_model(model));
1771 g_object_unref(model);
1773 gtk_tree_view_set_headers_visible(list_view, FALSE);
1775 selector = gtk_tree_view_get_selection(list_view);
1776 gtk_tree_selection_set_mode(selector, GTK_SELECTION_BROWSE);
1777 gtk_tree_selection_set_select_function(selector, addr_compl_selected,
1778 window, NULL);
1780 /* create the columns */
1781 addr_compl_create_list_view_columns(GTK_WIDGET(list_view));
1783 return GTK_WIDGET(list_view);
1786 static void addr_compl_create_list_view_columns(GtkWidget *list_view)
1788 GtkTreeViewColumn *column;
1789 GtkCellRenderer *renderer;
1791 renderer = gtk_cell_renderer_pixbuf_new();
1792 column = gtk_tree_view_column_new_with_attributes
1793 ("", renderer,
1794 "pixbuf", ADDR_COMPL_ICON, NULL);
1795 gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);
1796 renderer = gtk_cell_renderer_text_new();
1797 column = gtk_tree_view_column_new_with_attributes
1798 ("", renderer, "text", ADDR_COMPL_ADDRESS, NULL);
1799 gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);
1802 static gboolean list_view_button_press(GtkWidget *widget, GdkEventButton *event,
1803 CompletionWindow *window)
1805 if (window && event && event->type == GDK_BUTTON_PRESS) {
1806 window->in_mouse = TRUE;
1808 return FALSE;
1811 static gboolean list_view_button_release(GtkWidget *widget, GdkEventButton *event,
1812 CompletionWindow *window)
1814 if (window && event && event->type == GDK_BUTTON_RELEASE) {
1815 window->in_mouse = FALSE;
1817 return FALSE;
1820 static gboolean addr_compl_selected(GtkTreeSelection *selector,
1821 GtkTreeModel *model,
1822 GtkTreePath *path,
1823 gboolean currently_selected,
1824 gpointer data)
1826 CompletionWindow *window = data;
1828 if (currently_selected)
1829 return TRUE;
1831 if (!window->in_mouse)
1832 return TRUE;
1834 /* XXX: select the entry and kill window later... select is called before
1835 * any other mouse events handlers including the tree view internal one;
1836 * not using a time out would result in a crash. if this doesn't work
1837 * safely, maybe we should set variables when receiving button presses
1838 * in the tree view. */
1839 if (!window->destroying) {
1840 window->destroying = TRUE;
1841 g_idle_add((GSourceFunc) addr_compl_defer_select_destruct, data);
1844 return TRUE;
1847 static gboolean addr_compl_defer_select_destruct(CompletionWindow *window)
1849 GtkEntry *entry = GTK_ENTRY(window->entry);
1851 completion_window_apply_selection(GTK_TREE_VIEW(window->list_view),
1852 entry, TRUE);
1854 clear_completion_cache();
1856 addrcompl_destroy_window(window);
1857 return FALSE;
1860 gboolean found_in_addressbook(const gchar *address)
1862 gchar *addr = NULL;
1863 gboolean found = FALSE;
1864 gint num_addr = 0;
1866 if (!address)
1867 return FALSE;
1869 addr = g_strdup(address);
1870 extract_address(addr);
1871 num_addr = complete_address(addr);
1872 if (num_addr > 1) {
1873 /* skip first item (this is the search string itself) */
1874 int i = 1;
1875 for (; i < num_addr && !found; i++) {
1876 gchar *caddr = get_complete_address(i);
1877 extract_address(caddr);
1878 if (strcasecmp(caddr, addr) == 0)
1879 found = TRUE;
1880 g_free(caddr);
1883 g_free(addr);
1884 return found;
1888 * End of Source.