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/>.
27 #include <glib/gi18n.h>
28 #include <gdk/gdkkeysyms.h>
33 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
38 #include "addr_compl.h"
41 #include "prefs_common.h"
47 #ifndef USE_NEW_ADDRBOOK
48 #include "addrindex.h"
50 #include "addressbook-dbus.h"
54 *\brief For the GtkListStore
67 * The address book is read into memory. We set up an address list
68 * containing all address book entries. Next we make the completion
69 * list, which contains all the completable strings, and store a
70 * reference to the address entry it belongs to.
71 * After calling the g_completion_complete(), we get a reference
72 * to a valid email address.
74 * Completion is very simplified. We never complete on another prefix,
75 * i.e. we neglect the next smallest possible prefix for the current
76 * completion cache. This is simply done so we might break up the
77 * addresses a little more (e.g. break up alfons@proteus.demon.nl into
78 * something like alfons, proteus, demon, nl; and then completing on
79 * any of those words).
83 * completion_entry - structure used to complete addresses, with a reference
84 * the the real address information.
88 gchar *string; /* string to complete */
89 address_entry *ref; /* address the string belongs to */
92 /*******************************************************************************/
94 static gint g_ref_count; /* list ref count */
95 static GList *g_completion_list = NULL; /* list of strings to be checked */
96 static GList *g_address_list = NULL; /* address storage */
97 static GCompletion *g_completion; /* completion object */
99 static GHashTable *_groupAddresses_ = NULL;
100 static gboolean _allowCommas_ = TRUE;
102 /* To allow for continuing completion we have to keep track of the state
103 * using the following variables. No need to create a context object. */
105 static gint g_completion_count; /* nr of addresses incl. the prefix */
106 static gint g_completion_next; /* next prev address */
107 static GSList *g_completion_addresses; /* unique addresses found in the
109 static gchar *g_completion_prefix; /* last prefix. (this is cached here
110 * because the prefix passed to g_completion
111 * is g_utf8_strdown()'ed */
113 static gchar *completion_folder_path = NULL;
115 /*******************************************************************************/
118 * Define the structure of the completion window.
120 typedef struct _CompletionWindow CompletionWindow;
121 struct _CompletionWindow {
126 GtkWidget *list_view;
128 gboolean in_mouse; /*!< mouse press pending... */
129 gboolean destroying; /*!< destruction in progress */
132 static GtkListStore *addr_compl_create_store (void);
134 static GtkWidget *addr_compl_list_view_create (CompletionWindow *window);
136 static void addr_compl_create_list_view_columns (GtkWidget *list_view);
138 static gboolean list_view_button_press (GtkWidget *widget,
139 GdkEventButton *event,
140 CompletionWindow *window);
142 static gboolean list_view_button_release (GtkWidget *widget,
143 GdkEventButton *event,
144 CompletionWindow *window);
146 static gboolean addr_compl_selected (GtkTreeSelection *selector,
149 gboolean currently_selected,
152 static gboolean addr_compl_defer_select_destruct(CompletionWindow *window);
155 * Function used by GTK to find the string data to be used for completion.
156 * \param data Pointer to data being processed.
158 static gchar *completion_func(gpointer data)
160 cm_return_val_if_fail(data != NULL, NULL);
162 return ((completion_entry *)data)->string;
166 * Initialize all completion index data.
168 static void init_all(void)
170 g_completion = g_completion_new(completion_func);
171 cm_return_if_fail(g_completion != NULL);
174 static void free_all_addresses(void)
179 walk = g_address_list;
180 for (; walk != NULL; walk = g_list_next(walk)) {
181 address_entry *ae = (address_entry *) walk->data;
184 g_list_free(ae->grp_emails);
187 g_list_free(g_address_list);
188 g_address_list = NULL;
189 if (_groupAddresses_)
190 g_hash_table_destroy(_groupAddresses_);
191 _groupAddresses_ = NULL;
194 static void clear_completion_cache(void);
195 static void free_completion_list(void)
198 if (!g_completion_list)
201 clear_completion_cache();
203 g_completion_clear_items(g_completion);
205 walk = g_list_first(g_completion_list);
206 for (; walk != NULL; walk = g_list_next(walk)) {
207 completion_entry *ce = (completion_entry *) walk->data;
211 g_list_free(g_completion_list);
212 g_completion_list = NULL;
215 * Free up all completion index data.
217 static void free_all(void)
219 free_completion_list();
220 free_all_addresses();
221 g_completion_free(g_completion);
226 * Append specified address entry to the index.
227 * \param str Index string value.
228 * \param ae Entry containing address data.
230 void addr_compl_add_address1(const char *str, address_entry *ae)
232 completion_entry *ce1;
233 ce1 = g_new0(completion_entry, 1),
234 /* GCompletion list is case sensitive */
235 ce1->string = g_utf8_strdown(str, -1);
238 g_completion_list = g_list_prepend(g_completion_list, ce1);
242 * Adds address to the completion list. This function looks complicated, but
243 * it's only allocation checks. Each value will be included in the index.
244 * \param name Recipient name.
245 * \param address EMail address.
246 * \param alias Alias to append.
247 * \param grp_emails the emails in case of a group. List should be freed later,
248 * but not its strings
249 * \return <code>0</code> if entry appended successfully, or <code>-1</code>
252 static gint add_address(const gchar *name, const gchar *address,
253 const gchar *nick, const gchar *alias, GList *grp_emails)
256 gboolean is_group = FALSE;
258 if (!name || !address) {
259 if (!address && !nick && !alias && grp_emails) {
265 ae = g_new0(address_entry, 1);
267 cm_return_val_if_fail(ae != NULL, -1);
269 ae->name = g_strdup(name);
270 ae->address = g_strdup(address);
271 ae->grp_emails = grp_emails;
272 g_address_list = g_list_prepend(g_address_list, ae);
274 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);
289 * Read address book, creating all entries in the completion index.
291 static void read_address_book(gchar *folderpath) {
292 free_all_addresses();
293 free_completion_list();
295 #ifndef USE_NEW_ADDRBOOK
296 addrindex_load_completion( add_address, folderpath );
298 GError* error = NULL;
300 addrcompl_initialize();
301 if (! addrindex_dbus_load_completion(add_address, &error)) {
302 g_warning("Failed to populate address completion list");
307 /* plugins may hook in here to modify/extend the completion list */
308 hooks_invoke(ADDDRESS_COMPLETION_BUILD_ADDRESS_LIST_HOOKLIST, &g_address_list);
310 g_address_list = g_list_reverse(g_address_list);
311 g_completion_list = g_list_reverse(g_completion_list);
312 /* merge the completion entry list into g_completion */
313 if (g_completion_list) {
314 g_completion_add_items(g_completion, g_completion_list);
315 if (debug_get_mode())
316 debug_print("read %d items in %s\n",
317 g_list_length(g_completion_list),
318 folderpath?folderpath:"(null)");
323 * Test whether there is a completion pending.
324 * \return <code>TRUE</code> if pending.
326 static gboolean is_completion_pending(void)
328 /* check if completion pending, i.e. we might satisfy a request for the next
329 * or previous address */
330 return g_completion_count;
334 * Clear the completion cache.
336 static void clear_completion_cache(void)
338 if (is_completion_pending()) {
339 g_free(g_completion_prefix);
341 if (g_completion_addresses) {
342 g_slist_free(g_completion_addresses);
343 g_completion_addresses = NULL;
346 g_completion_count = g_completion_next = 0;
351 * Prepare completion index. This function should be called prior to attempting
352 * address completion.
353 * \return The number of addresses in the completion list.
355 gint start_address_completion(gchar *folderpath)
357 gboolean different_book = FALSE;
358 clear_completion_cache();
360 if (strcmp2(completion_folder_path,folderpath))
361 different_book = TRUE;
363 g_free(completion_folder_path);
364 if (folderpath != NULL)
365 completion_folder_path = g_strdup(folderpath);
367 completion_folder_path = NULL;
371 /* open the address book */
372 read_address_book(folderpath);
373 } else if (different_book)
374 read_address_book(folderpath);
377 debug_print("start_address_completion(%s) ref count %d\n",
378 folderpath?folderpath:"(null)", g_ref_count);
380 return g_list_length(g_completion_list);
384 * Retrieve a possible address (or a part) from an entry box. To make life
385 * easier, we only look at the last valid address component; address
386 * completion only works at the last string component in the entry box.
388 * \param entry Address entry field.
389 * \param start_pos Address of start position of address.
390 * \return Possible address.
392 static gchar *get_address_from_edit(GtkEntry *entry, gint *start_pos)
394 const gchar *edit_text, *p;
396 gboolean in_quote = FALSE;
397 gboolean in_bracket = FALSE;
400 edit_text = gtk_entry_get_text(entry);
401 if (edit_text == NULL) return NULL;
403 cur_pos = gtk_editable_get_position(GTK_EDITABLE(entry));
405 /* scan for a separator. doesn't matter if walk points at null byte. */
406 for (p = g_utf8_offset_to_pointer(edit_text, cur_pos);
408 p = g_utf8_prev_char(p)) {
411 } else if (!in_quote) {
412 if (!in_bracket && *p == ',') {
414 } else if (*p == '<')
421 /* have something valid */
422 if (g_utf8_strlen(p, -1) == 0)
425 #define IS_VALID_CHAR(x) \
426 (g_ascii_isalnum(x) || (x) == '"' || (x) == '<' || (((unsigned char)(x)) > 0x7f))
428 /* now scan back until we hit a valid character */
429 for (; *p && !IS_VALID_CHAR(*p); p = g_utf8_next_char(p))
434 if (g_utf8_strlen(p, -1) == 0)
437 if (start_pos) *start_pos = g_utf8_pointer_to_offset(edit_text, p);
444 static gchar *get_complete_address_from_name_email(const gchar *name, const gchar *email)
446 gchar *address = NULL;
447 if (!name || name[0] == '\0')
448 address = g_strdup_printf("<%s>", email);
449 else if (strchr_with_skip_quote(name, '"', ','))
450 address = g_strdup_printf
451 ("\"%s\" <%s>", name, email);
453 address = g_strdup_printf
454 ("%s <%s>", name, email);
459 * Replace an incompleted address with a completed one.
460 * \param entry Address entry field.
461 * \param newtext New text.
462 * \param start_pos Insertion point in entry field.
464 static void replace_address_in_edit(GtkEntry *entry, const gchar *newtext,
465 gint start_pos, gboolean is_group, GList *grp_emails)
467 if (!newtext) return;
468 gtk_editable_delete_text(GTK_EDITABLE(entry), start_pos, -1);
470 gtk_editable_insert_text(GTK_EDITABLE(entry), newtext, strlen(newtext),
473 gchar *addresses = NULL;
474 GList *cur = grp_emails;
475 for (; cur; cur = cur->next) {
477 ItemEMail *email = (ItemEMail *)cur->data;
478 ItemPerson *person = ( ItemPerson * ) ADDRITEM_PARENT(email);
480 gchar *addr = get_complete_address_from_name_email(
481 ADDRITEM_NAME(person), email->address);
483 tmp = g_strdup_printf("%s, %s", addresses, addr);
485 tmp = g_strdup_printf("%s", addr);
490 gtk_editable_insert_text(GTK_EDITABLE(entry), addresses, strlen(addresses),
494 gtk_editable_set_position(GTK_EDITABLE(entry), -1);
498 * Attempt to complete an address, and returns the number of addresses found.
499 * Use <code>get_complete_address()</code> to get an entry from the index.
501 * \param str Search string to find.
502 * \return Zero if no match was found, otherwise the number of addresses; the
503 * original prefix (search string) will appear at index 0.
505 guint complete_address(const gchar *str)
507 GList *result = NULL;
511 completion_entry *ce = NULL;
513 cm_return_val_if_fail(str != NULL, 0);
515 /* g_completion is case sensitive */
516 d = g_utf8_strdown(str, -1);
518 clear_completion_cache();
519 g_completion_prefix = g_strdup(str);
521 result = g_completion_complete(g_completion, d, NULL);
523 count = g_list_length(result);
525 /* create list with unique addresses */
526 for (cpl = 0, result = g_list_first(result);
528 result = g_list_next(result)) {
529 ce = (completion_entry *)(result->data);
530 if (NULL == g_slist_find(g_completion_addresses,
533 g_completion_addresses =
534 g_slist_append(g_completion_addresses,
538 count = cpl + 1; /* index 0 is the original prefix */
539 g_completion_next = 1; /* we start at the first completed one */
541 g_free(g_completion_prefix);
542 g_completion_prefix = NULL;
545 g_completion_count = count;
553 * complete_matches_found() returns the number of matched addresses according
554 * to the completion mechanism. Unlike complete_address(), the returned value
555 * doesn't count str itself. If there's no match, it returns 0.
556 * To get a list of completion matches, see complete_address() instead.
558 guint complete_matches_found(const gchar *str)
560 GList *result = NULL;
563 cm_return_val_if_fail(str != NULL, 0);
565 /* g_completion is case sensitive */
566 d = g_utf8_strdown(str, -1);
568 clear_completion_cache();
569 g_completion_prefix = g_strdup(str);
571 result = g_completion_complete(g_completion, d, NULL);
573 g_free(g_completion_prefix);
576 return g_list_length(result);
580 * Return a complete address from the index.
581 * \param index Index of entry that was found (by the previous call to
582 * <code>complete_address()</code>
583 * \return Completed address string; this should be freed when done.
585 gchar *get_complete_address(gint index)
587 const address_entry *p;
588 gchar *address = NULL;
590 if (index < g_completion_count) {
592 address = g_strdup(g_completion_prefix);
594 /* get something from the unique addresses */
595 p = (address_entry *)g_slist_nth_data
596 (g_completion_addresses, index - 1);
597 if (p != NULL && p->address != NULL) {
598 address = get_complete_address_from_name_email(p->name, p->address);
599 } else if (p != NULL && p->address == NULL && p->name != NULL) {
601 address = g_strdup_printf("%s (%s) <!--___group___-->", p->name, _("Group"));
602 if (!_groupAddresses_) {
603 _groupAddresses_ = g_hash_table_new(NULL, g_direct_equal);
605 if (!g_hash_table_lookup(_groupAddresses_, GINT_TO_POINTER(g_str_hash(address)))) {
606 g_hash_table_insert(_groupAddresses_, GINT_TO_POINTER(g_str_hash(address)), p->grp_emails);
617 * Return the next complete address match from the completion index.
618 * \return Completed address string; this should be freed when done.
620 static gchar *get_next_complete_address(void)
622 if (is_completion_pending()) {
625 res = get_complete_address(g_completion_next);
626 g_completion_next += 1;
627 if (g_completion_next >= g_completion_count)
628 g_completion_next = 0;
636 * Return a count of the completed matches in the completion index.
637 * \return Number of matched entries.
639 static guint get_completion_count(void)
641 if (is_completion_pending())
642 return g_completion_count;
648 * Invalidate address completion index. This function should be called whenever
649 * the address book changes. This forces data to be read into the completion
651 * \return Number of entries in index.
653 gint invalidate_address_completion(void)
656 /* simply the same as start_address_completion() */
657 debug_print("Invalidation request for address completion\n");
658 read_address_book(completion_folder_path);
659 clear_completion_cache();
662 return g_list_length(g_completion_list);
666 * Finished with completion index. This function should be called after
667 * matching addresses.
668 * \return Reference count.
670 gint end_address_completion(void)
672 gboolean different_folder = FALSE;
673 clear_completion_cache();
675 /* reset the folderpath to NULL */
676 if (completion_folder_path) {
677 g_free(completion_folder_path);
678 completion_folder_path = NULL;
679 different_folder = TRUE;
681 if (0 == --g_ref_count)
684 debug_print("end_address_completion ref count %d\n", g_ref_count);
685 if (g_ref_count && different_folder) {
686 debug_print("still ref'd, different folder\n");
687 invalidate_address_completion();
696 static CompletionWindow *_compWindow_ = NULL;
699 * Mutex to protect callback from multiple threads.
701 static pthread_mutex_t _completionMutex_ = PTHREAD_MUTEX_INITIALIZER;
704 * Completion queue list.
706 static GList *_displayQueue_ = NULL;
710 static gint _queryID_ = 0;
713 * Completion idle ID.
715 static guint _completionIdleID_ = 0;
718 * address completion entry ui. the ui (completion list was inspired by galeon's
719 * auto completion list). remaining things powered by claws's completion engine.
722 #define ENTRY_DATA_TAB_HOOK "tab_hook" /* used to lookup entry */
723 #define ENTRY_DATA_ALLOW_COMMAS "allowcommas" /* used to know whether to present groups */
725 static void address_completion_mainwindow_set_focus (GtkWindow *window,
728 static gboolean address_completion_entry_key_pressed (GtkEntry *entry,
731 static gboolean address_completion_complete_address_in_entry
734 static void address_completion_create_completion_window (GtkEntry *entry);
736 static gboolean completion_window_button_press
738 GdkEventButton *event,
739 CompletionWindow *compWin );
741 static gboolean completion_window_key_press
744 CompletionWindow *compWin );
745 static void address_completion_create_completion_window( GtkEntry *entry_ );
748 * Create a completion window object.
749 * \return Initialized completion window.
751 static CompletionWindow *addrcompl_create_window( void ) {
752 CompletionWindow *cw;
754 cw = g_new0( CompletionWindow, 1 );
756 cw->searchTerm = NULL;
759 cw->list_view = NULL;
760 cw->in_mouse = FALSE;
761 cw->destroying = FALSE;
767 * Destroy completion window.
768 * \param cw Window to destroy.
770 static void addrcompl_destroy_window( CompletionWindow *cw ) {
771 /* Stop all searches currently in progress */
772 #ifndef USE_NEW_ADDRBOOK
773 addrindex_stop_search( _queryID_ );
775 /* Remove idler function... or application may not terminate */
776 if( _completionIdleID_ != 0 ) {
777 g_source_remove( _completionIdleID_ );
778 _completionIdleID_ = 0;
781 /* Now destroy window */
783 /* Clear references to widgets */
785 cw->list_view = NULL;
789 gtk_widget_hide( cw->window );
790 gtk_widget_destroy( cw->window );
793 cw->destroying = FALSE;
794 cw->in_mouse = FALSE;
800 * Free up completion window.
801 * \param cw Window to free.
803 static void addrcompl_free_window( CompletionWindow *cw ) {
805 addrcompl_destroy_window( cw );
807 g_free( cw->searchTerm );
808 cw->searchTerm = NULL;
810 /* Clear references */
819 * Advance selection to previous/next item in list.
820 * \param list_view List to process.
821 * \param forward Set to <i>TRUE</i> to select next or <i>FALSE</i> for
824 static void completion_window_advance_selection(GtkTreeView *list_view, gboolean forward)
826 GtkTreeSelection *selection;
830 cm_return_if_fail(list_view != NULL);
832 selection = gtk_tree_view_get_selection(list_view);
833 if (!gtk_tree_selection_get_selected(selection, &model, &iter))
837 forward = gtk_tree_model_iter_next(model, &iter);
839 gtk_tree_selection_select_iter(selection, &iter);
843 prev = gtk_tree_model_get_path(model, &iter);
847 if (gtk_tree_path_prev(prev))
848 gtk_tree_selection_select_path(selection, prev);
850 gtk_tree_path_free(prev);
855 * Resize window to accommodate maximum number of address entries.
856 * \param cw Completion window.
858 static void addrcompl_resize_window( CompletionWindow *cw ) {
860 gint x, y, width, height, depth;
862 /* Get current geometry of window */
863 gdk_window_get_geometry( gtk_widget_get_window( cw->window ), &x, &y, &width, &height, &depth );
865 /* simple _hide breaks size requisition !? */
866 gtk_widget_hide_all( cw->window );
867 gtk_widget_show_all( cw->window );
868 gtk_widget_size_request( cw->list_view, &r );
870 /* Adjust window height to available screen space */
871 if( y + r.height > gdk_screen_height())
872 r.height = gdk_screen_height() - y;
874 gtk_widget_set_size_request(cw->window, width, r.height);
876 gdk_pointer_grab(gtk_widget_get_window(cw->window), TRUE,
877 GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK |
878 GDK_BUTTON_RELEASE_MASK,
879 NULL, NULL, GDK_CURRENT_TIME);
880 gdk_keyboard_grab(gtk_widget_get_window(cw->window), FALSE, GDK_CURRENT_TIME);
881 gtk_grab_add(cw->window);
885 static GdkPixbuf *group_pixbuf = NULL;
886 static GdkPixbuf *email_pixbuf = NULL;
889 * Add an address the completion window address list.
890 * \param cw Completion window.
891 * \param address Address to add.
893 static void addrcompl_add_entry( CompletionWindow *cw, gchar *address ) {
896 GtkTreeSelection *selection;
897 gboolean is_group = FALSE;
898 GList *grp_emails = NULL;
899 store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(cw->list_view)));
903 stock_pixbuf_gdk(cw->list_view, STOCK_PIXMAP_ADDR_TWO, &group_pixbuf);
904 g_object_ref(G_OBJECT(group_pixbuf));
907 stock_pixbuf_gdk(cw->list_view, STOCK_PIXMAP_ADDR_ONE, &email_pixbuf);
908 g_object_ref(G_OBJECT(email_pixbuf));
910 /* g_print( "\t\tAdding :%s\n", address ); */
911 if (strstr(address, " <!--___group___-->")) {
913 if (_groupAddresses_)
914 grp_emails = g_hash_table_lookup(_groupAddresses_, GINT_TO_POINTER(g_str_hash(address)));
915 *(strstr(address, " <!--___group___-->")) = '\0';
916 pixbuf = group_pixbuf;
917 } else if (strchr(address, '@') && strchr(address, '<') &&
918 strchr(address, '>')) {
919 pixbuf = email_pixbuf;
923 if (is_group && !_allowCommas_)
925 gtk_list_store_append(store, &iter);
926 gtk_list_store_set(store, &iter,
927 ADDR_COMPL_ICON, pixbuf,
928 ADDR_COMPL_ADDRESS, address,
929 ADDR_COMPL_ISGROUP, is_group,
930 ADDR_COMPL_GROUPLIST, grp_emails,
935 addrcompl_resize_window( cw );
936 gtk_grab_add( cw->window );
938 selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(cw->list_view));
939 gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store), &iter);
941 if( cw->listCount == 1 ) {
942 /* Select first row for now */
943 gtk_tree_selection_select_iter(selection, &iter);
946 else if( cw->listCount == 2 ) {
947 gtk_tree_model_iter_next(GTK_TREE_MODEL(store), &iter);
948 /* Move off first row */
949 gtk_tree_selection_select_iter(selection, &iter);
955 * Completion idle function. This function is called by the main (UI) thread
956 * during UI idle time while an address search is in progress. Items from the
957 * display queue are processed and appended to the address list.
959 * \param data Target completion window to receive email addresses.
960 * \return <i>TRUE</i> to ensure that idle event do not get ignored.
962 static gboolean addrcompl_idle( gpointer data ) {
966 /* Process all entries in display queue */
967 pthread_mutex_lock( & _completionMutex_ );
968 if( _displayQueue_ ) {
969 node = _displayQueue_;
971 address = node->data;
972 /* g_print( "address ::: %s :::\n", address ); */
973 addrcompl_add_entry( _compWindow_, address );
975 node = g_list_next( node );
977 g_list_free( _displayQueue_ );
978 _displayQueue_ = NULL;
980 pthread_mutex_unlock( & _completionMutex_ );
987 * Callback entry point. The background thread (if any) appends the address
988 * list to the display queue.
989 * \param sender Sender of query.
990 * \param queryID Query ID of search request.
991 * \param listEMail List of zero of more email objects that met search
993 * \param data Query data.
995 #ifndef USE_NEW_ADDRBOOK
996 static gint addrcompl_callback_entry(
997 gpointer sender, gint queryID, GList *listEMail, gpointer data )
1002 /* g_print( "addrcompl_callback_entry::queryID=%d\n", queryID ); */
1003 pthread_mutex_lock( & _completionMutex_ );
1004 if( queryID == _queryID_ ) {
1005 /* Append contents to end of display queue */
1008 ItemEMail *email = node->data;
1010 address = addritem_format_email( email );
1011 /* g_print( "\temail/address ::%s::\n", address ); */
1012 _displayQueue_ = g_list_append( _displayQueue_, address );
1013 node = g_list_next( node );
1016 g_list_free( listEMail );
1017 pthread_mutex_unlock( & _completionMutex_ );
1024 * Clear the display queue.
1026 static void addrcompl_clear_queue( void ) {
1027 /* Clear out display queue */
1028 pthread_mutex_lock( & _completionMutex_ );
1030 g_list_free( _displayQueue_ );
1031 _displayQueue_ = NULL;
1033 pthread_mutex_unlock( & _completionMutex_ );
1037 * Add a single address entry into the display queue.
1038 * \param address Address to append.
1040 static void addrcompl_add_queue( gchar *address ) {
1041 pthread_mutex_lock( & _completionMutex_ );
1042 _displayQueue_ = g_list_append( _displayQueue_, address );
1043 pthread_mutex_unlock( & _completionMutex_ );
1047 * Load list with entries from local completion index.
1049 static void addrcompl_load_local( void ) {
1052 for (count = 0; count < get_completion_count(); count++) {
1055 address = get_complete_address( count );
1056 /* g_print( "\taddress ::%s::\n", address ); */
1058 /* Append contents to end of display queue */
1059 addrcompl_add_queue( address );
1066 static void addrcompl_start_search( void ) {
1067 #ifndef USE_NEW_ADDRBOOK
1070 searchTerm = g_strdup( _compWindow_->searchTerm );
1072 /* Setup the search */
1073 _queryID_ = addrindex_setup_search(
1074 searchTerm, NULL, addrcompl_callback_entry );
1075 g_free( searchTerm );
1077 /* g_print( "addrcompl_start_search::queryID=%d\n", _queryID_ ); */
1079 /* Load local stuff */
1080 addrcompl_load_local();
1082 /* Sit back and wait until something happens */
1083 _completionIdleID_ =
1084 g_idle_add( (GSourceFunc) addrcompl_idle, NULL );
1085 /* g_print( "addrindex_start_search::queryID=%d\n", _queryID_ ); */
1087 #ifndef USE_NEW_ADDRBOOK
1088 addrindex_start_search( _queryID_ );
1095 * Apply the current selection in the list to the entry field. Focus is also
1096 * moved to the next widget so that Tab key works correctly.
1097 * \param list_view List to process.
1098 * \param entry Address entry field.
1099 * \param move_focus Move focus to the next widget ?
1101 static void completion_window_apply_selection(GtkTreeView *list_view,
1103 gboolean move_focus)
1105 gchar *address = NULL, *text = NULL;
1108 GtkTreeSelection *selection;
1109 GtkTreeModel *model;
1111 gboolean is_group = FALSE;
1112 cm_return_if_fail(list_view != NULL);
1113 cm_return_if_fail(entry != NULL);
1114 GList *grp_emails = NULL;
1116 selection = gtk_tree_view_get_selection(list_view);
1117 if (! gtk_tree_selection_get_selected(selection, &model, &iter))
1120 /* First remove the idler */
1121 if( _completionIdleID_ != 0 ) {
1122 g_source_remove( _completionIdleID_ );
1123 _completionIdleID_ = 0;
1126 /* Process selected item */
1127 gtk_tree_model_get(model, &iter, ADDR_COMPL_ADDRESS, &text,
1128 ADDR_COMPL_ISGROUP, &is_group,
1129 ADDR_COMPL_GROUPLIST, &grp_emails,
1132 address = get_address_from_edit(entry, &cursor_pos);
1134 replace_address_in_edit(entry, text, cursor_pos, is_group, grp_emails);
1137 /* Move focus to next widget */
1138 parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1139 if( parent && move_focus) {
1140 gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1145 * Start address completion. Should be called when creating the main window
1146 * containing address completion entries.
1147 * \param mainwindow Main window.
1149 void address_completion_start(GtkWidget *mainwindow)
1151 start_address_completion(NULL);
1153 /* register focus change hook */
1154 g_signal_connect(G_OBJECT(mainwindow), "set_focus",
1155 G_CALLBACK(address_completion_mainwindow_set_focus),
1160 * Need unique data to make unregistering signal handler possible for the auto
1163 #define COMPLETION_UNIQUE_DATA (GINT_TO_POINTER(0xfeefaa))
1166 * Register specified entry widget for address completion.
1167 * \param entry Address entry field.
1169 void address_completion_register_entry(GtkEntry *entry, gboolean allow_commas)
1171 cm_return_if_fail(entry != NULL);
1172 cm_return_if_fail(GTK_IS_ENTRY(entry));
1174 /* add hooked property */
1175 g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, entry);
1176 g_object_set_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS, GINT_TO_POINTER(allow_commas));
1178 /* add keypress event */
1179 g_signal_connect_closure
1180 (G_OBJECT(entry), "key_press_event",
1181 g_cclosure_new(G_CALLBACK(address_completion_entry_key_pressed),
1182 COMPLETION_UNIQUE_DATA,
1188 * Unregister specified entry widget from address completion operations.
1189 * \param entry Address entry field.
1191 void address_completion_unregister_entry(GtkEntry *entry)
1195 cm_return_if_fail(entry != NULL);
1196 cm_return_if_fail(GTK_IS_ENTRY(entry));
1198 entry_obj = g_object_get_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK);
1199 cm_return_if_fail(entry_obj);
1200 cm_return_if_fail(G_OBJECT(entry_obj) == G_OBJECT(entry));
1202 /* has the hooked property? */
1203 g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, NULL);
1205 /* remove the hook */
1206 g_signal_handlers_disconnect_by_func(G_OBJECT(entry),
1207 G_CALLBACK(address_completion_entry_key_pressed),
1208 COMPLETION_UNIQUE_DATA);
1212 * End address completion. Should be called when main window with address
1213 * completion entries terminates. NOTE: this function assumes that it is
1214 * called upon destruction of the window.
1215 * \param mainwindow Main window.
1217 void address_completion_end(GtkWidget *mainwindow)
1219 /* if address_completion_end() is really called on closing the window,
1220 * we don't need to unregister the set_focus_cb */
1221 end_address_completion();
1224 /* if focus changes to another entry, then clear completion cache */
1225 static void address_completion_mainwindow_set_focus(GtkWindow *window,
1230 if (widget && GTK_IS_ENTRY(widget) &&
1231 g_object_get_data(G_OBJECT(widget), ENTRY_DATA_TAB_HOOK)) {
1232 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), ENTRY_DATA_ALLOW_COMMAS));
1233 clear_completion_cache();
1238 * Listener that watches for tab or other keystroke in address entry field.
1239 * \param entry Address entry field.
1240 * \param ev Event object.
1241 * \param data User data.
1242 * \return <i>TRUE</i>.
1244 static gboolean address_completion_entry_key_pressed(GtkEntry *entry,
1248 if (ev->keyval == GDK_KEY_Tab) {
1249 addrcompl_clear_queue();
1250 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS));
1251 if( address_completion_complete_address_in_entry( entry, TRUE ) ) {
1252 /* route a void character to the default handler */
1253 /* this is a dirty hack; we're actually changing a key
1254 * reported by the system. */
1255 ev->keyval = GDK_KEY_AudibleBell_Enable;
1256 ev->state &= ~GDK_SHIFT_MASK;
1259 address_completion_create_completion_window(entry);
1261 /* Start remote queries */
1262 addrcompl_start_search();
1269 } else if (ev->keyval == GDK_KEY_Shift_L
1270 || ev->keyval == GDK_KEY_Shift_R
1271 || ev->keyval == GDK_KEY_Control_L
1272 || ev->keyval == GDK_KEY_Control_R
1273 || ev->keyval == GDK_KEY_Caps_Lock
1274 || ev->keyval == GDK_KEY_Shift_Lock
1275 || ev->keyval == GDK_KEY_Meta_L
1276 || ev->keyval == GDK_KEY_Meta_R
1277 || ev->keyval == GDK_KEY_Alt_L
1278 || ev->keyval == GDK_KEY_Alt_R) {
1279 /* these buttons should not clear the cache... */
1281 clear_completion_cache();
1286 * Initialize search term for address completion.
1287 * \param entry Address entry field.
1289 static gboolean address_completion_complete_address_in_entry(GtkEntry *entry,
1292 gint ncount, cursor_pos;
1293 gchar *searchTerm, *new = NULL;
1295 cm_return_val_if_fail(entry != NULL, FALSE);
1297 if (!gtk_widget_has_focus(GTK_WIDGET(entry))) return FALSE;
1299 /* get an address component from the cursor */
1300 searchTerm = get_address_from_edit( entry, &cursor_pos );
1301 if( ! searchTerm ) return FALSE;
1302 /* g_print( "search for :::%s:::\n", searchTerm ); */
1304 /* Clear any existing search */
1305 g_free( _compWindow_->searchTerm );
1306 _compWindow_->searchTerm = g_strdup( searchTerm );
1308 /* Perform search on local completion index */
1309 ncount = complete_address( searchTerm );
1311 new = get_next_complete_address();
1314 #if (!defined(USE_LDAP) && !defined(GENERIC_UMPC))
1315 /* Select the address if there is only one match */
1317 /* Display selected address in entry field */
1318 gchar *addr = get_complete_address(1);
1319 if (addr && !strstr(addr, " <!--___group___-->")) {
1320 replace_address_in_edit(entry, addr, cursor_pos, FALSE, NULL);
1321 /* Discard the window */
1322 clear_completion_cache();
1326 /* Make sure that drop-down appears uniform! */
1330 addrcompl_add_queue( g_strdup( searchTerm ) );
1332 g_free( searchTerm );
1338 * Create new address completion window for specified entry.
1339 * \param entry_ Entry widget to associate with window.
1341 static void address_completion_create_completion_window( GtkEntry *entry_ )
1343 gint x, y, height, width, depth;
1344 GtkWidget *scroll, *list_view;
1347 GtkWidget *entry = GTK_WIDGET(entry_);
1350 /* Create new window and list */
1351 window = gtk_window_new(GTK_WINDOW_POPUP);
1352 list_view = addr_compl_list_view_create(_compWindow_);
1354 /* Destroy any existing window */
1355 addrcompl_destroy_window( _compWindow_ );
1357 /* Create new object */
1358 _compWindow_->window = window;
1359 _compWindow_->entry = entry;
1360 _compWindow_->list_view = list_view;
1361 _compWindow_->listCount = 0;
1362 _compWindow_->in_mouse = FALSE;
1364 scroll = gtk_scrolled_window_new(NULL, NULL);
1365 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
1366 GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
1367 gtk_container_add(GTK_CONTAINER(window), scroll);
1368 gtk_container_add(GTK_CONTAINER(scroll), list_view);
1369 gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll),
1371 /* Use entry widget to create initial window */
1372 gdkwin = gtk_widget_get_window(entry),
1373 gdk_window_get_geometry(gdkwin, &x, &y, &width, &height, &depth);
1374 gdk_window_get_origin (gdkwin, &x, &y);
1376 gtk_window_move(GTK_WINDOW(window), x, y);
1378 /* Resize window to fit initial (empty) address list */
1379 gtk_widget_size_request( list_view, &r );
1380 gtk_widget_set_size_request( window, width, r.height );
1381 gtk_widget_show_all( window );
1382 gtk_widget_size_request( list_view, &r );
1384 /* Setup handlers */
1385 g_signal_connect(G_OBJECT(list_view), "button_press_event",
1386 G_CALLBACK(list_view_button_press),
1389 g_signal_connect(G_OBJECT(list_view), "button_release_event",
1390 G_CALLBACK(list_view_button_release),
1393 g_signal_connect(G_OBJECT(window),
1394 "button-press-event",
1395 G_CALLBACK(completion_window_button_press),
1397 g_signal_connect(G_OBJECT(window),
1399 G_CALLBACK(completion_window_key_press),
1401 gdk_pointer_grab(gtk_widget_get_window(window), TRUE,
1402 GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK |
1403 GDK_BUTTON_RELEASE_MASK,
1404 NULL, NULL, GDK_CURRENT_TIME);
1405 gdk_keyboard_grab(gtk_widget_get_window(window), FALSE, GDK_CURRENT_TIME);
1406 gtk_grab_add( window );
1410 * Respond to button press in completion window. Check if mouse click is
1411 * anywhere outside the completion window. In that case the completion
1412 * window is destroyed, and the original searchTerm is restored.
1414 * \param widget Window object.
1415 * \param event Event.
1416 * \param compWin Reference to completion window.
1418 static gboolean completion_window_button_press(GtkWidget *widget,
1419 GdkEventButton *event,
1420 CompletionWindow *compWin )
1422 GtkWidget *event_widget, *entry;
1425 gboolean restore = TRUE;
1427 cm_return_val_if_fail(compWin != NULL, FALSE);
1429 entry = compWin->entry;
1430 cm_return_val_if_fail(entry != NULL, FALSE);
1432 /* Test where mouse was clicked */
1433 event_widget = gtk_get_event_widget((GdkEvent *)event);
1434 if (event_widget != widget) {
1435 while (event_widget) {
1436 if (event_widget == widget)
1438 else if (event_widget == entry) {
1442 event_widget = gtk_widget_get_parent(event_widget);
1447 /* Clicked outside of completion window - restore */
1448 searchTerm = _compWindow_->searchTerm;
1449 g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1450 replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos, FALSE, NULL);
1453 clear_completion_cache();
1454 addrcompl_destroy_window( _compWindow_ );
1460 * Respond to key press in completion window.
1461 * \param widget Window object.
1462 * \param event Event.
1463 * \param compWind Reference to completion window.
1465 static gboolean completion_window_key_press(GtkWidget *widget,
1467 CompletionWindow *compWin )
1469 GdkEventKey tmp_event;
1473 GtkWidget *list_view;
1475 cm_return_val_if_fail(compWin != NULL, FALSE);
1477 entry = compWin->entry;
1478 list_view = compWin->list_view;
1479 cm_return_val_if_fail(entry != NULL, FALSE);
1481 /* allow keyboard navigation in the alternatives tree view */
1482 if (event->keyval == GDK_KEY_Up || event->keyval == GDK_KEY_Down ||
1483 event->keyval == GDK_KEY_Page_Up || event->keyval == GDK_KEY_Page_Down) {
1484 completion_window_advance_selection
1485 (GTK_TREE_VIEW(list_view),
1486 event->keyval == GDK_KEY_Down ||
1487 event->keyval == GDK_KEY_Page_Down ? TRUE : FALSE);
1491 /* make tab move to next field */
1492 if( event->keyval == GDK_KEY_Tab ) {
1493 /* Reference to parent */
1494 parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1496 /* Discard the window */
1497 clear_completion_cache();
1498 addrcompl_destroy_window( _compWindow_ );
1500 /* Move focus to next widget */
1502 gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1507 /* make backtab move to previous field */
1508 if( event->keyval == GDK_KEY_ISO_Left_Tab ) {
1509 /* Reference to parent */
1510 parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1512 /* Discard the window */
1513 clear_completion_cache();
1514 addrcompl_destroy_window( _compWindow_ );
1516 /* Move focus to previous widget */
1518 gtk_widget_child_focus( parent, GTK_DIR_TAB_BACKWARD );
1522 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS));
1524 /* look for presses that accept the selection */
1525 if (event->keyval == GDK_KEY_Return || event->keyval == GDK_KEY_space ||
1526 event->keyval == GDK_KEY_KP_Enter ||
1527 (_allowCommas_ && event->keyval == GDK_KEY_comma)) {
1528 /* User selected address with a key press */
1530 /* Display selected address in entry field */
1531 completion_window_apply_selection(
1532 GTK_TREE_VIEW(list_view), GTK_ENTRY(entry),
1533 event->keyval != GDK_KEY_comma);
1535 if (event->keyval == GDK_KEY_comma) {
1536 gint pos = gtk_editable_get_position(GTK_EDITABLE(entry));
1537 gtk_editable_insert_text(GTK_EDITABLE(entry), ", ", 2, &pos);
1538 gtk_editable_set_position(GTK_EDITABLE(entry), pos + 1);
1541 /* Discard the window */
1542 clear_completion_cache();
1543 addrcompl_destroy_window( _compWindow_ );
1547 /* key state keys should never be handled */
1548 if (event->keyval == GDK_KEY_Shift_L
1549 || event->keyval == GDK_KEY_Shift_R
1550 || event->keyval == GDK_KEY_Control_L
1551 || event->keyval == GDK_KEY_Control_R
1552 || event->keyval == GDK_KEY_Caps_Lock
1553 || event->keyval == GDK_KEY_Shift_Lock
1554 || event->keyval == GDK_KEY_Meta_L
1555 || event->keyval == GDK_KEY_Meta_R
1556 || event->keyval == GDK_KEY_Alt_L
1557 || event->keyval == GDK_KEY_Alt_R) {
1561 /* some other key, let's restore the searchTerm (orignal text) */
1562 searchTerm = _compWindow_->searchTerm;
1563 g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1564 replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos, FALSE, NULL);
1566 /* make sure anything we typed comes in the edit box */
1567 tmp_event.type = event->type;
1568 tmp_event.window = gtk_widget_get_window(GTK_WIDGET(entry));
1569 tmp_event.send_event = TRUE;
1570 tmp_event.time = event->time;
1571 tmp_event.state = event->state;
1572 tmp_event.keyval = event->keyval;
1573 tmp_event.length = event->length;
1574 tmp_event.string = event->string;
1575 gtk_widget_event(entry, (GdkEvent *)&tmp_event);
1577 /* and close the completion window */
1578 clear_completion_cache();
1579 addrcompl_destroy_window( _compWindow_ );
1585 * ============================================================================
1586 * Publically accessible functions.
1587 * ============================================================================
1591 * Setup completion object.
1593 void addrcompl_initialize( void ) {
1594 /* g_print( "addrcompl_initialize...\n" ); */
1595 if( ! _compWindow_ ) {
1596 _compWindow_ = addrcompl_create_window();
1599 _completionIdleID_ = 0;
1600 /* g_print( "addrcompl_initialize...done\n" ); */
1604 * Teardown completion object.
1606 void addrcompl_teardown( void ) {
1607 /* g_print( "addrcompl_teardown...\n" ); */
1608 addrcompl_free_window( _compWindow_ );
1609 _compWindow_ = NULL;
1610 if( _displayQueue_ ) {
1611 g_list_free( _displayQueue_ );
1613 _displayQueue_ = NULL;
1614 _completionIdleID_ = 0;
1615 /* g_print( "addrcompl_teardown...done\n" ); */
1619 * tree view functions
1622 static GtkListStore *addr_compl_create_store(void)
1624 return gtk_list_store_new(N_ADDR_COMPL_COLUMNS,
1632 static GtkWidget *addr_compl_list_view_create(CompletionWindow *window)
1634 GtkTreeView *list_view;
1635 GtkTreeSelection *selector;
1636 GtkTreeModel *model;
1638 model = GTK_TREE_MODEL(addr_compl_create_store());
1639 list_view = GTK_TREE_VIEW(gtk_tree_view_new_with_model(model));
1640 g_object_unref(model);
1642 gtk_tree_view_set_rules_hint(list_view, prefs_common.use_stripes_everywhere);
1643 gtk_tree_view_set_headers_visible(list_view, FALSE);
1645 selector = gtk_tree_view_get_selection(list_view);
1646 gtk_tree_selection_set_mode(selector, GTK_SELECTION_BROWSE);
1647 gtk_tree_selection_set_select_function(selector, addr_compl_selected,
1650 /* create the columns */
1651 addr_compl_create_list_view_columns(GTK_WIDGET(list_view));
1653 return GTK_WIDGET(list_view);
1656 static void addr_compl_create_list_view_columns(GtkWidget *list_view)
1658 GtkTreeViewColumn *column;
1659 GtkCellRenderer *renderer;
1661 renderer = gtk_cell_renderer_pixbuf_new();
1662 column = gtk_tree_view_column_new_with_attributes
1664 "pixbuf", ADDR_COMPL_ICON, NULL);
1665 gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);
1666 renderer = gtk_cell_renderer_text_new();
1667 column = gtk_tree_view_column_new_with_attributes
1668 ("", renderer, "text", ADDR_COMPL_ADDRESS, NULL);
1669 gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);
1672 static gboolean list_view_button_press(GtkWidget *widget, GdkEventButton *event,
1673 CompletionWindow *window)
1675 if (window && event && event->type == GDK_BUTTON_PRESS) {
1676 window->in_mouse = TRUE;
1681 static gboolean list_view_button_release(GtkWidget *widget, GdkEventButton *event,
1682 CompletionWindow *window)
1684 if (window && event && event->type == GDK_BUTTON_RELEASE) {
1685 window->in_mouse = FALSE;
1690 static gboolean addr_compl_selected(GtkTreeSelection *selector,
1691 GtkTreeModel *model,
1693 gboolean currently_selected,
1696 CompletionWindow *window = data;
1698 if (currently_selected)
1701 if (!window->in_mouse)
1704 /* XXX: select the entry and kill window later... select is called before
1705 * any other mouse events handlers including the tree view internal one;
1706 * not using a time out would result in a crash. if this doesn't work
1707 * safely, maybe we should set variables when receiving button presses
1708 * in the tree view. */
1709 if (!window->destroying) {
1710 window->destroying = TRUE;
1711 g_idle_add((GSourceFunc) addr_compl_defer_select_destruct, data);
1717 static gboolean addr_compl_defer_select_destruct(CompletionWindow *window)
1719 GtkEntry *entry = GTK_ENTRY(window->entry);
1721 completion_window_apply_selection(GTK_TREE_VIEW(window->list_view),
1724 clear_completion_cache();
1726 addrcompl_destroy_window(window);