2 * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
4 * Copyright (C) 2000-2012 by Alfons Hoogervorst & The Claws Mail Team.
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/>.
23 #include "claws-features.h"
28 #include <glib/gi18n.h>
29 #include <gdk/gdkkeysyms.h>
34 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
39 #include "addr_compl.h"
42 #include "prefs_common.h"
46 #include "stock_pixmap.h"
49 #ifndef USE_NEW_ADDRBOOK
50 #include "addrindex.h"
52 #include "addressbook-dbus.h"
56 *\brief For the GtkListStore
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.
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).
85 * completion_entry - structure used to complete addresses, with a reference
86 * the the real address information.
90 gchar *string; /* string to complete */
91 address_entry *ref; /* address the string belongs to */
94 /*******************************************************************************/
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 */
101 static GHashTable *_groupAddresses_ = NULL;
102 static gboolean _allowCommas_ = TRUE;
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. */
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
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 */
115 static gchar *completion_folder_path = NULL;
117 /*******************************************************************************/
120 * Define the structure of the completion window.
122 typedef struct _CompletionWindow CompletionWindow;
123 struct _CompletionWindow {
128 GtkWidget *list_view;
130 gboolean in_mouse; /*!< mouse press pending... */
131 gboolean destroying; /*!< destruction in progress */
134 static GtkListStore *addr_compl_create_store (void);
136 static GtkWidget *addr_compl_list_view_create (CompletionWindow *window);
138 static void addr_compl_create_list_view_columns (GtkWidget *list_view);
140 static gboolean list_view_button_press (GtkWidget *widget,
141 GdkEventButton *event,
142 CompletionWindow *window);
144 static gboolean list_view_button_release (GtkWidget *widget,
145 GdkEventButton *event,
146 CompletionWindow *window);
148 static gboolean addr_compl_selected (GtkTreeSelection *selector,
151 gboolean currently_selected,
154 static gboolean addr_compl_defer_select_destruct(CompletionWindow *window);
157 * Function used by GTK to find the string data to be used for completion.
158 * \param data Pointer to data being processed.
160 static gchar *completion_func(gpointer data)
162 cm_return_val_if_fail(data != NULL, NULL);
164 return ((completion_entry *)data)->string;
168 * Initialize all completion index data.
170 static void init_all(void)
172 g_completion = g_completion_new(completion_func);
173 cm_return_if_fail(g_completion != NULL);
176 static void free_all_addresses(void)
181 walk = g_address_list;
182 for (; walk != NULL; walk = g_list_next(walk)) {
183 address_entry *ae = (address_entry *) walk->data;
186 g_list_free(ae->grp_emails);
189 g_list_free(g_address_list);
190 g_address_list = NULL;
191 if (_groupAddresses_)
192 g_hash_table_destroy(_groupAddresses_);
193 _groupAddresses_ = NULL;
196 static void clear_completion_cache(void);
197 static void free_completion_list(void)
200 if (!g_completion_list)
203 clear_completion_cache();
205 g_completion_clear_items(g_completion);
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;
213 g_list_free(g_completion_list);
214 g_completion_list = NULL;
217 * Free up all completion index data.
219 static void free_all(void)
221 free_completion_list();
222 free_all_addresses();
223 g_completion_free(g_completion);
228 * Append specified address entry to the index.
229 * \param str Index string value.
230 * \param ae Entry containing address data.
232 void addr_compl_add_address1(const char *str, address_entry *ae)
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);
240 g_completion_list = g_list_prepend(g_completion_list, ce1);
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>
254 static gint add_address(const gchar *name, const gchar *address,
255 const gchar *nick, const gchar *alias, GList *grp_emails)
259 if (!address && !grp_emails)
265 ae = g_new0(address_entry, 1);
266 cm_return_val_if_fail(ae != NULL, -1);
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);
273 addr_compl_add_address1(name, ae);
275 if (address != NULL && *address != '\0')
276 addr_compl_add_address1(address, ae);
278 if (nick != NULL && *nick != '\0')
279 addr_compl_add_address1(nick, ae);
281 if (alias != NULL && *alias != '\0')
282 addr_compl_add_address1(alias, ae);
288 * Read address book, creating all entries in the completion index.
290 static void read_address_book(gchar *folderpath) {
291 free_all_addresses();
292 free_completion_list();
294 #ifndef USE_NEW_ADDRBOOK
295 addrindex_load_completion( add_address, folderpath );
297 GError* error = NULL;
299 addrcompl_initialize();
300 if (! addrindex_dbus_load_completion(add_address, &error)) {
301 g_warning("Failed to populate address completion list");
306 /* plugins may hook in here to modify/extend the completion list */
307 hooks_invoke(ADDDRESS_COMPLETION_BUILD_ADDRESS_LIST_HOOKLIST, &g_address_list);
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)");
322 * Test whether there is a completion pending.
323 * \return <code>TRUE</code> if pending.
325 static gboolean is_completion_pending(void)
327 /* check if completion pending, i.e. we might satisfy a request for the next
328 * or previous address */
329 return g_completion_count;
333 * Clear the completion cache.
335 static void clear_completion_cache(void)
337 if (is_completion_pending()) {
338 g_free(g_completion_prefix);
340 if (g_completion_addresses) {
341 g_slist_free(g_completion_addresses);
342 g_completion_addresses = NULL;
345 g_completion_count = g_completion_next = 0;
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.
354 gint start_address_completion(gchar *folderpath)
356 gboolean different_book = FALSE;
357 clear_completion_cache();
359 if (strcmp2(completion_folder_path,folderpath))
360 different_book = TRUE;
362 g_free(completion_folder_path);
363 if (folderpath != NULL)
364 completion_folder_path = g_strdup(folderpath);
366 completion_folder_path = NULL;
370 /* open the address book */
371 read_address_book(folderpath);
372 } else if (different_book)
373 read_address_book(folderpath);
376 debug_print("start_address_completion(%s) ref count %d\n",
377 folderpath?folderpath:"(null)", g_ref_count);
379 return g_list_length(g_completion_list);
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.
387 * \param entry Address entry field.
388 * \param start_pos Address of start position of address.
389 * \return Possible address.
391 static gchar *get_address_from_edit(GtkEntry *entry, gint *start_pos)
393 const gchar *edit_text, *p;
395 gboolean in_quote = FALSE;
396 gboolean in_bracket = FALSE;
399 edit_text = gtk_entry_get_text(entry);
400 if (edit_text == NULL) return NULL;
402 cur_pos = gtk_editable_get_position(GTK_EDITABLE(entry));
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);
407 p = g_utf8_prev_char(p)) {
410 } else if (!in_quote) {
411 if (!in_bracket && *p == ',') {
413 } else if (*p == '<')
420 /* have something valid */
421 if (g_utf8_strlen(p, -1) == 0)
424 #define IS_VALID_CHAR(x) \
425 (g_ascii_isalnum(x) || (x) == '"' || (x) == '<' || (((unsigned char)(x)) > 0x7f))
427 /* now scan back until we hit a valid character */
428 for (; *p && !IS_VALID_CHAR(*p); p = g_utf8_next_char(p))
433 if (g_utf8_strlen(p, -1) == 0)
436 if (start_pos) *start_pos = g_utf8_pointer_to_offset(edit_text, p);
443 static gchar *get_complete_address_from_name_email(const gchar *name, const gchar *email)
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);
452 address = g_strdup_printf
453 ("%s <%s>", name, email);
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.
463 static void replace_address_in_edit(GtkEntry *entry, const gchar *newtext,
464 gint start_pos, gboolean is_group, GList *grp_emails)
466 if (!newtext) return;
467 gtk_editable_delete_text(GTK_EDITABLE(entry), start_pos, -1);
469 gtk_editable_insert_text(GTK_EDITABLE(entry), newtext, strlen(newtext),
472 gchar *addresses = NULL;
473 GList *cur = grp_emails;
474 for (; cur; cur = cur->next) {
476 ItemEMail *email = (ItemEMail *)cur->data;
477 ItemPerson *person = ( ItemPerson * ) ADDRITEM_PARENT(email);
479 gchar *addr = get_complete_address_from_name_email(
480 ADDRITEM_NAME(person), email->address);
482 tmp = g_strdup_printf("%s, %s", addresses, addr);
484 tmp = g_strdup_printf("%s", addr);
489 gtk_editable_insert_text(GTK_EDITABLE(entry), addresses, strlen(addresses),
493 gtk_editable_set_position(GTK_EDITABLE(entry), -1);
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.
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.
504 guint complete_address(const gchar *str)
506 GList *result = NULL;
510 completion_entry *ce = NULL;
512 cm_return_val_if_fail(str != NULL, 0);
514 /* g_completion is case sensitive */
515 d = g_utf8_strdown(str, -1);
517 clear_completion_cache();
518 g_completion_prefix = g_strdup(str);
520 result = g_completion_complete(g_completion, d, NULL);
522 count = g_list_length(result);
524 /* create list with unique addresses */
525 for (cpl = 0, result = g_list_first(result);
527 result = g_list_next(result)) {
528 ce = (completion_entry *)(result->data);
529 if (NULL == g_slist_find(g_completion_addresses,
532 g_completion_addresses =
533 g_slist_append(g_completion_addresses,
537 count = cpl + 1; /* index 0 is the original prefix */
538 g_completion_next = 1; /* we start at the first completed one */
540 g_free(g_completion_prefix);
541 g_completion_prefix = NULL;
544 g_completion_count = count;
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.
557 guint complete_matches_found(const gchar *str)
559 GList *result = NULL;
562 cm_return_val_if_fail(str != NULL, 0);
564 /* g_completion is case sensitive */
565 d = g_utf8_strdown(str, -1);
567 clear_completion_cache();
568 g_completion_prefix = g_strdup(str);
570 result = g_completion_complete(g_completion, d, NULL);
572 g_free(g_completion_prefix);
575 return g_list_length(result);
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.
584 gchar *get_complete_address(gint index)
586 const address_entry *p;
587 gchar *address = NULL;
589 if (index < g_completion_count) {
591 address = g_strdup(g_completion_prefix);
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) {
600 address = g_strdup_printf("%s (%s) <!--___group___-->", p->name, _("Group"));
601 if (!_groupAddresses_) {
602 _groupAddresses_ = g_hash_table_new(NULL, g_direct_equal);
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);
616 * Return the next complete address match from the completion index.
617 * \return Completed address string; this should be freed when done.
619 static gchar *get_next_complete_address(void)
621 if (is_completion_pending()) {
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;
635 * Return a count of the completed matches in the completion index.
636 * \return Number of matched entries.
638 static guint get_completion_count(void)
640 if (is_completion_pending())
641 return g_completion_count;
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
650 * \return Number of entries in index.
652 gint invalidate_address_completion(void)
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();
661 return g_list_length(g_completion_list);
665 * Finished with completion index. This function should be called after
666 * matching addresses.
667 * \return Reference count.
669 gint end_address_completion(void)
671 gboolean different_folder = FALSE;
672 clear_completion_cache();
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;
680 if (0 == --g_ref_count)
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();
695 static CompletionWindow *_compWindow_ = NULL;
698 * Mutex to protect callback from multiple threads.
700 static pthread_mutex_t _completionMutex_ = PTHREAD_MUTEX_INITIALIZER;
703 * Completion queue list.
705 static GList *_displayQueue_ = NULL;
709 static gint _queryID_ = 0;
712 * Completion idle ID.
714 static guint _completionIdleID_ = 0;
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.
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 */
724 static void address_completion_mainwindow_set_focus (GtkWindow *window,
727 static gboolean address_completion_entry_key_pressed (GtkEntry *entry,
730 static gboolean address_completion_complete_address_in_entry
733 static void address_completion_create_completion_window (GtkEntry *entry);
735 static gboolean completion_window_button_press
737 GdkEventButton *event,
738 CompletionWindow *compWin );
740 static gboolean completion_window_key_press
743 CompletionWindow *compWin );
744 static void address_completion_create_completion_window( GtkEntry *entry_ );
747 * Create a completion window object.
748 * \return Initialized completion window.
750 static CompletionWindow *addrcompl_create_window( void ) {
751 CompletionWindow *cw;
753 cw = g_new0( CompletionWindow, 1 );
755 cw->searchTerm = NULL;
758 cw->list_view = NULL;
759 cw->in_mouse = FALSE;
760 cw->destroying = FALSE;
766 * Destroy completion window.
767 * \param cw Window to destroy.
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_ );
774 /* Remove idler function... or application may not terminate */
775 if( _completionIdleID_ != 0 ) {
776 g_source_remove( _completionIdleID_ );
777 _completionIdleID_ = 0;
780 /* Now destroy window */
782 /* Clear references to widgets */
784 cw->list_view = NULL;
788 gtk_widget_hide( cw->window );
789 gtk_widget_destroy( cw->window );
792 cw->destroying = FALSE;
793 cw->in_mouse = FALSE;
799 * Free up completion window.
800 * \param cw Window to free.
802 static void addrcompl_free_window( CompletionWindow *cw ) {
804 addrcompl_destroy_window( cw );
806 g_free( cw->searchTerm );
807 cw->searchTerm = NULL;
809 /* Clear references */
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
823 static void completion_window_advance_selection(GtkTreeView *list_view, gboolean forward)
825 GtkTreeSelection *selection;
829 cm_return_if_fail(list_view != NULL);
831 selection = gtk_tree_view_get_selection(list_view);
832 if (!gtk_tree_selection_get_selected(selection, &model, &iter))
836 forward = gtk_tree_model_iter_next(model, &iter);
838 gtk_tree_selection_select_iter(selection, &iter);
842 prev = gtk_tree_model_get_path(model, &iter);
846 if (gtk_tree_path_prev(prev))
847 gtk_tree_selection_select_path(selection, prev);
849 gtk_tree_path_free(prev);
854 * Resize window to accommodate maximum number of address entries.
855 * \param cw Completion window.
857 static void addrcompl_resize_window( CompletionWindow *cw ) {
859 gint x, y, width, height, depth;
861 /* Get current geometry of window */
862 #if !GTK_CHECK_VERSION(3, 0, 0)
863 gdk_window_get_geometry( gtk_widget_get_window( cw->window ), &x, &y, &width, &height, &depth );
865 gdk_window_get_geometry( gtk_widget_get_window( cw->window ), &x, &y, &width, &height );
868 /* simple _hide breaks size requisition !? */
869 #if !GTK_CHECK_VERSION(3, 0, 0)
870 gtk_widget_hide_all( cw->window );
871 gtk_widget_show_all( cw->window );
873 gtk_widget_hide( cw->window );
874 gtk_widget_show( cw->window );
876 gtk_widget_size_request( cw->list_view, &r );
878 /* Adjust window height to available screen space */
879 if( y + r.height > gdk_screen_height())
880 r.height = gdk_screen_height() - y;
882 gtk_widget_set_size_request(cw->window, width, r.height);
884 gdk_pointer_grab(gtk_widget_get_window(cw->window), TRUE,
885 GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK |
886 GDK_BUTTON_RELEASE_MASK,
887 NULL, NULL, GDK_CURRENT_TIME);
888 gdk_keyboard_grab(gtk_widget_get_window(cw->window), FALSE, GDK_CURRENT_TIME);
889 gtk_grab_add(cw->window);
893 static GdkPixbuf *group_pixbuf = NULL;
894 static GdkPixbuf *email_pixbuf = NULL;
897 * Add an address the completion window address list.
898 * \param cw Completion window.
899 * \param address Address to add.
901 static void addrcompl_add_entry( CompletionWindow *cw, gchar *address ) {
904 GtkTreeSelection *selection;
905 gboolean is_group = FALSE;
906 GList *grp_emails = NULL;
907 store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(cw->list_view)));
911 stock_pixbuf_gdk(cw->list_view, STOCK_PIXMAP_ADDR_TWO, &group_pixbuf);
912 g_object_ref(G_OBJECT(group_pixbuf));
915 stock_pixbuf_gdk(cw->list_view, STOCK_PIXMAP_ADDR_ONE, &email_pixbuf);
916 g_object_ref(G_OBJECT(email_pixbuf));
918 /* g_print( "\t\tAdding :%s\n", address ); */
919 if (strstr(address, " <!--___group___-->")) {
921 if (_groupAddresses_)
922 grp_emails = g_hash_table_lookup(_groupAddresses_, GINT_TO_POINTER(g_str_hash(address)));
923 *(strstr(address, " <!--___group___-->")) = '\0';
924 pixbuf = group_pixbuf;
925 } else if (strchr(address, '@') && strchr(address, '<') &&
926 strchr(address, '>')) {
927 pixbuf = email_pixbuf;
931 if (is_group && !_allowCommas_)
933 gtk_list_store_append(store, &iter);
934 gtk_list_store_set(store, &iter,
935 ADDR_COMPL_ICON, pixbuf,
936 ADDR_COMPL_ADDRESS, address,
937 ADDR_COMPL_ISGROUP, is_group,
938 ADDR_COMPL_GROUPLIST, grp_emails,
943 addrcompl_resize_window( cw );
944 gtk_grab_add( cw->window );
946 selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(cw->list_view));
947 gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store), &iter);
949 if( cw->listCount == 1 ) {
950 /* Select first row for now */
951 gtk_tree_selection_select_iter(selection, &iter);
954 else if( cw->listCount == 2 ) {
955 gtk_tree_model_iter_next(GTK_TREE_MODEL(store), &iter);
956 /* Move off first row */
957 gtk_tree_selection_select_iter(selection, &iter);
963 * Completion idle function. This function is called by the main (UI) thread
964 * during UI idle time while an address search is in progress. Items from the
965 * display queue are processed and appended to the address list.
967 * \param data Target completion window to receive email addresses.
968 * \return <i>TRUE</i> to ensure that idle event do not get ignored.
970 static gboolean addrcompl_idle( gpointer data ) {
974 /* Process all entries in display queue */
975 pthread_mutex_lock( & _completionMutex_ );
976 if( _displayQueue_ ) {
977 node = _displayQueue_;
979 address = node->data;
980 /* g_print( "address ::: %s :::\n", address ); */
981 addrcompl_add_entry( _compWindow_, address );
983 node = g_list_next( node );
985 g_list_free( _displayQueue_ );
986 _displayQueue_ = NULL;
988 pthread_mutex_unlock( & _completionMutex_ );
995 * Callback entry point. The background thread (if any) appends the address
996 * list to the display queue.
997 * \param sender Sender of query.
998 * \param queryID Query ID of search request.
999 * \param listEMail List of zero of more email objects that met search
1001 * \param data Query data.
1003 #ifndef USE_NEW_ADDRBOOK
1004 static gint addrcompl_callback_entry(
1005 gpointer sender, gint queryID, GList *listEMail, gpointer data )
1010 /* g_print( "addrcompl_callback_entry::queryID=%d\n", queryID ); */
1011 pthread_mutex_lock( & _completionMutex_ );
1012 if( queryID == _queryID_ ) {
1013 /* Append contents to end of display queue */
1016 ItemEMail *email = node->data;
1018 address = addritem_format_email( email );
1019 /* g_print( "\temail/address ::%s::\n", address ); */
1020 _displayQueue_ = g_list_append( _displayQueue_, address );
1021 node = g_list_next( node );
1024 g_list_free( listEMail );
1025 pthread_mutex_unlock( & _completionMutex_ );
1032 * Clear the display queue.
1034 static void addrcompl_clear_queue( void ) {
1035 /* Clear out display queue */
1036 pthread_mutex_lock( & _completionMutex_ );
1038 g_list_free( _displayQueue_ );
1039 _displayQueue_ = NULL;
1041 pthread_mutex_unlock( & _completionMutex_ );
1045 * Add a single address entry into the display queue.
1046 * \param address Address to append.
1048 static void addrcompl_add_queue( gchar *address ) {
1049 pthread_mutex_lock( & _completionMutex_ );
1050 _displayQueue_ = g_list_append( _displayQueue_, address );
1051 pthread_mutex_unlock( & _completionMutex_ );
1055 * Load list with entries from local completion index.
1057 static void addrcompl_load_local( void ) {
1060 for (count = 0; count < get_completion_count(); count++) {
1063 address = get_complete_address( count );
1064 /* g_print( "\taddress ::%s::\n", address ); */
1066 /* Append contents to end of display queue */
1067 addrcompl_add_queue( address );
1074 static void addrcompl_start_search( void ) {
1075 #ifndef USE_NEW_ADDRBOOK
1078 searchTerm = g_strdup( _compWindow_->searchTerm );
1080 /* Setup the search */
1081 _queryID_ = addrindex_setup_search(
1082 searchTerm, NULL, addrcompl_callback_entry );
1083 g_free( searchTerm );
1085 /* g_print( "addrcompl_start_search::queryID=%d\n", _queryID_ ); */
1087 /* Load local stuff */
1088 addrcompl_load_local();
1090 /* Sit back and wait until something happens */
1091 _completionIdleID_ =
1092 g_idle_add( (GSourceFunc) addrcompl_idle, NULL );
1093 /* g_print( "addrindex_start_search::queryID=%d\n", _queryID_ ); */
1095 #ifndef USE_NEW_ADDRBOOK
1096 addrindex_start_search( _queryID_ );
1103 * Apply the current selection in the list to the entry field. Focus is also
1104 * moved to the next widget so that Tab key works correctly.
1105 * \param list_view List to process.
1106 * \param entry Address entry field.
1107 * \param move_focus Move focus to the next widget ?
1109 static void completion_window_apply_selection(GtkTreeView *list_view,
1111 gboolean move_focus)
1113 gchar *address = NULL, *text = NULL;
1116 GtkTreeSelection *selection;
1117 GtkTreeModel *model;
1119 gboolean is_group = FALSE;
1120 cm_return_if_fail(list_view != NULL);
1121 cm_return_if_fail(entry != NULL);
1122 GList *grp_emails = NULL;
1124 selection = gtk_tree_view_get_selection(list_view);
1125 if (! gtk_tree_selection_get_selected(selection, &model, &iter))
1128 /* First remove the idler */
1129 if( _completionIdleID_ != 0 ) {
1130 g_source_remove( _completionIdleID_ );
1131 _completionIdleID_ = 0;
1134 /* Process selected item */
1135 gtk_tree_model_get(model, &iter, ADDR_COMPL_ADDRESS, &text,
1136 ADDR_COMPL_ISGROUP, &is_group,
1137 ADDR_COMPL_GROUPLIST, &grp_emails,
1140 address = get_address_from_edit(entry, &cursor_pos);
1142 replace_address_in_edit(entry, text, cursor_pos, is_group, grp_emails);
1145 /* Move focus to next widget */
1146 parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1147 if( parent && move_focus) {
1148 gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1153 * Start address completion. Should be called when creating the main window
1154 * containing address completion entries.
1155 * \param mainwindow Main window.
1157 void address_completion_start(GtkWidget *mainwindow)
1159 start_address_completion(NULL);
1161 /* register focus change hook */
1162 g_signal_connect(G_OBJECT(mainwindow), "set_focus",
1163 G_CALLBACK(address_completion_mainwindow_set_focus),
1168 * Need unique data to make unregistering signal handler possible for the auto
1171 #define COMPLETION_UNIQUE_DATA (GINT_TO_POINTER(0xfeefaa))
1174 * Register specified entry widget for address completion.
1175 * \param entry Address entry field.
1177 void address_completion_register_entry(GtkEntry *entry, gboolean allow_commas)
1179 cm_return_if_fail(entry != NULL);
1180 cm_return_if_fail(GTK_IS_ENTRY(entry));
1182 /* add hooked property */
1183 g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, entry);
1184 g_object_set_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS, GINT_TO_POINTER(allow_commas));
1186 /* add keypress event */
1187 g_signal_connect_closure
1188 (G_OBJECT(entry), "key_press_event",
1189 g_cclosure_new(G_CALLBACK(address_completion_entry_key_pressed),
1190 COMPLETION_UNIQUE_DATA,
1196 * Unregister specified entry widget from address completion operations.
1197 * \param entry Address entry field.
1199 void address_completion_unregister_entry(GtkEntry *entry)
1203 cm_return_if_fail(entry != NULL);
1204 cm_return_if_fail(GTK_IS_ENTRY(entry));
1206 entry_obj = g_object_get_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK);
1207 cm_return_if_fail(entry_obj);
1208 cm_return_if_fail(G_OBJECT(entry_obj) == G_OBJECT(entry));
1210 /* has the hooked property? */
1211 g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, NULL);
1213 /* remove the hook */
1214 g_signal_handlers_disconnect_by_func(G_OBJECT(entry),
1215 G_CALLBACK(address_completion_entry_key_pressed),
1216 COMPLETION_UNIQUE_DATA);
1220 * End address completion. Should be called when main window with address
1221 * completion entries terminates. NOTE: this function assumes that it is
1222 * called upon destruction of the window.
1223 * \param mainwindow Main window.
1225 void address_completion_end(GtkWidget *mainwindow)
1227 /* if address_completion_end() is really called on closing the window,
1228 * we don't need to unregister the set_focus_cb */
1229 end_address_completion();
1232 /* if focus changes to another entry, then clear completion cache */
1233 static void address_completion_mainwindow_set_focus(GtkWindow *window,
1238 if (widget && GTK_IS_ENTRY(widget) &&
1239 g_object_get_data(G_OBJECT(widget), ENTRY_DATA_TAB_HOOK)) {
1240 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), ENTRY_DATA_ALLOW_COMMAS));
1241 clear_completion_cache();
1246 * Listener that watches for tab or other keystroke in address entry field.
1247 * \param entry Address entry field.
1248 * \param ev Event object.
1249 * \param data User data.
1250 * \return <i>TRUE</i>.
1252 static gboolean address_completion_entry_key_pressed(GtkEntry *entry,
1256 if (ev->keyval == GDK_KEY_Tab) {
1257 addrcompl_clear_queue();
1258 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS));
1259 if( address_completion_complete_address_in_entry( entry, TRUE ) ) {
1260 /* route a void character to the default handler */
1261 /* this is a dirty hack; we're actually changing a key
1262 * reported by the system. */
1263 ev->keyval = GDK_KEY_AudibleBell_Enable;
1264 ev->state &= ~GDK_SHIFT_MASK;
1267 address_completion_create_completion_window(entry);
1269 /* Start remote queries */
1270 addrcompl_start_search();
1277 } else if (ev->keyval == GDK_KEY_Shift_L
1278 || ev->keyval == GDK_KEY_Shift_R
1279 || ev->keyval == GDK_KEY_Control_L
1280 || ev->keyval == GDK_KEY_Control_R
1281 || ev->keyval == GDK_KEY_Caps_Lock
1282 || ev->keyval == GDK_KEY_Shift_Lock
1283 || ev->keyval == GDK_KEY_Meta_L
1284 || ev->keyval == GDK_KEY_Meta_R
1285 || ev->keyval == GDK_KEY_Alt_L
1286 || ev->keyval == GDK_KEY_Alt_R) {
1287 /* these buttons should not clear the cache... */
1289 clear_completion_cache();
1294 * Initialize search term for address completion.
1295 * \param entry Address entry field.
1297 static gboolean address_completion_complete_address_in_entry(GtkEntry *entry,
1300 gint ncount, cursor_pos;
1301 gchar *searchTerm, *new = NULL;
1303 cm_return_val_if_fail(entry != NULL, FALSE);
1305 if (!gtk_widget_has_focus(GTK_WIDGET(entry))) return FALSE;
1307 /* get an address component from the cursor */
1308 searchTerm = get_address_from_edit( entry, &cursor_pos );
1309 if( ! searchTerm ) return FALSE;
1310 /* g_print( "search for :::%s:::\n", searchTerm ); */
1312 /* Clear any existing search */
1313 g_free( _compWindow_->searchTerm );
1314 _compWindow_->searchTerm = g_strdup( searchTerm );
1316 /* Perform search on local completion index */
1317 ncount = complete_address( searchTerm );
1319 new = get_next_complete_address();
1322 #if (!defined(USE_LDAP) && !defined(GENERIC_UMPC))
1323 /* Select the address if there is only one match */
1325 /* Display selected address in entry field */
1326 gchar *addr = get_complete_address(1);
1327 if (addr && !strstr(addr, " <!--___group___-->")) {
1328 replace_address_in_edit(entry, addr, cursor_pos, FALSE, NULL);
1329 /* Discard the window */
1330 clear_completion_cache();
1334 /* Make sure that drop-down appears uniform! */
1338 addrcompl_add_queue( g_strdup( searchTerm ) );
1340 g_free( searchTerm );
1346 * Create new address completion window for specified entry.
1347 * \param entry_ Entry widget to associate with window.
1349 static void address_completion_create_completion_window( GtkEntry *entry_ )
1351 gint x, y, height, width, depth;
1352 GtkWidget *scroll, *list_view;
1355 GtkWidget *entry = GTK_WIDGET(entry_);
1358 /* Create new window and list */
1359 window = gtk_window_new(GTK_WINDOW_POPUP);
1360 list_view = addr_compl_list_view_create(_compWindow_);
1362 /* Destroy any existing window */
1363 addrcompl_destroy_window( _compWindow_ );
1365 /* Create new object */
1366 _compWindow_->window = window;
1367 _compWindow_->entry = entry;
1368 _compWindow_->list_view = list_view;
1369 _compWindow_->listCount = 0;
1370 _compWindow_->in_mouse = FALSE;
1372 scroll = gtk_scrolled_window_new(NULL, NULL);
1373 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
1374 GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
1375 gtk_container_add(GTK_CONTAINER(window), scroll);
1376 gtk_container_add(GTK_CONTAINER(scroll), list_view);
1377 gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll),
1379 /* Use entry widget to create initial window */
1380 gdkwin = gtk_widget_get_window(entry),
1381 #if !GTK_CHECK_VERSION(3, 0, 0)
1382 gdk_window_get_geometry(gdkwin, &x, &y, &width, &height, &depth);
1384 gdk_window_get_geometry(gdkwin, &x, &y, &width, &height);
1386 gdk_window_get_origin (gdkwin, &x, &y);
1388 gtk_window_move(GTK_WINDOW(window), x, y);
1390 /* Resize window to fit initial (empty) address list */
1391 gtk_widget_size_request( list_view, &r );
1392 gtk_widget_set_size_request( window, width, r.height );
1393 gtk_widget_show_all( window );
1394 gtk_widget_size_request( list_view, &r );
1396 /* Setup handlers */
1397 g_signal_connect(G_OBJECT(list_view), "button_press_event",
1398 G_CALLBACK(list_view_button_press),
1401 g_signal_connect(G_OBJECT(list_view), "button_release_event",
1402 G_CALLBACK(list_view_button_release),
1405 g_signal_connect(G_OBJECT(window),
1406 "button-press-event",
1407 G_CALLBACK(completion_window_button_press),
1409 g_signal_connect(G_OBJECT(window),
1411 G_CALLBACK(completion_window_key_press),
1413 gdk_pointer_grab(gtk_widget_get_window(window), TRUE,
1414 GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK |
1415 GDK_BUTTON_RELEASE_MASK,
1416 NULL, NULL, GDK_CURRENT_TIME);
1417 gdk_keyboard_grab(gtk_widget_get_window(window), FALSE, GDK_CURRENT_TIME);
1418 gtk_grab_add( window );
1422 * Respond to button press in completion window. Check if mouse click is
1423 * anywhere outside the completion window. In that case the completion
1424 * window is destroyed, and the original searchTerm is restored.
1426 * \param widget Window object.
1427 * \param event Event.
1428 * \param compWin Reference to completion window.
1430 static gboolean completion_window_button_press(GtkWidget *widget,
1431 GdkEventButton *event,
1432 CompletionWindow *compWin )
1434 GtkWidget *event_widget, *entry;
1437 gboolean restore = TRUE;
1439 cm_return_val_if_fail(compWin != NULL, FALSE);
1441 entry = compWin->entry;
1442 cm_return_val_if_fail(entry != NULL, FALSE);
1444 /* Test where mouse was clicked */
1445 event_widget = gtk_get_event_widget((GdkEvent *)event);
1446 if (event_widget != widget) {
1447 while (event_widget) {
1448 if (event_widget == widget)
1450 else if (event_widget == entry) {
1454 event_widget = gtk_widget_get_parent(event_widget);
1459 /* Clicked outside of completion window - restore */
1460 searchTerm = _compWindow_->searchTerm;
1461 g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1462 replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos, FALSE, NULL);
1465 clear_completion_cache();
1466 addrcompl_destroy_window( _compWindow_ );
1472 * Respond to key press in completion window.
1473 * \param widget Window object.
1474 * \param event Event.
1475 * \param compWind Reference to completion window.
1477 static gboolean completion_window_key_press(GtkWidget *widget,
1479 CompletionWindow *compWin )
1481 GdkEventKey tmp_event;
1485 GtkWidget *list_view;
1487 cm_return_val_if_fail(compWin != NULL, FALSE);
1489 entry = compWin->entry;
1490 list_view = compWin->list_view;
1491 cm_return_val_if_fail(entry != NULL, FALSE);
1493 /* allow keyboard navigation in the alternatives tree view */
1494 if (event->keyval == GDK_KEY_Up || event->keyval == GDK_KEY_Down ||
1495 event->keyval == GDK_KEY_Page_Up || event->keyval == GDK_KEY_Page_Down) {
1496 completion_window_advance_selection
1497 (GTK_TREE_VIEW(list_view),
1498 event->keyval == GDK_KEY_Down ||
1499 event->keyval == GDK_KEY_Page_Down ? TRUE : FALSE);
1503 /* make tab move to next field */
1504 if( event->keyval == GDK_KEY_Tab ) {
1505 /* Reference to parent */
1506 parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1508 /* Discard the window */
1509 clear_completion_cache();
1510 addrcompl_destroy_window( _compWindow_ );
1512 /* Move focus to next widget */
1514 gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1519 /* make backtab move to previous field */
1520 if( event->keyval == GDK_KEY_ISO_Left_Tab ) {
1521 /* Reference to parent */
1522 parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1524 /* Discard the window */
1525 clear_completion_cache();
1526 addrcompl_destroy_window( _compWindow_ );
1528 /* Move focus to previous widget */
1530 gtk_widget_child_focus( parent, GTK_DIR_TAB_BACKWARD );
1534 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS));
1536 /* look for presses that accept the selection */
1537 if (event->keyval == GDK_KEY_Return || event->keyval == GDK_KEY_space ||
1538 event->keyval == GDK_KEY_KP_Enter ||
1539 (_allowCommas_ && event->keyval == GDK_KEY_comma)) {
1540 /* User selected address with a key press */
1542 /* Display selected address in entry field */
1543 completion_window_apply_selection(
1544 GTK_TREE_VIEW(list_view), GTK_ENTRY(entry),
1545 event->keyval != GDK_KEY_comma);
1547 if (event->keyval == GDK_KEY_comma) {
1548 gint pos = gtk_editable_get_position(GTK_EDITABLE(entry));
1549 gtk_editable_insert_text(GTK_EDITABLE(entry), ", ", 2, &pos);
1550 gtk_editable_set_position(GTK_EDITABLE(entry), pos + 1);
1553 /* Discard the window */
1554 clear_completion_cache();
1555 addrcompl_destroy_window( _compWindow_ );
1559 /* key state keys should never be handled */
1560 if (event->keyval == GDK_KEY_Shift_L
1561 || event->keyval == GDK_KEY_Shift_R
1562 || event->keyval == GDK_KEY_Control_L
1563 || event->keyval == GDK_KEY_Control_R
1564 || event->keyval == GDK_KEY_Caps_Lock
1565 || event->keyval == GDK_KEY_Shift_Lock
1566 || event->keyval == GDK_KEY_Meta_L
1567 || event->keyval == GDK_KEY_Meta_R
1568 || event->keyval == GDK_KEY_Alt_L
1569 || event->keyval == GDK_KEY_Alt_R) {
1573 /* some other key, let's restore the searchTerm (orignal text) */
1574 searchTerm = _compWindow_->searchTerm;
1575 g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1576 replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos, FALSE, NULL);
1578 /* make sure anything we typed comes in the edit box */
1579 tmp_event.type = event->type;
1580 tmp_event.window = gtk_widget_get_window(GTK_WIDGET(entry));
1581 tmp_event.send_event = TRUE;
1582 tmp_event.time = event->time;
1583 tmp_event.state = event->state;
1584 tmp_event.keyval = event->keyval;
1585 tmp_event.length = event->length;
1586 tmp_event.string = event->string;
1587 gtk_widget_event(entry, (GdkEvent *)&tmp_event);
1589 /* and close the completion window */
1590 clear_completion_cache();
1591 addrcompl_destroy_window( _compWindow_ );
1597 * ============================================================================
1598 * Publically accessible functions.
1599 * ============================================================================
1603 * Setup completion object.
1605 void addrcompl_initialize( void ) {
1606 /* g_print( "addrcompl_initialize...\n" ); */
1607 if( ! _compWindow_ ) {
1608 _compWindow_ = addrcompl_create_window();
1611 _completionIdleID_ = 0;
1612 /* g_print( "addrcompl_initialize...done\n" ); */
1616 * Teardown completion object.
1618 void addrcompl_teardown( void ) {
1619 /* g_print( "addrcompl_teardown...\n" ); */
1620 addrcompl_free_window( _compWindow_ );
1621 _compWindow_ = NULL;
1622 if( _displayQueue_ ) {
1623 g_list_free( _displayQueue_ );
1625 _displayQueue_ = NULL;
1626 _completionIdleID_ = 0;
1627 /* g_print( "addrcompl_teardown...done\n" ); */
1631 * tree view functions
1634 static GtkListStore *addr_compl_create_store(void)
1636 return gtk_list_store_new(N_ADDR_COMPL_COLUMNS,
1644 static GtkWidget *addr_compl_list_view_create(CompletionWindow *window)
1646 GtkTreeView *list_view;
1647 GtkTreeSelection *selector;
1648 GtkTreeModel *model;
1650 model = GTK_TREE_MODEL(addr_compl_create_store());
1651 list_view = GTK_TREE_VIEW(gtk_tree_view_new_with_model(model));
1652 g_object_unref(model);
1654 gtk_tree_view_set_rules_hint(list_view, prefs_common.use_stripes_everywhere);
1655 gtk_tree_view_set_headers_visible(list_view, FALSE);
1657 selector = gtk_tree_view_get_selection(list_view);
1658 gtk_tree_selection_set_mode(selector, GTK_SELECTION_BROWSE);
1659 gtk_tree_selection_set_select_function(selector, addr_compl_selected,
1662 /* create the columns */
1663 addr_compl_create_list_view_columns(GTK_WIDGET(list_view));
1665 return GTK_WIDGET(list_view);
1668 static void addr_compl_create_list_view_columns(GtkWidget *list_view)
1670 GtkTreeViewColumn *column;
1671 GtkCellRenderer *renderer;
1673 renderer = gtk_cell_renderer_pixbuf_new();
1674 column = gtk_tree_view_column_new_with_attributes
1676 "pixbuf", ADDR_COMPL_ICON, NULL);
1677 gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);
1678 renderer = gtk_cell_renderer_text_new();
1679 column = gtk_tree_view_column_new_with_attributes
1680 ("", renderer, "text", ADDR_COMPL_ADDRESS, NULL);
1681 gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);
1684 static gboolean list_view_button_press(GtkWidget *widget, GdkEventButton *event,
1685 CompletionWindow *window)
1687 if (window && event && event->type == GDK_BUTTON_PRESS) {
1688 window->in_mouse = TRUE;
1693 static gboolean list_view_button_release(GtkWidget *widget, GdkEventButton *event,
1694 CompletionWindow *window)
1696 if (window && event && event->type == GDK_BUTTON_RELEASE) {
1697 window->in_mouse = FALSE;
1702 static gboolean addr_compl_selected(GtkTreeSelection *selector,
1703 GtkTreeModel *model,
1705 gboolean currently_selected,
1708 CompletionWindow *window = data;
1710 if (currently_selected)
1713 if (!window->in_mouse)
1716 /* XXX: select the entry and kill window later... select is called before
1717 * any other mouse events handlers including the tree view internal one;
1718 * not using a time out would result in a crash. if this doesn't work
1719 * safely, maybe we should set variables when receiving button presses
1720 * in the tree view. */
1721 if (!window->destroying) {
1722 window->destroying = TRUE;
1723 g_idle_add((GSourceFunc) addr_compl_defer_select_destruct, data);
1729 static gboolean addr_compl_defer_select_destruct(CompletionWindow *window)
1731 GtkEntry *entry = GTK_ENTRY(window->entry);
1733 completion_window_apply_selection(GTK_TREE_VIEW(window->list_view),
1736 clear_completion_cache();
1738 addrcompl_destroy_window(window);