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"
48 #ifndef USE_NEW_ADDRBOOK
49 #include "addrindex.h"
51 #include "addressbook-dbus.h"
55 *\brief For the GtkListStore
68 * The address book is read into memory. We set up an address list
69 * containing all address book entries. Next we make the completion
70 * list, which contains all the completable strings, and store a
71 * reference to the address entry it belongs to.
72 * After calling the g_completion_complete(), we get a reference
73 * to a valid email address.
75 * Completion is very simplified. We never complete on another prefix,
76 * i.e. we neglect the next smallest possible prefix for the current
77 * completion cache. This is simply done so we might break up the
78 * addresses a little more (e.g. break up alfons@proteus.demon.nl into
79 * something like alfons, proteus, demon, nl; and then completing on
80 * any of those words).
84 * completion_entry - structure used to complete addresses, with a reference
85 * the the real address information.
89 gchar *string; /* string to complete */
90 address_entry *ref; /* address the string belongs to */
93 /*******************************************************************************/
95 static gint g_ref_count; /* list ref count */
96 static GList *g_completion_list = NULL; /* list of strings to be checked */
97 static GList *g_address_list = NULL; /* address storage */
98 static GCompletion *g_completion; /* completion object */
100 static GHashTable *_groupAddresses_ = NULL;
101 static gboolean _allowCommas_ = TRUE;
103 /* To allow for continuing completion we have to keep track of the state
104 * using the following variables. No need to create a context object. */
106 static gint g_completion_count; /* nr of addresses incl. the prefix */
107 static gint g_completion_next; /* next prev address */
108 static GSList *g_completion_addresses; /* unique addresses found in the
110 static gchar *g_completion_prefix; /* last prefix. (this is cached here
111 * because the prefix passed to g_completion
112 * is g_utf8_strdown()'ed */
114 static gchar *completion_folder_path = NULL;
116 /*******************************************************************************/
119 * Define the structure of the completion window.
121 typedef struct _CompletionWindow CompletionWindow;
122 struct _CompletionWindow {
127 GtkWidget *list_view;
129 gboolean in_mouse; /*!< mouse press pending... */
130 gboolean destroying; /*!< destruction in progress */
133 static GtkListStore *addr_compl_create_store (void);
135 static GtkWidget *addr_compl_list_view_create (CompletionWindow *window);
137 static void addr_compl_create_list_view_columns (GtkWidget *list_view);
139 static gboolean list_view_button_press (GtkWidget *widget,
140 GdkEventButton *event,
141 CompletionWindow *window);
143 static gboolean list_view_button_release (GtkWidget *widget,
144 GdkEventButton *event,
145 CompletionWindow *window);
147 static gboolean addr_compl_selected (GtkTreeSelection *selector,
150 gboolean currently_selected,
153 static gboolean addr_compl_defer_select_destruct(CompletionWindow *window);
156 * Function used by GTK to find the string data to be used for completion.
157 * \param data Pointer to data being processed.
159 static gchar *completion_func(gpointer data)
161 cm_return_val_if_fail(data != NULL, NULL);
163 return ((completion_entry *)data)->string;
167 * Initialize all completion index data.
169 static void init_all(void)
171 g_completion = g_completion_new(completion_func);
172 cm_return_if_fail(g_completion != NULL);
175 static void free_all_addresses(void)
180 walk = g_address_list;
181 for (; walk != NULL; walk = g_list_next(walk)) {
182 address_entry *ae = (address_entry *) walk->data;
185 g_list_free(ae->grp_emails);
188 g_list_free(g_address_list);
189 g_address_list = NULL;
190 if (_groupAddresses_)
191 g_hash_table_destroy(_groupAddresses_);
192 _groupAddresses_ = NULL;
195 static void clear_completion_cache(void);
196 static void free_completion_list(void)
199 if (!g_completion_list)
202 clear_completion_cache();
204 g_completion_clear_items(g_completion);
206 walk = g_list_first(g_completion_list);
207 for (; walk != NULL; walk = g_list_next(walk)) {
208 completion_entry *ce = (completion_entry *) walk->data;
212 g_list_free(g_completion_list);
213 g_completion_list = NULL;
216 * Free up all completion index data.
218 static void free_all(void)
220 free_completion_list();
221 free_all_addresses();
222 g_completion_free(g_completion);
227 * Append specified address entry to the index.
228 * \param str Index string value.
229 * \param ae Entry containing address data.
231 void addr_compl_add_address1(const char *str, address_entry *ae)
233 completion_entry *ce1;
234 ce1 = g_new0(completion_entry, 1),
235 /* GCompletion list is case sensitive */
236 ce1->string = g_utf8_strdown(str, -1);
239 g_completion_list = g_list_prepend(g_completion_list, ce1);
243 * Adds address to the completion list. This function looks complicated, but
244 * it's only allocation checks. Each value will be included in the index.
245 * \param name Recipient name.
246 * \param address EMail address.
247 * \param alias Alias to append.
248 * \param grp_emails the emails in case of a group. List should be freed later,
249 * but not its strings
250 * \return <code>0</code> if entry appended successfully, or <code>-1</code>
253 static gint add_address(const gchar *name, const gchar *address,
254 const gchar *nick, const gchar *alias, GList *grp_emails)
257 gboolean is_group = FALSE;
259 if (!name || !address) {
260 if (!address && !nick && !alias && grp_emails) {
266 ae = g_new0(address_entry, 1);
268 cm_return_val_if_fail(ae != NULL, -1);
270 ae->name = g_strdup(name);
271 ae->address = g_strdup(address);
272 ae->grp_emails = grp_emails;
273 g_address_list = g_list_prepend(g_address_list, ae);
275 addr_compl_add_address1(name, ae);
276 if (address != NULL && *address != '\0')
277 addr_compl_add_address1(address, ae);
279 if (nick != NULL && *nick != '\0')
280 addr_compl_add_address1(nick, ae);
282 if ( alias != NULL && *alias != '\0') {
283 addr_compl_add_address1(alias, ae);
290 * Read address book, creating all entries in the completion index.
292 static void read_address_book(gchar *folderpath) {
293 free_all_addresses();
294 free_completion_list();
296 #ifndef USE_NEW_ADDRBOOK
297 addrindex_load_completion( add_address, folderpath );
299 GError* error = NULL;
301 addrcompl_initialize();
302 if (! addrindex_dbus_load_completion(add_address, &error)) {
303 g_warning("Failed to populate address completion list");
308 /* plugins may hook in here to modify/extend the completion list */
309 hooks_invoke(ADDDRESS_COMPLETION_BUILD_ADDRESS_LIST_HOOKLIST, &g_address_list);
311 g_address_list = g_list_reverse(g_address_list);
312 g_completion_list = g_list_reverse(g_completion_list);
313 /* merge the completion entry list into g_completion */
314 if (g_completion_list) {
315 g_completion_add_items(g_completion, g_completion_list);
316 if (debug_get_mode())
317 debug_print("read %d items in %s\n",
318 g_list_length(g_completion_list),
319 folderpath?folderpath:"(null)");
324 * Test whether there is a completion pending.
325 * \return <code>TRUE</code> if pending.
327 static gboolean is_completion_pending(void)
329 /* check if completion pending, i.e. we might satisfy a request for the next
330 * or previous address */
331 return g_completion_count;
335 * Clear the completion cache.
337 static void clear_completion_cache(void)
339 if (is_completion_pending()) {
340 g_free(g_completion_prefix);
342 if (g_completion_addresses) {
343 g_slist_free(g_completion_addresses);
344 g_completion_addresses = NULL;
347 g_completion_count = g_completion_next = 0;
352 * Prepare completion index. This function should be called prior to attempting
353 * address completion.
354 * \return The number of addresses in the completion list.
356 gint start_address_completion(gchar *folderpath)
358 gboolean different_book = FALSE;
359 clear_completion_cache();
361 if (strcmp2(completion_folder_path,folderpath))
362 different_book = TRUE;
364 g_free(completion_folder_path);
365 if (folderpath != NULL)
366 completion_folder_path = g_strdup(folderpath);
368 completion_folder_path = NULL;
372 /* open the address book */
373 read_address_book(folderpath);
374 } else if (different_book)
375 read_address_book(folderpath);
378 debug_print("start_address_completion(%s) ref count %d\n",
379 folderpath?folderpath:"(null)", g_ref_count);
381 return g_list_length(g_completion_list);
385 * Retrieve a possible address (or a part) from an entry box. To make life
386 * easier, we only look at the last valid address component; address
387 * completion only works at the last string component in the entry box.
389 * \param entry Address entry field.
390 * \param start_pos Address of start position of address.
391 * \return Possible address.
393 static gchar *get_address_from_edit(GtkEntry *entry, gint *start_pos)
395 const gchar *edit_text, *p;
397 gboolean in_quote = FALSE;
398 gboolean in_bracket = FALSE;
401 edit_text = gtk_entry_get_text(entry);
402 if (edit_text == NULL) return NULL;
404 cur_pos = gtk_editable_get_position(GTK_EDITABLE(entry));
406 /* scan for a separator. doesn't matter if walk points at null byte. */
407 for (p = g_utf8_offset_to_pointer(edit_text, cur_pos);
409 p = g_utf8_prev_char(p)) {
412 } else if (!in_quote) {
413 if (!in_bracket && *p == ',') {
415 } else if (*p == '<')
422 /* have something valid */
423 if (g_utf8_strlen(p, -1) == 0)
426 #define IS_VALID_CHAR(x) \
427 (g_ascii_isalnum(x) || (x) == '"' || (x) == '<' || (((unsigned char)(x)) > 0x7f))
429 /* now scan back until we hit a valid character */
430 for (; *p && !IS_VALID_CHAR(*p); p = g_utf8_next_char(p))
435 if (g_utf8_strlen(p, -1) == 0)
438 if (start_pos) *start_pos = g_utf8_pointer_to_offset(edit_text, p);
445 static gchar *get_complete_address_from_name_email(const gchar *name, const gchar *email)
447 gchar *address = NULL;
448 if (!name || name[0] == '\0')
449 address = g_strdup_printf("<%s>", email);
450 else if (strchr_with_skip_quote(name, '"', ','))
451 address = g_strdup_printf
452 ("\"%s\" <%s>", name, email);
454 address = g_strdup_printf
455 ("%s <%s>", name, email);
460 * Replace an incompleted address with a completed one.
461 * \param entry Address entry field.
462 * \param newtext New text.
463 * \param start_pos Insertion point in entry field.
465 static void replace_address_in_edit(GtkEntry *entry, const gchar *newtext,
466 gint start_pos, gboolean is_group, GList *grp_emails)
468 if (!newtext) return;
469 gtk_editable_delete_text(GTK_EDITABLE(entry), start_pos, -1);
471 gtk_editable_insert_text(GTK_EDITABLE(entry), newtext, strlen(newtext),
474 gchar *addresses = NULL;
475 GList *cur = grp_emails;
476 for (; cur; cur = cur->next) {
478 ItemEMail *email = (ItemEMail *)cur->data;
479 ItemPerson *person = ( ItemPerson * ) ADDRITEM_PARENT(email);
481 gchar *addr = get_complete_address_from_name_email(
482 ADDRITEM_NAME(person), email->address);
484 tmp = g_strdup_printf("%s, %s", addresses, addr);
486 tmp = g_strdup_printf("%s", addr);
491 gtk_editable_insert_text(GTK_EDITABLE(entry), addresses, strlen(addresses),
495 gtk_editable_set_position(GTK_EDITABLE(entry), -1);
499 * Attempt to complete an address, and returns the number of addresses found.
500 * Use <code>get_complete_address()</code> to get an entry from the index.
502 * \param str Search string to find.
503 * \return Zero if no match was found, otherwise the number of addresses; the
504 * original prefix (search string) will appear at index 0.
506 guint complete_address(const gchar *str)
508 GList *result = NULL;
512 completion_entry *ce = NULL;
514 cm_return_val_if_fail(str != NULL, 0);
516 /* g_completion is case sensitive */
517 d = g_utf8_strdown(str, -1);
519 clear_completion_cache();
520 g_completion_prefix = g_strdup(str);
522 result = g_completion_complete(g_completion, d, NULL);
524 count = g_list_length(result);
526 /* create list with unique addresses */
527 for (cpl = 0, result = g_list_first(result);
529 result = g_list_next(result)) {
530 ce = (completion_entry *)(result->data);
531 if (NULL == g_slist_find(g_completion_addresses,
534 g_completion_addresses =
535 g_slist_append(g_completion_addresses,
539 count = cpl + 1; /* index 0 is the original prefix */
540 g_completion_next = 1; /* we start at the first completed one */
542 g_free(g_completion_prefix);
543 g_completion_prefix = NULL;
546 g_completion_count = count;
554 * complete_matches_found() returns the number of matched addresses according
555 * to the completion mechanism. Unlike complete_address(), the returned value
556 * doesn't count str itself. If there's no match, it returns 0.
557 * To get a list of completion matches, see complete_address() instead.
559 guint complete_matches_found(const gchar *str)
561 GList *result = NULL;
564 cm_return_val_if_fail(str != NULL, 0);
566 /* g_completion is case sensitive */
567 d = g_utf8_strdown(str, -1);
569 clear_completion_cache();
570 g_completion_prefix = g_strdup(str);
572 result = g_completion_complete(g_completion, d, NULL);
574 g_free(g_completion_prefix);
577 return g_list_length(result);
581 * Return a complete address from the index.
582 * \param index Index of entry that was found (by the previous call to
583 * <code>complete_address()</code>
584 * \return Completed address string; this should be freed when done.
586 gchar *get_complete_address(gint index)
588 const address_entry *p;
589 gchar *address = NULL;
591 if (index < g_completion_count) {
593 address = g_strdup(g_completion_prefix);
595 /* get something from the unique addresses */
596 p = (address_entry *)g_slist_nth_data
597 (g_completion_addresses, index - 1);
598 if (p != NULL && p->address != NULL) {
599 address = get_complete_address_from_name_email(p->name, p->address);
600 } else if (p != NULL && p->address == NULL && p->name != NULL) {
602 address = g_strdup_printf("%s (%s) <!--___group___-->", p->name, _("Group"));
603 if (!_groupAddresses_) {
604 _groupAddresses_ = g_hash_table_new(NULL, g_direct_equal);
606 if (!g_hash_table_lookup(_groupAddresses_, GINT_TO_POINTER(g_str_hash(address)))) {
607 g_hash_table_insert(_groupAddresses_, GINT_TO_POINTER(g_str_hash(address)), p->grp_emails);
618 * Return the next complete address match from the completion index.
619 * \return Completed address string; this should be freed when done.
621 static gchar *get_next_complete_address(void)
623 if (is_completion_pending()) {
626 res = get_complete_address(g_completion_next);
627 g_completion_next += 1;
628 if (g_completion_next >= g_completion_count)
629 g_completion_next = 0;
637 * Return a count of the completed matches in the completion index.
638 * \return Number of matched entries.
640 static guint get_completion_count(void)
642 if (is_completion_pending())
643 return g_completion_count;
649 * Invalidate address completion index. This function should be called whenever
650 * the address book changes. This forces data to be read into the completion
652 * \return Number of entries in index.
654 gint invalidate_address_completion(void)
657 /* simply the same as start_address_completion() */
658 debug_print("Invalidation request for address completion\n");
659 read_address_book(completion_folder_path);
660 clear_completion_cache();
663 return g_list_length(g_completion_list);
667 * Finished with completion index. This function should be called after
668 * matching addresses.
669 * \return Reference count.
671 gint end_address_completion(void)
673 gboolean different_folder = FALSE;
674 clear_completion_cache();
676 /* reset the folderpath to NULL */
677 if (completion_folder_path) {
678 g_free(completion_folder_path);
679 completion_folder_path = NULL;
680 different_folder = TRUE;
682 if (0 == --g_ref_count)
685 debug_print("end_address_completion ref count %d\n", g_ref_count);
686 if (g_ref_count && different_folder) {
687 debug_print("still ref'd, different folder\n");
688 invalidate_address_completion();
697 static CompletionWindow *_compWindow_ = NULL;
700 * Mutex to protect callback from multiple threads.
702 static pthread_mutex_t _completionMutex_ = PTHREAD_MUTEX_INITIALIZER;
705 * Completion queue list.
707 static GList *_displayQueue_ = NULL;
711 static gint _queryID_ = 0;
714 * Completion idle ID.
716 static guint _completionIdleID_ = 0;
719 * address completion entry ui. the ui (completion list was inspired by galeon's
720 * auto completion list). remaining things powered by claws's completion engine.
723 #define ENTRY_DATA_TAB_HOOK "tab_hook" /* used to lookup entry */
724 #define ENTRY_DATA_ALLOW_COMMAS "allowcommas" /* used to know whether to present groups */
726 static void address_completion_mainwindow_set_focus (GtkWindow *window,
729 static gboolean address_completion_entry_key_pressed (GtkEntry *entry,
732 static gboolean address_completion_complete_address_in_entry
735 static void address_completion_create_completion_window (GtkEntry *entry);
737 static gboolean completion_window_button_press
739 GdkEventButton *event,
740 CompletionWindow *compWin );
742 static gboolean completion_window_key_press
745 CompletionWindow *compWin );
746 static void address_completion_create_completion_window( GtkEntry *entry_ );
749 * Create a completion window object.
750 * \return Initialized completion window.
752 static CompletionWindow *addrcompl_create_window( void ) {
753 CompletionWindow *cw;
755 cw = g_new0( CompletionWindow, 1 );
757 cw->searchTerm = NULL;
760 cw->list_view = NULL;
761 cw->in_mouse = FALSE;
762 cw->destroying = FALSE;
768 * Destroy completion window.
769 * \param cw Window to destroy.
771 static void addrcompl_destroy_window( CompletionWindow *cw ) {
772 /* Stop all searches currently in progress */
773 #ifndef USE_NEW_ADDRBOOK
774 addrindex_stop_search( _queryID_ );
776 /* Remove idler function... or application may not terminate */
777 if( _completionIdleID_ != 0 ) {
778 g_source_remove( _completionIdleID_ );
779 _completionIdleID_ = 0;
782 /* Now destroy window */
784 /* Clear references to widgets */
786 cw->list_view = NULL;
790 gtk_widget_hide( cw->window );
791 gtk_widget_destroy( cw->window );
794 cw->destroying = FALSE;
795 cw->in_mouse = FALSE;
801 * Free up completion window.
802 * \param cw Window to free.
804 static void addrcompl_free_window( CompletionWindow *cw ) {
806 addrcompl_destroy_window( cw );
808 g_free( cw->searchTerm );
809 cw->searchTerm = NULL;
811 /* Clear references */
820 * Advance selection to previous/next item in list.
821 * \param list_view List to process.
822 * \param forward Set to <i>TRUE</i> to select next or <i>FALSE</i> for
825 static void completion_window_advance_selection(GtkTreeView *list_view, gboolean forward)
827 GtkTreeSelection *selection;
831 cm_return_if_fail(list_view != NULL);
833 selection = gtk_tree_view_get_selection(list_view);
834 if (!gtk_tree_selection_get_selected(selection, &model, &iter))
838 forward = gtk_tree_model_iter_next(model, &iter);
840 gtk_tree_selection_select_iter(selection, &iter);
844 prev = gtk_tree_model_get_path(model, &iter);
848 if (gtk_tree_path_prev(prev))
849 gtk_tree_selection_select_path(selection, prev);
851 gtk_tree_path_free(prev);
856 * Resize window to accommodate maximum number of address entries.
857 * \param cw Completion window.
859 static void addrcompl_resize_window( CompletionWindow *cw ) {
861 gint x, y, width, height, depth;
863 /* Get current geometry of window */
864 gdk_window_get_geometry( gtk_widget_get_window( cw->window ), &x, &y, &width, &height, &depth );
866 /* simple _hide breaks size requisition !? */
867 gtk_widget_hide_all( cw->window );
868 gtk_widget_show_all( cw->window );
869 gtk_widget_size_request( cw->list_view, &r );
871 /* Adjust window height to available screen space */
872 if( y + r.height > gdk_screen_height())
873 r.height = gdk_screen_height() - y;
875 gtk_widget_set_size_request(cw->window, width, r.height);
877 gdk_pointer_grab(gtk_widget_get_window(cw->window), TRUE,
878 GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK |
879 GDK_BUTTON_RELEASE_MASK,
880 NULL, NULL, GDK_CURRENT_TIME);
881 gdk_keyboard_grab(gtk_widget_get_window(cw->window), FALSE, GDK_CURRENT_TIME);
882 gtk_grab_add(cw->window);
886 static GdkPixbuf *group_pixbuf = NULL;
887 static GdkPixbuf *email_pixbuf = NULL;
890 * Add an address the completion window address list.
891 * \param cw Completion window.
892 * \param address Address to add.
894 static void addrcompl_add_entry( CompletionWindow *cw, gchar *address ) {
897 GtkTreeSelection *selection;
898 gboolean is_group = FALSE;
899 GList *grp_emails = NULL;
900 store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(cw->list_view)));
904 stock_pixbuf_gdk(cw->list_view, STOCK_PIXMAP_ADDR_TWO, &group_pixbuf);
905 g_object_ref(G_OBJECT(group_pixbuf));
908 stock_pixbuf_gdk(cw->list_view, STOCK_PIXMAP_ADDR_ONE, &email_pixbuf);
909 g_object_ref(G_OBJECT(email_pixbuf));
911 /* g_print( "\t\tAdding :%s\n", address ); */
912 if (strstr(address, " <!--___group___-->")) {
914 if (_groupAddresses_)
915 grp_emails = g_hash_table_lookup(_groupAddresses_, GINT_TO_POINTER(g_str_hash(address)));
916 *(strstr(address, " <!--___group___-->")) = '\0';
917 pixbuf = group_pixbuf;
918 } else if (strchr(address, '@') && strchr(address, '<') &&
919 strchr(address, '>')) {
920 pixbuf = email_pixbuf;
924 if (is_group && !_allowCommas_)
926 gtk_list_store_append(store, &iter);
927 gtk_list_store_set(store, &iter,
928 ADDR_COMPL_ICON, pixbuf,
929 ADDR_COMPL_ADDRESS, address,
930 ADDR_COMPL_ISGROUP, is_group,
931 ADDR_COMPL_GROUPLIST, grp_emails,
936 addrcompl_resize_window( cw );
937 gtk_grab_add( cw->window );
939 selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(cw->list_view));
940 gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store), &iter);
942 if( cw->listCount == 1 ) {
943 /* Select first row for now */
944 gtk_tree_selection_select_iter(selection, &iter);
947 else if( cw->listCount == 2 ) {
948 gtk_tree_model_iter_next(GTK_TREE_MODEL(store), &iter);
949 /* Move off first row */
950 gtk_tree_selection_select_iter(selection, &iter);
956 * Completion idle function. This function is called by the main (UI) thread
957 * during UI idle time while an address search is in progress. Items from the
958 * display queue are processed and appended to the address list.
960 * \param data Target completion window to receive email addresses.
961 * \return <i>TRUE</i> to ensure that idle event do not get ignored.
963 static gboolean addrcompl_idle( gpointer data ) {
967 /* Process all entries in display queue */
968 pthread_mutex_lock( & _completionMutex_ );
969 if( _displayQueue_ ) {
970 node = _displayQueue_;
972 address = node->data;
973 /* g_print( "address ::: %s :::\n", address ); */
974 addrcompl_add_entry( _compWindow_, address );
976 node = g_list_next( node );
978 g_list_free( _displayQueue_ );
979 _displayQueue_ = NULL;
981 pthread_mutex_unlock( & _completionMutex_ );
988 * Callback entry point. The background thread (if any) appends the address
989 * list to the display queue.
990 * \param sender Sender of query.
991 * \param queryID Query ID of search request.
992 * \param listEMail List of zero of more email objects that met search
994 * \param data Query data.
996 #ifndef USE_NEW_ADDRBOOK
997 static gint addrcompl_callback_entry(
998 gpointer sender, gint queryID, GList *listEMail, gpointer data )
1003 /* g_print( "addrcompl_callback_entry::queryID=%d\n", queryID ); */
1004 pthread_mutex_lock( & _completionMutex_ );
1005 if( queryID == _queryID_ ) {
1006 /* Append contents to end of display queue */
1009 ItemEMail *email = node->data;
1011 address = addritem_format_email( email );
1012 /* g_print( "\temail/address ::%s::\n", address ); */
1013 _displayQueue_ = g_list_append( _displayQueue_, address );
1014 node = g_list_next( node );
1017 g_list_free( listEMail );
1018 pthread_mutex_unlock( & _completionMutex_ );
1025 * Clear the display queue.
1027 static void addrcompl_clear_queue( void ) {
1028 /* Clear out display queue */
1029 pthread_mutex_lock( & _completionMutex_ );
1031 g_list_free( _displayQueue_ );
1032 _displayQueue_ = NULL;
1034 pthread_mutex_unlock( & _completionMutex_ );
1038 * Add a single address entry into the display queue.
1039 * \param address Address to append.
1041 static void addrcompl_add_queue( gchar *address ) {
1042 pthread_mutex_lock( & _completionMutex_ );
1043 _displayQueue_ = g_list_append( _displayQueue_, address );
1044 pthread_mutex_unlock( & _completionMutex_ );
1048 * Load list with entries from local completion index.
1050 static void addrcompl_load_local( void ) {
1053 for (count = 0; count < get_completion_count(); count++) {
1056 address = get_complete_address( count );
1057 /* g_print( "\taddress ::%s::\n", address ); */
1059 /* Append contents to end of display queue */
1060 addrcompl_add_queue( address );
1067 static void addrcompl_start_search( void ) {
1068 #ifndef USE_NEW_ADDRBOOK
1071 searchTerm = g_strdup( _compWindow_->searchTerm );
1073 /* Setup the search */
1074 _queryID_ = addrindex_setup_search(
1075 searchTerm, NULL, addrcompl_callback_entry );
1076 g_free( searchTerm );
1078 /* g_print( "addrcompl_start_search::queryID=%d\n", _queryID_ ); */
1080 /* Load local stuff */
1081 addrcompl_load_local();
1083 /* Sit back and wait until something happens */
1084 _completionIdleID_ =
1085 g_idle_add( (GSourceFunc) addrcompl_idle, NULL );
1086 /* g_print( "addrindex_start_search::queryID=%d\n", _queryID_ ); */
1088 #ifndef USE_NEW_ADDRBOOK
1089 addrindex_start_search( _queryID_ );
1096 * Apply the current selection in the list to the entry field. Focus is also
1097 * moved to the next widget so that Tab key works correctly.
1098 * \param list_view List to process.
1099 * \param entry Address entry field.
1100 * \param move_focus Move focus to the next widget ?
1102 static void completion_window_apply_selection(GtkTreeView *list_view,
1104 gboolean move_focus)
1106 gchar *address = NULL, *text = NULL;
1109 GtkTreeSelection *selection;
1110 GtkTreeModel *model;
1112 gboolean is_group = FALSE;
1113 cm_return_if_fail(list_view != NULL);
1114 cm_return_if_fail(entry != NULL);
1115 GList *grp_emails = NULL;
1117 selection = gtk_tree_view_get_selection(list_view);
1118 if (! gtk_tree_selection_get_selected(selection, &model, &iter))
1121 /* First remove the idler */
1122 if( _completionIdleID_ != 0 ) {
1123 g_source_remove( _completionIdleID_ );
1124 _completionIdleID_ = 0;
1127 /* Process selected item */
1128 gtk_tree_model_get(model, &iter, ADDR_COMPL_ADDRESS, &text,
1129 ADDR_COMPL_ISGROUP, &is_group,
1130 ADDR_COMPL_GROUPLIST, &grp_emails,
1133 address = get_address_from_edit(entry, &cursor_pos);
1135 replace_address_in_edit(entry, text, cursor_pos, is_group, grp_emails);
1138 /* Move focus to next widget */
1139 parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1140 if( parent && move_focus) {
1141 gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1146 * Start address completion. Should be called when creating the main window
1147 * containing address completion entries.
1148 * \param mainwindow Main window.
1150 void address_completion_start(GtkWidget *mainwindow)
1152 start_address_completion(NULL);
1154 /* register focus change hook */
1155 g_signal_connect(G_OBJECT(mainwindow), "set_focus",
1156 G_CALLBACK(address_completion_mainwindow_set_focus),
1161 * Need unique data to make unregistering signal handler possible for the auto
1164 #define COMPLETION_UNIQUE_DATA (GINT_TO_POINTER(0xfeefaa))
1167 * Register specified entry widget for address completion.
1168 * \param entry Address entry field.
1170 void address_completion_register_entry(GtkEntry *entry, gboolean allow_commas)
1172 cm_return_if_fail(entry != NULL);
1173 cm_return_if_fail(GTK_IS_ENTRY(entry));
1175 /* add hooked property */
1176 g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, entry);
1177 g_object_set_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS, GINT_TO_POINTER(allow_commas));
1179 /* add keypress event */
1180 g_signal_connect_closure
1181 (G_OBJECT(entry), "key_press_event",
1182 g_cclosure_new(G_CALLBACK(address_completion_entry_key_pressed),
1183 COMPLETION_UNIQUE_DATA,
1189 * Unregister specified entry widget from address completion operations.
1190 * \param entry Address entry field.
1192 void address_completion_unregister_entry(GtkEntry *entry)
1196 cm_return_if_fail(entry != NULL);
1197 cm_return_if_fail(GTK_IS_ENTRY(entry));
1199 entry_obj = g_object_get_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK);
1200 cm_return_if_fail(entry_obj);
1201 cm_return_if_fail(G_OBJECT(entry_obj) == G_OBJECT(entry));
1203 /* has the hooked property? */
1204 g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, NULL);
1206 /* remove the hook */
1207 g_signal_handlers_disconnect_by_func(G_OBJECT(entry),
1208 G_CALLBACK(address_completion_entry_key_pressed),
1209 COMPLETION_UNIQUE_DATA);
1213 * End address completion. Should be called when main window with address
1214 * completion entries terminates. NOTE: this function assumes that it is
1215 * called upon destruction of the window.
1216 * \param mainwindow Main window.
1218 void address_completion_end(GtkWidget *mainwindow)
1220 /* if address_completion_end() is really called on closing the window,
1221 * we don't need to unregister the set_focus_cb */
1222 end_address_completion();
1225 /* if focus changes to another entry, then clear completion cache */
1226 static void address_completion_mainwindow_set_focus(GtkWindow *window,
1231 if (widget && GTK_IS_ENTRY(widget) &&
1232 g_object_get_data(G_OBJECT(widget), ENTRY_DATA_TAB_HOOK)) {
1233 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), ENTRY_DATA_ALLOW_COMMAS));
1234 clear_completion_cache();
1239 * Listener that watches for tab or other keystroke in address entry field.
1240 * \param entry Address entry field.
1241 * \param ev Event object.
1242 * \param data User data.
1243 * \return <i>TRUE</i>.
1245 static gboolean address_completion_entry_key_pressed(GtkEntry *entry,
1249 if (ev->keyval == GDK_KEY_Tab) {
1250 addrcompl_clear_queue();
1251 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS));
1252 if( address_completion_complete_address_in_entry( entry, TRUE ) ) {
1253 /* route a void character to the default handler */
1254 /* this is a dirty hack; we're actually changing a key
1255 * reported by the system. */
1256 ev->keyval = GDK_KEY_AudibleBell_Enable;
1257 ev->state &= ~GDK_SHIFT_MASK;
1260 address_completion_create_completion_window(entry);
1262 /* Start remote queries */
1263 addrcompl_start_search();
1270 } else if (ev->keyval == GDK_KEY_Shift_L
1271 || ev->keyval == GDK_KEY_Shift_R
1272 || ev->keyval == GDK_KEY_Control_L
1273 || ev->keyval == GDK_KEY_Control_R
1274 || ev->keyval == GDK_KEY_Caps_Lock
1275 || ev->keyval == GDK_KEY_Shift_Lock
1276 || ev->keyval == GDK_KEY_Meta_L
1277 || ev->keyval == GDK_KEY_Meta_R
1278 || ev->keyval == GDK_KEY_Alt_L
1279 || ev->keyval == GDK_KEY_Alt_R) {
1280 /* these buttons should not clear the cache... */
1282 clear_completion_cache();
1287 * Initialize search term for address completion.
1288 * \param entry Address entry field.
1290 static gboolean address_completion_complete_address_in_entry(GtkEntry *entry,
1293 gint ncount, cursor_pos;
1294 gchar *searchTerm, *new = NULL;
1296 cm_return_val_if_fail(entry != NULL, FALSE);
1298 if (!gtk_widget_has_focus(GTK_WIDGET(entry))) return FALSE;
1300 /* get an address component from the cursor */
1301 searchTerm = get_address_from_edit( entry, &cursor_pos );
1302 if( ! searchTerm ) return FALSE;
1303 /* g_print( "search for :::%s:::\n", searchTerm ); */
1305 /* Clear any existing search */
1306 g_free( _compWindow_->searchTerm );
1307 _compWindow_->searchTerm = g_strdup( searchTerm );
1309 /* Perform search on local completion index */
1310 ncount = complete_address( searchTerm );
1312 new = get_next_complete_address();
1315 #if (!defined(USE_LDAP) && !defined(GENERIC_UMPC))
1316 /* Select the address if there is only one match */
1318 /* Display selected address in entry field */
1319 gchar *addr = get_complete_address(1);
1320 if (addr && !strstr(addr, " <!--___group___-->")) {
1321 replace_address_in_edit(entry, addr, cursor_pos, FALSE, NULL);
1322 /* Discard the window */
1323 clear_completion_cache();
1327 /* Make sure that drop-down appears uniform! */
1331 addrcompl_add_queue( g_strdup( searchTerm ) );
1333 g_free( searchTerm );
1339 * Create new address completion window for specified entry.
1340 * \param entry_ Entry widget to associate with window.
1342 static void address_completion_create_completion_window( GtkEntry *entry_ )
1344 gint x, y, height, width, depth;
1345 GtkWidget *scroll, *list_view;
1348 GtkWidget *entry = GTK_WIDGET(entry_);
1351 /* Create new window and list */
1352 window = gtk_window_new(GTK_WINDOW_POPUP);
1353 list_view = addr_compl_list_view_create(_compWindow_);
1355 /* Destroy any existing window */
1356 addrcompl_destroy_window( _compWindow_ );
1358 /* Create new object */
1359 _compWindow_->window = window;
1360 _compWindow_->entry = entry;
1361 _compWindow_->list_view = list_view;
1362 _compWindow_->listCount = 0;
1363 _compWindow_->in_mouse = FALSE;
1365 scroll = gtk_scrolled_window_new(NULL, NULL);
1366 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
1367 GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
1368 gtk_container_add(GTK_CONTAINER(window), scroll);
1369 gtk_container_add(GTK_CONTAINER(scroll), list_view);
1370 gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll),
1372 /* Use entry widget to create initial window */
1373 gdkwin = gtk_widget_get_window(entry),
1374 gdk_window_get_geometry(gdkwin, &x, &y, &width, &height, &depth);
1375 gdk_window_get_origin (gdkwin, &x, &y);
1377 gtk_window_move(GTK_WINDOW(window), x, y);
1379 /* Resize window to fit initial (empty) address list */
1380 gtk_widget_size_request( list_view, &r );
1381 gtk_widget_set_size_request( window, width, r.height );
1382 gtk_widget_show_all( window );
1383 gtk_widget_size_request( list_view, &r );
1385 /* Setup handlers */
1386 g_signal_connect(G_OBJECT(list_view), "button_press_event",
1387 G_CALLBACK(list_view_button_press),
1390 g_signal_connect(G_OBJECT(list_view), "button_release_event",
1391 G_CALLBACK(list_view_button_release),
1394 g_signal_connect(G_OBJECT(window),
1395 "button-press-event",
1396 G_CALLBACK(completion_window_button_press),
1398 g_signal_connect(G_OBJECT(window),
1400 G_CALLBACK(completion_window_key_press),
1402 gdk_pointer_grab(gtk_widget_get_window(window), TRUE,
1403 GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK |
1404 GDK_BUTTON_RELEASE_MASK,
1405 NULL, NULL, GDK_CURRENT_TIME);
1406 gdk_keyboard_grab(gtk_widget_get_window(window), FALSE, GDK_CURRENT_TIME);
1407 gtk_grab_add( window );
1411 * Respond to button press in completion window. Check if mouse click is
1412 * anywhere outside the completion window. In that case the completion
1413 * window is destroyed, and the original searchTerm is restored.
1415 * \param widget Window object.
1416 * \param event Event.
1417 * \param compWin Reference to completion window.
1419 static gboolean completion_window_button_press(GtkWidget *widget,
1420 GdkEventButton *event,
1421 CompletionWindow *compWin )
1423 GtkWidget *event_widget, *entry;
1426 gboolean restore = TRUE;
1428 cm_return_val_if_fail(compWin != NULL, FALSE);
1430 entry = compWin->entry;
1431 cm_return_val_if_fail(entry != NULL, FALSE);
1433 /* Test where mouse was clicked */
1434 event_widget = gtk_get_event_widget((GdkEvent *)event);
1435 if (event_widget != widget) {
1436 while (event_widget) {
1437 if (event_widget == widget)
1439 else if (event_widget == entry) {
1443 event_widget = gtk_widget_get_parent(event_widget);
1448 /* Clicked outside of completion window - restore */
1449 searchTerm = _compWindow_->searchTerm;
1450 g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1451 replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos, FALSE, NULL);
1454 clear_completion_cache();
1455 addrcompl_destroy_window( _compWindow_ );
1461 * Respond to key press in completion window.
1462 * \param widget Window object.
1463 * \param event Event.
1464 * \param compWind Reference to completion window.
1466 static gboolean completion_window_key_press(GtkWidget *widget,
1468 CompletionWindow *compWin )
1470 GdkEventKey tmp_event;
1474 GtkWidget *list_view;
1476 cm_return_val_if_fail(compWin != NULL, FALSE);
1478 entry = compWin->entry;
1479 list_view = compWin->list_view;
1480 cm_return_val_if_fail(entry != NULL, FALSE);
1482 /* allow keyboard navigation in the alternatives tree view */
1483 if (event->keyval == GDK_KEY_Up || event->keyval == GDK_KEY_Down ||
1484 event->keyval == GDK_KEY_Page_Up || event->keyval == GDK_KEY_Page_Down) {
1485 completion_window_advance_selection
1486 (GTK_TREE_VIEW(list_view),
1487 event->keyval == GDK_KEY_Down ||
1488 event->keyval == GDK_KEY_Page_Down ? TRUE : FALSE);
1492 /* make tab move to next field */
1493 if( event->keyval == GDK_KEY_Tab ) {
1494 /* Reference to parent */
1495 parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1497 /* Discard the window */
1498 clear_completion_cache();
1499 addrcompl_destroy_window( _compWindow_ );
1501 /* Move focus to next widget */
1503 gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1508 /* make backtab move to previous field */
1509 if( event->keyval == GDK_KEY_ISO_Left_Tab ) {
1510 /* Reference to parent */
1511 parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1513 /* Discard the window */
1514 clear_completion_cache();
1515 addrcompl_destroy_window( _compWindow_ );
1517 /* Move focus to previous widget */
1519 gtk_widget_child_focus( parent, GTK_DIR_TAB_BACKWARD );
1523 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS));
1525 /* look for presses that accept the selection */
1526 if (event->keyval == GDK_KEY_Return || event->keyval == GDK_KEY_space ||
1527 event->keyval == GDK_KEY_KP_Enter ||
1528 (_allowCommas_ && event->keyval == GDK_KEY_comma)) {
1529 /* User selected address with a key press */
1531 /* Display selected address in entry field */
1532 completion_window_apply_selection(
1533 GTK_TREE_VIEW(list_view), GTK_ENTRY(entry),
1534 event->keyval != GDK_KEY_comma);
1536 if (event->keyval == GDK_KEY_comma) {
1537 gint pos = gtk_editable_get_position(GTK_EDITABLE(entry));
1538 gtk_editable_insert_text(GTK_EDITABLE(entry), ", ", 2, &pos);
1539 gtk_editable_set_position(GTK_EDITABLE(entry), pos + 1);
1542 /* Discard the window */
1543 clear_completion_cache();
1544 addrcompl_destroy_window( _compWindow_ );
1548 /* key state keys should never be handled */
1549 if (event->keyval == GDK_KEY_Shift_L
1550 || event->keyval == GDK_KEY_Shift_R
1551 || event->keyval == GDK_KEY_Control_L
1552 || event->keyval == GDK_KEY_Control_R
1553 || event->keyval == GDK_KEY_Caps_Lock
1554 || event->keyval == GDK_KEY_Shift_Lock
1555 || event->keyval == GDK_KEY_Meta_L
1556 || event->keyval == GDK_KEY_Meta_R
1557 || event->keyval == GDK_KEY_Alt_L
1558 || event->keyval == GDK_KEY_Alt_R) {
1562 /* some other key, let's restore the searchTerm (orignal text) */
1563 searchTerm = _compWindow_->searchTerm;
1564 g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1565 replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos, FALSE, NULL);
1567 /* make sure anything we typed comes in the edit box */
1568 tmp_event.type = event->type;
1569 tmp_event.window = gtk_widget_get_window(GTK_WIDGET(entry));
1570 tmp_event.send_event = TRUE;
1571 tmp_event.time = event->time;
1572 tmp_event.state = event->state;
1573 tmp_event.keyval = event->keyval;
1574 tmp_event.length = event->length;
1575 tmp_event.string = event->string;
1576 gtk_widget_event(entry, (GdkEvent *)&tmp_event);
1578 /* and close the completion window */
1579 clear_completion_cache();
1580 addrcompl_destroy_window( _compWindow_ );
1586 * ============================================================================
1587 * Publically accessible functions.
1588 * ============================================================================
1592 * Setup completion object.
1594 void addrcompl_initialize( void ) {
1595 /* g_print( "addrcompl_initialize...\n" ); */
1596 if( ! _compWindow_ ) {
1597 _compWindow_ = addrcompl_create_window();
1600 _completionIdleID_ = 0;
1601 /* g_print( "addrcompl_initialize...done\n" ); */
1605 * Teardown completion object.
1607 void addrcompl_teardown( void ) {
1608 /* g_print( "addrcompl_teardown...\n" ); */
1609 addrcompl_free_window( _compWindow_ );
1610 _compWindow_ = NULL;
1611 if( _displayQueue_ ) {
1612 g_list_free( _displayQueue_ );
1614 _displayQueue_ = NULL;
1615 _completionIdleID_ = 0;
1616 /* g_print( "addrcompl_teardown...done\n" ); */
1620 * tree view functions
1623 static GtkListStore *addr_compl_create_store(void)
1625 return gtk_list_store_new(N_ADDR_COMPL_COLUMNS,
1633 static GtkWidget *addr_compl_list_view_create(CompletionWindow *window)
1635 GtkTreeView *list_view;
1636 GtkTreeSelection *selector;
1637 GtkTreeModel *model;
1639 model = GTK_TREE_MODEL(addr_compl_create_store());
1640 list_view = GTK_TREE_VIEW(gtk_tree_view_new_with_model(model));
1641 g_object_unref(model);
1643 gtk_tree_view_set_rules_hint(list_view, prefs_common.use_stripes_everywhere);
1644 gtk_tree_view_set_headers_visible(list_view, FALSE);
1646 selector = gtk_tree_view_get_selection(list_view);
1647 gtk_tree_selection_set_mode(selector, GTK_SELECTION_BROWSE);
1648 gtk_tree_selection_set_select_function(selector, addr_compl_selected,
1651 /* create the columns */
1652 addr_compl_create_list_view_columns(GTK_WIDGET(list_view));
1654 return GTK_WIDGET(list_view);
1657 static void addr_compl_create_list_view_columns(GtkWidget *list_view)
1659 GtkTreeViewColumn *column;
1660 GtkCellRenderer *renderer;
1662 renderer = gtk_cell_renderer_pixbuf_new();
1663 column = gtk_tree_view_column_new_with_attributes
1665 "pixbuf", ADDR_COMPL_ICON, NULL);
1666 gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);
1667 renderer = gtk_cell_renderer_text_new();
1668 column = gtk_tree_view_column_new_with_attributes
1669 ("", renderer, "text", ADDR_COMPL_ADDRESS, NULL);
1670 gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);
1673 static gboolean list_view_button_press(GtkWidget *widget, GdkEventButton *event,
1674 CompletionWindow *window)
1676 if (window && event && event->type == GDK_BUTTON_PRESS) {
1677 window->in_mouse = TRUE;
1682 static gboolean list_view_button_release(GtkWidget *widget, GdkEventButton *event,
1683 CompletionWindow *window)
1685 if (window && event && event->type == GDK_BUTTON_RELEASE) {
1686 window->in_mouse = FALSE;
1691 static gboolean addr_compl_selected(GtkTreeSelection *selector,
1692 GtkTreeModel *model,
1694 gboolean currently_selected,
1697 CompletionWindow *window = data;
1699 if (currently_selected)
1702 if (!window->in_mouse)
1705 /* XXX: select the entry and kill window later... select is called before
1706 * any other mouse events handlers including the tree view internal one;
1707 * not using a time out would result in a crash. if this doesn't work
1708 * safely, maybe we should set variables when receiving button presses
1709 * in the tree view. */
1710 if (!window->destroying) {
1711 window->destroying = TRUE;
1712 g_idle_add((GSourceFunc) addr_compl_defer_select_destruct, data);
1718 static gboolean addr_compl_defer_select_destruct(CompletionWindow *window)
1720 GtkEntry *entry = GTK_ENTRY(window->entry);
1722 completion_window_apply_selection(GTK_TREE_VIEW(window->list_view),
1725 clear_completion_cache();
1727 addrcompl_destroy_window(window);