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 (!name || !address) {
260 if (address || nick || alias || !grp_emails)
264 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);
274 if (address != NULL && *address != '\0')
275 addr_compl_add_address1(address, ae);
277 if (nick != NULL && *nick != '\0')
278 addr_compl_add_address1(nick, ae);
280 if ( alias != NULL && *alias != '\0') {
281 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 gdk_window_get_geometry( gtk_widget_get_window( cw->window ), &x, &y, &width, &height, &depth );
864 /* simple _hide breaks size requisition !? */
865 gtk_widget_hide_all( cw->window );
866 gtk_widget_show_all( cw->window );
867 gtk_widget_size_request( cw->list_view, &r );
869 /* Adjust window height to available screen space */
870 if( y + r.height > gdk_screen_height())
871 r.height = gdk_screen_height() - y;
873 gtk_widget_set_size_request(cw->window, width, r.height);
875 gdk_pointer_grab(gtk_widget_get_window(cw->window), TRUE,
876 GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK |
877 GDK_BUTTON_RELEASE_MASK,
878 NULL, NULL, GDK_CURRENT_TIME);
879 gdk_keyboard_grab(gtk_widget_get_window(cw->window), FALSE, GDK_CURRENT_TIME);
880 gtk_grab_add(cw->window);
884 static GdkPixbuf *group_pixbuf = NULL;
885 static GdkPixbuf *email_pixbuf = NULL;
888 * Add an address the completion window address list.
889 * \param cw Completion window.
890 * \param address Address to add.
892 static void addrcompl_add_entry( CompletionWindow *cw, gchar *address ) {
895 GtkTreeSelection *selection;
896 gboolean is_group = FALSE;
897 GList *grp_emails = NULL;
898 store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(cw->list_view)));
902 stock_pixbuf_gdk(cw->list_view, STOCK_PIXMAP_ADDR_TWO, &group_pixbuf);
903 g_object_ref(G_OBJECT(group_pixbuf));
906 stock_pixbuf_gdk(cw->list_view, STOCK_PIXMAP_ADDR_ONE, &email_pixbuf);
907 g_object_ref(G_OBJECT(email_pixbuf));
909 /* g_print( "\t\tAdding :%s\n", address ); */
910 if (strstr(address, " <!--___group___-->")) {
912 if (_groupAddresses_)
913 grp_emails = g_hash_table_lookup(_groupAddresses_, GINT_TO_POINTER(g_str_hash(address)));
914 *(strstr(address, " <!--___group___-->")) = '\0';
915 pixbuf = group_pixbuf;
916 } else if (strchr(address, '@') && strchr(address, '<') &&
917 strchr(address, '>')) {
918 pixbuf = email_pixbuf;
922 if (is_group && !_allowCommas_)
924 gtk_list_store_append(store, &iter);
925 gtk_list_store_set(store, &iter,
926 ADDR_COMPL_ICON, pixbuf,
927 ADDR_COMPL_ADDRESS, address,
928 ADDR_COMPL_ISGROUP, is_group,
929 ADDR_COMPL_GROUPLIST, grp_emails,
934 addrcompl_resize_window( cw );
935 gtk_grab_add( cw->window );
937 selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(cw->list_view));
938 gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store), &iter);
940 if( cw->listCount == 1 ) {
941 /* Select first row for now */
942 gtk_tree_selection_select_iter(selection, &iter);
945 else if( cw->listCount == 2 ) {
946 gtk_tree_model_iter_next(GTK_TREE_MODEL(store), &iter);
947 /* Move off first row */
948 gtk_tree_selection_select_iter(selection, &iter);
954 * Completion idle function. This function is called by the main (UI) thread
955 * during UI idle time while an address search is in progress. Items from the
956 * display queue are processed and appended to the address list.
958 * \param data Target completion window to receive email addresses.
959 * \return <i>TRUE</i> to ensure that idle event do not get ignored.
961 static gboolean addrcompl_idle( gpointer data ) {
965 /* Process all entries in display queue */
966 pthread_mutex_lock( & _completionMutex_ );
967 if( _displayQueue_ ) {
968 node = _displayQueue_;
970 address = node->data;
971 /* g_print( "address ::: %s :::\n", address ); */
972 addrcompl_add_entry( _compWindow_, address );
974 node = g_list_next( node );
976 g_list_free( _displayQueue_ );
977 _displayQueue_ = NULL;
979 pthread_mutex_unlock( & _completionMutex_ );
986 * Callback entry point. The background thread (if any) appends the address
987 * list to the display queue.
988 * \param sender Sender of query.
989 * \param queryID Query ID of search request.
990 * \param listEMail List of zero of more email objects that met search
992 * \param data Query data.
994 #ifndef USE_NEW_ADDRBOOK
995 static gint addrcompl_callback_entry(
996 gpointer sender, gint queryID, GList *listEMail, gpointer data )
1001 /* g_print( "addrcompl_callback_entry::queryID=%d\n", queryID ); */
1002 pthread_mutex_lock( & _completionMutex_ );
1003 if( queryID == _queryID_ ) {
1004 /* Append contents to end of display queue */
1007 ItemEMail *email = node->data;
1009 address = addritem_format_email( email );
1010 /* g_print( "\temail/address ::%s::\n", address ); */
1011 _displayQueue_ = g_list_append( _displayQueue_, address );
1012 node = g_list_next( node );
1015 g_list_free( listEMail );
1016 pthread_mutex_unlock( & _completionMutex_ );
1023 * Clear the display queue.
1025 static void addrcompl_clear_queue( void ) {
1026 /* Clear out display queue */
1027 pthread_mutex_lock( & _completionMutex_ );
1029 g_list_free( _displayQueue_ );
1030 _displayQueue_ = NULL;
1032 pthread_mutex_unlock( & _completionMutex_ );
1036 * Add a single address entry into the display queue.
1037 * \param address Address to append.
1039 static void addrcompl_add_queue( gchar *address ) {
1040 pthread_mutex_lock( & _completionMutex_ );
1041 _displayQueue_ = g_list_append( _displayQueue_, address );
1042 pthread_mutex_unlock( & _completionMutex_ );
1046 * Load list with entries from local completion index.
1048 static void addrcompl_load_local( void ) {
1051 for (count = 0; count < get_completion_count(); count++) {
1054 address = get_complete_address( count );
1055 /* g_print( "\taddress ::%s::\n", address ); */
1057 /* Append contents to end of display queue */
1058 addrcompl_add_queue( address );
1065 static void addrcompl_start_search( void ) {
1066 #ifndef USE_NEW_ADDRBOOK
1069 searchTerm = g_strdup( _compWindow_->searchTerm );
1071 /* Setup the search */
1072 _queryID_ = addrindex_setup_search(
1073 searchTerm, NULL, addrcompl_callback_entry );
1074 g_free( searchTerm );
1076 /* g_print( "addrcompl_start_search::queryID=%d\n", _queryID_ ); */
1078 /* Load local stuff */
1079 addrcompl_load_local();
1081 /* Sit back and wait until something happens */
1082 _completionIdleID_ =
1083 g_idle_add( (GSourceFunc) addrcompl_idle, NULL );
1084 /* g_print( "addrindex_start_search::queryID=%d\n", _queryID_ ); */
1086 #ifndef USE_NEW_ADDRBOOK
1087 addrindex_start_search( _queryID_ );
1094 * Apply the current selection in the list to the entry field. Focus is also
1095 * moved to the next widget so that Tab key works correctly.
1096 * \param list_view List to process.
1097 * \param entry Address entry field.
1098 * \param move_focus Move focus to the next widget ?
1100 static void completion_window_apply_selection(GtkTreeView *list_view,
1102 gboolean move_focus)
1104 gchar *address = NULL, *text = NULL;
1107 GtkTreeSelection *selection;
1108 GtkTreeModel *model;
1110 gboolean is_group = FALSE;
1111 cm_return_if_fail(list_view != NULL);
1112 cm_return_if_fail(entry != NULL);
1113 GList *grp_emails = NULL;
1115 selection = gtk_tree_view_get_selection(list_view);
1116 if (! gtk_tree_selection_get_selected(selection, &model, &iter))
1119 /* First remove the idler */
1120 if( _completionIdleID_ != 0 ) {
1121 g_source_remove( _completionIdleID_ );
1122 _completionIdleID_ = 0;
1125 /* Process selected item */
1126 gtk_tree_model_get(model, &iter, ADDR_COMPL_ADDRESS, &text,
1127 ADDR_COMPL_ISGROUP, &is_group,
1128 ADDR_COMPL_GROUPLIST, &grp_emails,
1131 address = get_address_from_edit(entry, &cursor_pos);
1133 replace_address_in_edit(entry, text, cursor_pos, is_group, grp_emails);
1136 /* Move focus to next widget */
1137 parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1138 if( parent && move_focus) {
1139 gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1144 * Start address completion. Should be called when creating the main window
1145 * containing address completion entries.
1146 * \param mainwindow Main window.
1148 void address_completion_start(GtkWidget *mainwindow)
1150 start_address_completion(NULL);
1152 /* register focus change hook */
1153 g_signal_connect(G_OBJECT(mainwindow), "set_focus",
1154 G_CALLBACK(address_completion_mainwindow_set_focus),
1159 * Need unique data to make unregistering signal handler possible for the auto
1162 #define COMPLETION_UNIQUE_DATA (GINT_TO_POINTER(0xfeefaa))
1165 * Register specified entry widget for address completion.
1166 * \param entry Address entry field.
1168 void address_completion_register_entry(GtkEntry *entry, gboolean allow_commas)
1170 cm_return_if_fail(entry != NULL);
1171 cm_return_if_fail(GTK_IS_ENTRY(entry));
1173 /* add hooked property */
1174 g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, entry);
1175 g_object_set_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS, GINT_TO_POINTER(allow_commas));
1177 /* add keypress event */
1178 g_signal_connect_closure
1179 (G_OBJECT(entry), "key_press_event",
1180 g_cclosure_new(G_CALLBACK(address_completion_entry_key_pressed),
1181 COMPLETION_UNIQUE_DATA,
1187 * Unregister specified entry widget from address completion operations.
1188 * \param entry Address entry field.
1190 void address_completion_unregister_entry(GtkEntry *entry)
1194 cm_return_if_fail(entry != NULL);
1195 cm_return_if_fail(GTK_IS_ENTRY(entry));
1197 entry_obj = g_object_get_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK);
1198 cm_return_if_fail(entry_obj);
1199 cm_return_if_fail(G_OBJECT(entry_obj) == G_OBJECT(entry));
1201 /* has the hooked property? */
1202 g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, NULL);
1204 /* remove the hook */
1205 g_signal_handlers_disconnect_by_func(G_OBJECT(entry),
1206 G_CALLBACK(address_completion_entry_key_pressed),
1207 COMPLETION_UNIQUE_DATA);
1211 * End address completion. Should be called when main window with address
1212 * completion entries terminates. NOTE: this function assumes that it is
1213 * called upon destruction of the window.
1214 * \param mainwindow Main window.
1216 void address_completion_end(GtkWidget *mainwindow)
1218 /* if address_completion_end() is really called on closing the window,
1219 * we don't need to unregister the set_focus_cb */
1220 end_address_completion();
1223 /* if focus changes to another entry, then clear completion cache */
1224 static void address_completion_mainwindow_set_focus(GtkWindow *window,
1229 if (widget && GTK_IS_ENTRY(widget) &&
1230 g_object_get_data(G_OBJECT(widget), ENTRY_DATA_TAB_HOOK)) {
1231 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), ENTRY_DATA_ALLOW_COMMAS));
1232 clear_completion_cache();
1237 * Listener that watches for tab or other keystroke in address entry field.
1238 * \param entry Address entry field.
1239 * \param ev Event object.
1240 * \param data User data.
1241 * \return <i>TRUE</i>.
1243 static gboolean address_completion_entry_key_pressed(GtkEntry *entry,
1247 if (ev->keyval == GDK_KEY_Tab) {
1248 addrcompl_clear_queue();
1249 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS));
1250 if( address_completion_complete_address_in_entry( entry, TRUE ) ) {
1251 /* route a void character to the default handler */
1252 /* this is a dirty hack; we're actually changing a key
1253 * reported by the system. */
1254 ev->keyval = GDK_KEY_AudibleBell_Enable;
1255 ev->state &= ~GDK_SHIFT_MASK;
1258 address_completion_create_completion_window(entry);
1260 /* Start remote queries */
1261 addrcompl_start_search();
1268 } else if (ev->keyval == GDK_KEY_Shift_L
1269 || ev->keyval == GDK_KEY_Shift_R
1270 || ev->keyval == GDK_KEY_Control_L
1271 || ev->keyval == GDK_KEY_Control_R
1272 || ev->keyval == GDK_KEY_Caps_Lock
1273 || ev->keyval == GDK_KEY_Shift_Lock
1274 || ev->keyval == GDK_KEY_Meta_L
1275 || ev->keyval == GDK_KEY_Meta_R
1276 || ev->keyval == GDK_KEY_Alt_L
1277 || ev->keyval == GDK_KEY_Alt_R) {
1278 /* these buttons should not clear the cache... */
1280 clear_completion_cache();
1285 * Initialize search term for address completion.
1286 * \param entry Address entry field.
1288 static gboolean address_completion_complete_address_in_entry(GtkEntry *entry,
1291 gint ncount, cursor_pos;
1292 gchar *searchTerm, *new = NULL;
1294 cm_return_val_if_fail(entry != NULL, FALSE);
1296 if (!gtk_widget_has_focus(GTK_WIDGET(entry))) return FALSE;
1298 /* get an address component from the cursor */
1299 searchTerm = get_address_from_edit( entry, &cursor_pos );
1300 if( ! searchTerm ) return FALSE;
1301 /* g_print( "search for :::%s:::\n", searchTerm ); */
1303 /* Clear any existing search */
1304 g_free( _compWindow_->searchTerm );
1305 _compWindow_->searchTerm = g_strdup( searchTerm );
1307 /* Perform search on local completion index */
1308 ncount = complete_address( searchTerm );
1310 new = get_next_complete_address();
1313 #if (!defined(USE_LDAP) && !defined(GENERIC_UMPC))
1314 /* Select the address if there is only one match */
1316 /* Display selected address in entry field */
1317 gchar *addr = get_complete_address(1);
1318 if (addr && !strstr(addr, " <!--___group___-->")) {
1319 replace_address_in_edit(entry, addr, cursor_pos, FALSE, NULL);
1320 /* Discard the window */
1321 clear_completion_cache();
1325 /* Make sure that drop-down appears uniform! */
1329 addrcompl_add_queue( g_strdup( searchTerm ) );
1331 g_free( searchTerm );
1337 * Create new address completion window for specified entry.
1338 * \param entry_ Entry widget to associate with window.
1340 static void address_completion_create_completion_window( GtkEntry *entry_ )
1342 gint x, y, height, width, depth;
1343 GtkWidget *scroll, *list_view;
1346 GtkWidget *entry = GTK_WIDGET(entry_);
1349 /* Create new window and list */
1350 window = gtk_window_new(GTK_WINDOW_POPUP);
1351 list_view = addr_compl_list_view_create(_compWindow_);
1353 /* Destroy any existing window */
1354 addrcompl_destroy_window( _compWindow_ );
1356 /* Create new object */
1357 _compWindow_->window = window;
1358 _compWindow_->entry = entry;
1359 _compWindow_->list_view = list_view;
1360 _compWindow_->listCount = 0;
1361 _compWindow_->in_mouse = FALSE;
1363 scroll = gtk_scrolled_window_new(NULL, NULL);
1364 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
1365 GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
1366 gtk_container_add(GTK_CONTAINER(window), scroll);
1367 gtk_container_add(GTK_CONTAINER(scroll), list_view);
1368 gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll),
1370 /* Use entry widget to create initial window */
1371 gdkwin = gtk_widget_get_window(entry),
1372 gdk_window_get_geometry(gdkwin, &x, &y, &width, &height, &depth);
1373 gdk_window_get_origin (gdkwin, &x, &y);
1375 gtk_window_move(GTK_WINDOW(window), x, y);
1377 /* Resize window to fit initial (empty) address list */
1378 gtk_widget_size_request( list_view, &r );
1379 gtk_widget_set_size_request( window, width, r.height );
1380 gtk_widget_show_all( window );
1381 gtk_widget_size_request( list_view, &r );
1383 /* Setup handlers */
1384 g_signal_connect(G_OBJECT(list_view), "button_press_event",
1385 G_CALLBACK(list_view_button_press),
1388 g_signal_connect(G_OBJECT(list_view), "button_release_event",
1389 G_CALLBACK(list_view_button_release),
1392 g_signal_connect(G_OBJECT(window),
1393 "button-press-event",
1394 G_CALLBACK(completion_window_button_press),
1396 g_signal_connect(G_OBJECT(window),
1398 G_CALLBACK(completion_window_key_press),
1400 gdk_pointer_grab(gtk_widget_get_window(window), TRUE,
1401 GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK |
1402 GDK_BUTTON_RELEASE_MASK,
1403 NULL, NULL, GDK_CURRENT_TIME);
1404 gdk_keyboard_grab(gtk_widget_get_window(window), FALSE, GDK_CURRENT_TIME);
1405 gtk_grab_add( window );
1409 * Respond to button press in completion window. Check if mouse click is
1410 * anywhere outside the completion window. In that case the completion
1411 * window is destroyed, and the original searchTerm is restored.
1413 * \param widget Window object.
1414 * \param event Event.
1415 * \param compWin Reference to completion window.
1417 static gboolean completion_window_button_press(GtkWidget *widget,
1418 GdkEventButton *event,
1419 CompletionWindow *compWin )
1421 GtkWidget *event_widget, *entry;
1424 gboolean restore = TRUE;
1426 cm_return_val_if_fail(compWin != NULL, FALSE);
1428 entry = compWin->entry;
1429 cm_return_val_if_fail(entry != NULL, FALSE);
1431 /* Test where mouse was clicked */
1432 event_widget = gtk_get_event_widget((GdkEvent *)event);
1433 if (event_widget != widget) {
1434 while (event_widget) {
1435 if (event_widget == widget)
1437 else if (event_widget == entry) {
1441 event_widget = gtk_widget_get_parent(event_widget);
1446 /* Clicked outside of completion window - restore */
1447 searchTerm = _compWindow_->searchTerm;
1448 g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1449 replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos, FALSE, NULL);
1452 clear_completion_cache();
1453 addrcompl_destroy_window( _compWindow_ );
1459 * Respond to key press in completion window.
1460 * \param widget Window object.
1461 * \param event Event.
1462 * \param compWind Reference to completion window.
1464 static gboolean completion_window_key_press(GtkWidget *widget,
1466 CompletionWindow *compWin )
1468 GdkEventKey tmp_event;
1472 GtkWidget *list_view;
1474 cm_return_val_if_fail(compWin != NULL, FALSE);
1476 entry = compWin->entry;
1477 list_view = compWin->list_view;
1478 cm_return_val_if_fail(entry != NULL, FALSE);
1480 /* allow keyboard navigation in the alternatives tree view */
1481 if (event->keyval == GDK_KEY_Up || event->keyval == GDK_KEY_Down ||
1482 event->keyval == GDK_KEY_Page_Up || event->keyval == GDK_KEY_Page_Down) {
1483 completion_window_advance_selection
1484 (GTK_TREE_VIEW(list_view),
1485 event->keyval == GDK_KEY_Down ||
1486 event->keyval == GDK_KEY_Page_Down ? TRUE : FALSE);
1490 /* make tab move to next field */
1491 if( event->keyval == GDK_KEY_Tab ) {
1492 /* Reference to parent */
1493 parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1495 /* Discard the window */
1496 clear_completion_cache();
1497 addrcompl_destroy_window( _compWindow_ );
1499 /* Move focus to next widget */
1501 gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1506 /* make backtab move to previous field */
1507 if( event->keyval == GDK_KEY_ISO_Left_Tab ) {
1508 /* Reference to parent */
1509 parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1511 /* Discard the window */
1512 clear_completion_cache();
1513 addrcompl_destroy_window( _compWindow_ );
1515 /* Move focus to previous widget */
1517 gtk_widget_child_focus( parent, GTK_DIR_TAB_BACKWARD );
1521 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS));
1523 /* look for presses that accept the selection */
1524 if (event->keyval == GDK_KEY_Return || event->keyval == GDK_KEY_space ||
1525 event->keyval == GDK_KEY_KP_Enter ||
1526 (_allowCommas_ && event->keyval == GDK_KEY_comma)) {
1527 /* User selected address with a key press */
1529 /* Display selected address in entry field */
1530 completion_window_apply_selection(
1531 GTK_TREE_VIEW(list_view), GTK_ENTRY(entry),
1532 event->keyval != GDK_KEY_comma);
1534 if (event->keyval == GDK_KEY_comma) {
1535 gint pos = gtk_editable_get_position(GTK_EDITABLE(entry));
1536 gtk_editable_insert_text(GTK_EDITABLE(entry), ", ", 2, &pos);
1537 gtk_editable_set_position(GTK_EDITABLE(entry), pos + 1);
1540 /* Discard the window */
1541 clear_completion_cache();
1542 addrcompl_destroy_window( _compWindow_ );
1546 /* key state keys should never be handled */
1547 if (event->keyval == GDK_KEY_Shift_L
1548 || event->keyval == GDK_KEY_Shift_R
1549 || event->keyval == GDK_KEY_Control_L
1550 || event->keyval == GDK_KEY_Control_R
1551 || event->keyval == GDK_KEY_Caps_Lock
1552 || event->keyval == GDK_KEY_Shift_Lock
1553 || event->keyval == GDK_KEY_Meta_L
1554 || event->keyval == GDK_KEY_Meta_R
1555 || event->keyval == GDK_KEY_Alt_L
1556 || event->keyval == GDK_KEY_Alt_R) {
1560 /* some other key, let's restore the searchTerm (orignal text) */
1561 searchTerm = _compWindow_->searchTerm;
1562 g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1563 replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos, FALSE, NULL);
1565 /* make sure anything we typed comes in the edit box */
1566 tmp_event.type = event->type;
1567 tmp_event.window = gtk_widget_get_window(GTK_WIDGET(entry));
1568 tmp_event.send_event = TRUE;
1569 tmp_event.time = event->time;
1570 tmp_event.state = event->state;
1571 tmp_event.keyval = event->keyval;
1572 tmp_event.length = event->length;
1573 tmp_event.string = event->string;
1574 gtk_widget_event(entry, (GdkEvent *)&tmp_event);
1576 /* and close the completion window */
1577 clear_completion_cache();
1578 addrcompl_destroy_window( _compWindow_ );
1584 * ============================================================================
1585 * Publically accessible functions.
1586 * ============================================================================
1590 * Setup completion object.
1592 void addrcompl_initialize( void ) {
1593 /* g_print( "addrcompl_initialize...\n" ); */
1594 if( ! _compWindow_ ) {
1595 _compWindow_ = addrcompl_create_window();
1598 _completionIdleID_ = 0;
1599 /* g_print( "addrcompl_initialize...done\n" ); */
1603 * Teardown completion object.
1605 void addrcompl_teardown( void ) {
1606 /* g_print( "addrcompl_teardown...\n" ); */
1607 addrcompl_free_window( _compWindow_ );
1608 _compWindow_ = NULL;
1609 if( _displayQueue_ ) {
1610 g_list_free( _displayQueue_ );
1612 _displayQueue_ = NULL;
1613 _completionIdleID_ = 0;
1614 /* g_print( "addrcompl_teardown...done\n" ); */
1618 * tree view functions
1621 static GtkListStore *addr_compl_create_store(void)
1623 return gtk_list_store_new(N_ADDR_COMPL_COLUMNS,
1631 static GtkWidget *addr_compl_list_view_create(CompletionWindow *window)
1633 GtkTreeView *list_view;
1634 GtkTreeSelection *selector;
1635 GtkTreeModel *model;
1637 model = GTK_TREE_MODEL(addr_compl_create_store());
1638 list_view = GTK_TREE_VIEW(gtk_tree_view_new_with_model(model));
1639 g_object_unref(model);
1641 gtk_tree_view_set_rules_hint(list_view, prefs_common.use_stripes_everywhere);
1642 gtk_tree_view_set_headers_visible(list_view, FALSE);
1644 selector = gtk_tree_view_get_selection(list_view);
1645 gtk_tree_selection_set_mode(selector, GTK_SELECTION_BROWSE);
1646 gtk_tree_selection_set_select_function(selector, addr_compl_selected,
1649 /* create the columns */
1650 addr_compl_create_list_view_columns(GTK_WIDGET(list_view));
1652 return GTK_WIDGET(list_view);
1655 static void addr_compl_create_list_view_columns(GtkWidget *list_view)
1657 GtkTreeViewColumn *column;
1658 GtkCellRenderer *renderer;
1660 renderer = gtk_cell_renderer_pixbuf_new();
1661 column = gtk_tree_view_column_new_with_attributes
1663 "pixbuf", ADDR_COMPL_ICON, NULL);
1664 gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);
1665 renderer = gtk_cell_renderer_text_new();
1666 column = gtk_tree_view_column_new_with_attributes
1667 ("", renderer, "text", ADDR_COMPL_ADDRESS, NULL);
1668 gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);
1671 static gboolean list_view_button_press(GtkWidget *widget, GdkEventButton *event,
1672 CompletionWindow *window)
1674 if (window && event && event->type == GDK_BUTTON_PRESS) {
1675 window->in_mouse = TRUE;
1680 static gboolean list_view_button_release(GtkWidget *widget, GdkEventButton *event,
1681 CompletionWindow *window)
1683 if (window && event && event->type == GDK_BUTTON_RELEASE) {
1684 window->in_mouse = FALSE;
1689 static gboolean addr_compl_selected(GtkTreeSelection *selector,
1690 GtkTreeModel *model,
1692 gboolean currently_selected,
1695 CompletionWindow *window = data;
1697 if (currently_selected)
1700 if (!window->in_mouse)
1703 /* XXX: select the entry and kill window later... select is called before
1704 * any other mouse events handlers including the tree view internal one;
1705 * not using a time out would result in a crash. if this doesn't work
1706 * safely, maybe we should set variables when receiving button presses
1707 * in the tree view. */
1708 if (!window->destroying) {
1709 window->destroying = TRUE;
1710 g_idle_add((GSourceFunc) addr_compl_defer_select_destruct, data);
1716 static gboolean addr_compl_defer_select_destruct(CompletionWindow *window)
1718 GtkEntry *entry = GTK_ENTRY(window->entry);
1720 completion_window_apply_selection(GTK_TREE_VIEW(window->list_view),
1723 clear_completion_cache();
1725 addrcompl_destroy_window(window);