2 * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
4 * Copyright (C) 2000-2011 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 "addrindex.h"
39 #include "addr_compl.h"
41 #include "prefs_common.h"
48 *\brief For the GtkListStore
61 * The address book is read into memory. We set up an address list
62 * containing all address book entries. Next we make the completion
63 * list, which contains all the completable strings, and store a
64 * reference to the address entry it belongs to.
65 * After calling the g_completion_complete(), we get a reference
66 * to a valid email address.
68 * Completion is very simplified. We never complete on another prefix,
69 * i.e. we neglect the next smallest possible prefix for the current
70 * completion cache. This is simply done so we might break up the
71 * addresses a little more (e.g. break up alfons@proteus.demon.nl into
72 * something like alfons, proteus, demon, nl; and then completing on
73 * any of those words).
77 * completion_entry - structure used to complete addresses, with a reference
78 * the the real address information.
82 gchar *string; /* string to complete */
83 address_entry *ref; /* address the string belongs to */
86 /*******************************************************************************/
88 static gint g_ref_count; /* list ref count */
89 static GList *g_completion_list = NULL; /* list of strings to be checked */
90 static GList *g_address_list = NULL; /* address storage */
91 static GCompletion *g_completion; /* completion object */
93 static GHashTable *_groupAddresses_ = NULL;
94 static gboolean _allowCommas_ = TRUE;
96 /* To allow for continuing completion we have to keep track of the state
97 * using the following variables. No need to create a context object. */
99 static gint g_completion_count; /* nr of addresses incl. the prefix */
100 static gint g_completion_next; /* next prev address */
101 static GSList *g_completion_addresses; /* unique addresses found in the
103 static gchar *g_completion_prefix; /* last prefix. (this is cached here
104 * because the prefix passed to g_completion
105 * is g_utf8_strdown()'ed */
107 static gchar *completion_folder_path = NULL;
109 /*******************************************************************************/
112 * Define the structure of the completion window.
114 typedef struct _CompletionWindow CompletionWindow;
115 struct _CompletionWindow {
120 GtkWidget *list_view;
122 gboolean in_mouse; /*!< mouse press pending... */
123 gboolean destroying; /*!< destruction in progress */
126 static GtkListStore *addr_compl_create_store (void);
128 static GtkWidget *addr_compl_list_view_create (CompletionWindow *window);
130 static void addr_compl_create_list_view_columns (GtkWidget *list_view);
132 static gboolean list_view_button_press (GtkWidget *widget,
133 GdkEventButton *event,
134 CompletionWindow *window);
136 static gboolean list_view_button_release (GtkWidget *widget,
137 GdkEventButton *event,
138 CompletionWindow *window);
140 static gboolean addr_compl_selected (GtkTreeSelection *selector,
143 gboolean currently_selected,
146 static gboolean addr_compl_defer_select_destruct(CompletionWindow *window);
149 * Function used by GTK to find the string data to be used for completion.
150 * \param data Pointer to data being processed.
152 static gchar *completion_func(gpointer data)
154 cm_return_val_if_fail(data != NULL, NULL);
156 return ((completion_entry *)data)->string;
160 * Initialize all completion index data.
162 static void init_all(void)
164 g_completion = g_completion_new(completion_func);
165 cm_return_if_fail(g_completion != NULL);
168 static void free_all_addresses(void)
173 walk = g_address_list;
174 for (; walk != NULL; walk = g_list_next(walk)) {
175 address_entry *ae = (address_entry *) walk->data;
178 g_list_free(ae->grp_emails);
181 g_list_free(g_address_list);
182 g_address_list = NULL;
183 if (_groupAddresses_)
184 g_hash_table_destroy(_groupAddresses_);
185 _groupAddresses_ = NULL;
188 static void clear_completion_cache(void);
189 static void free_completion_list(void)
192 if (!g_completion_list)
195 clear_completion_cache();
197 g_completion_clear_items(g_completion);
199 walk = g_list_first(g_completion_list);
200 for (; walk != NULL; walk = g_list_next(walk)) {
201 completion_entry *ce = (completion_entry *) walk->data;
205 g_list_free(g_completion_list);
206 g_completion_list = NULL;
209 * Free up all completion index data.
211 static void free_all(void)
213 free_completion_list();
214 free_all_addresses();
215 g_completion_free(g_completion);
220 * Append specified address entry to the index.
221 * \param str Index string value.
222 * \param ae Entry containing address data.
224 void addr_compl_add_address1(const char *str, address_entry *ae)
226 completion_entry *ce1;
227 ce1 = g_new0(completion_entry, 1),
228 /* GCompletion list is case sensitive */
229 ce1->string = g_utf8_strdown(str, -1);
232 g_completion_list = g_list_prepend(g_completion_list, ce1);
236 * Adds address to the completion list. This function looks complicated, but
237 * it's only allocation checks. Each value will be included in the index.
238 * \param name Recipient name.
239 * \param address EMail address.
240 * \param alias Alias to append.
241 * \param grp_emails the emails in case of a group. List should be freed later,
242 * but not its strings
243 * \return <code>0</code> if entry appended successfully, or <code>-1</code>
246 static gint add_address(const gchar *name, const gchar *address,
247 const gchar *nick, const gchar *alias, GList *grp_emails)
250 gboolean is_group = FALSE;
252 if (!name || !address) {
253 if (!address && !nick && !alias && grp_emails) {
259 ae = g_new0(address_entry, 1);
261 cm_return_val_if_fail(ae != NULL, -1);
263 ae->name = g_strdup(name);
264 ae->address = g_strdup(address);
265 ae->grp_emails = grp_emails;
266 g_address_list = g_list_prepend(g_address_list, ae);
268 addr_compl_add_address1(name, ae);
269 if (address != NULL && *address != '\0')
270 addr_compl_add_address1(address, ae);
272 if (nick != NULL && *nick != '\0')
273 addr_compl_add_address1(nick, ae);
275 if ( alias != NULL && *alias != '\0') {
276 addr_compl_add_address1(alias, ae);
283 * Read address book, creating all entries in the completion index.
285 static void read_address_book(gchar *folderpath) {
286 free_all_addresses();
287 free_completion_list();
289 addrindex_load_completion( add_address, folderpath );
291 /* plugins may hook in here to modify/extend the completion list */
292 hooks_invoke(ADDDRESS_COMPLETION_BUILD_ADDRESS_LIST_HOOKLIST, &g_address_list);
294 g_address_list = g_list_reverse(g_address_list);
295 g_completion_list = g_list_reverse(g_completion_list);
296 /* merge the completion entry list into g_completion */
297 if (g_completion_list) {
298 g_completion_add_items(g_completion, g_completion_list);
299 if (debug_get_mode())
300 debug_print("read %d items in %s\n",
301 g_list_length(g_completion_list),
302 folderpath?folderpath:"(null)");
307 * Test whether there is a completion pending.
308 * \return <code>TRUE</code> if pending.
310 static gboolean is_completion_pending(void)
312 /* check if completion pending, i.e. we might satisfy a request for the next
313 * or previous address */
314 return g_completion_count;
318 * Clear the completion cache.
320 static void clear_completion_cache(void)
322 if (is_completion_pending()) {
323 g_free(g_completion_prefix);
325 if (g_completion_addresses) {
326 g_slist_free(g_completion_addresses);
327 g_completion_addresses = NULL;
330 g_completion_count = g_completion_next = 0;
335 * Prepare completion index. This function should be called prior to attempting
336 * address completion.
337 * \return The number of addresses in the completion list.
339 gint start_address_completion(gchar *folderpath)
341 gboolean different_book = FALSE;
342 clear_completion_cache();
344 if (strcmp2(completion_folder_path,folderpath))
345 different_book = TRUE;
347 g_free(completion_folder_path);
348 if (folderpath != NULL)
349 completion_folder_path = g_strdup(folderpath);
351 completion_folder_path = NULL;
355 /* open the address book */
356 read_address_book(folderpath);
357 } else if (different_book)
358 read_address_book(folderpath);
361 debug_print("start_address_completion(%s) ref count %d\n",
362 folderpath?folderpath:"(null)", g_ref_count);
364 return g_list_length(g_completion_list);
368 * Retrieve a possible address (or a part) from an entry box. To make life
369 * easier, we only look at the last valid address component; address
370 * completion only works at the last string component in the entry box.
372 * \param entry Address entry field.
373 * \param start_pos Address of start position of address.
374 * \return Possible address.
376 static gchar *get_address_from_edit(GtkEntry *entry, gint *start_pos)
378 const gchar *edit_text, *p;
380 gboolean in_quote = FALSE;
381 gboolean in_bracket = FALSE;
384 edit_text = gtk_entry_get_text(entry);
385 if (edit_text == NULL) return NULL;
387 cur_pos = gtk_editable_get_position(GTK_EDITABLE(entry));
389 /* scan for a separator. doesn't matter if walk points at null byte. */
390 for (p = g_utf8_offset_to_pointer(edit_text, cur_pos);
392 p = g_utf8_prev_char(p)) {
395 } else if (!in_quote) {
396 if (!in_bracket && *p == ',') {
398 } else if (*p == '<')
405 /* have something valid */
406 if (g_utf8_strlen(p, -1) == 0)
409 #define IS_VALID_CHAR(x) \
410 (g_ascii_isalnum(x) || (x) == '"' || (x) == '<' || (((unsigned char)(x)) > 0x7f))
412 /* now scan back until we hit a valid character */
413 for (; *p && !IS_VALID_CHAR(*p); p = g_utf8_next_char(p))
418 if (g_utf8_strlen(p, -1) == 0)
421 if (start_pos) *start_pos = g_utf8_pointer_to_offset(edit_text, p);
428 static gchar *get_complete_address_from_name_email(const gchar *name, const gchar *email)
430 gchar *address = NULL;
431 if (!name || name[0] == '\0')
432 address = g_strdup_printf("<%s>", email);
433 else if (strchr_with_skip_quote(name, '"', ','))
434 address = g_strdup_printf
435 ("\"%s\" <%s>", name, email);
437 address = g_strdup_printf
438 ("%s <%s>", name, email);
443 * Replace an incompleted address with a completed one.
444 * \param entry Address entry field.
445 * \param newtext New text.
446 * \param start_pos Insertion point in entry field.
448 static void replace_address_in_edit(GtkEntry *entry, const gchar *newtext,
449 gint start_pos, gboolean is_group, GList *grp_emails)
451 if (!newtext) return;
452 gtk_editable_delete_text(GTK_EDITABLE(entry), start_pos, -1);
454 gtk_editable_insert_text(GTK_EDITABLE(entry), newtext, strlen(newtext),
457 gchar *addresses = NULL;
458 GList *cur = grp_emails;
459 for (; cur; cur = cur->next) {
461 ItemEMail *email = (ItemEMail *)cur->data;
462 ItemPerson *person = ( ItemPerson * ) ADDRITEM_PARENT(email);
464 gchar *addr = get_complete_address_from_name_email(
465 ADDRITEM_NAME(person), email->address);
467 tmp = g_strdup_printf("%s, %s", addresses, addr);
469 tmp = g_strdup_printf("%s", addr);
474 gtk_editable_insert_text(GTK_EDITABLE(entry), addresses, strlen(addresses),
478 gtk_editable_set_position(GTK_EDITABLE(entry), -1);
482 * Attempt to complete an address, and returns the number of addresses found.
483 * Use <code>get_complete_address()</code> to get an entry from the index.
485 * \param str Search string to find.
486 * \return Zero if no match was found, otherwise the number of addresses; the
487 * original prefix (search string) will appear at index 0.
489 guint complete_address(const gchar *str)
491 GList *result = NULL;
495 completion_entry *ce = NULL;
497 cm_return_val_if_fail(str != NULL, 0);
499 /* g_completion is case sensitive */
500 d = g_utf8_strdown(str, -1);
502 clear_completion_cache();
503 g_completion_prefix = g_strdup(str);
505 result = g_completion_complete(g_completion, d, NULL);
507 count = g_list_length(result);
509 /* create list with unique addresses */
510 for (cpl = 0, result = g_list_first(result);
512 result = g_list_next(result)) {
513 ce = (completion_entry *)(result->data);
514 if (NULL == g_slist_find(g_completion_addresses,
517 g_completion_addresses =
518 g_slist_append(g_completion_addresses,
522 count = cpl + 1; /* index 0 is the original prefix */
523 g_completion_next = 1; /* we start at the first completed one */
525 g_free(g_completion_prefix);
526 g_completion_prefix = NULL;
529 g_completion_count = count;
537 * complete_matches_found() returns the number of matched addresses according
538 * to the completion mechanism. Unlike complete_address(), the returned value
539 * doesn't count str itself. If there's no match, it returns 0.
540 * To get a list of completion matches, see complete_address() instead.
542 guint complete_matches_found(const gchar *str)
544 GList *result = NULL;
547 cm_return_val_if_fail(str != NULL, 0);
549 /* g_completion is case sensitive */
550 d = g_utf8_strdown(str, -1);
552 clear_completion_cache();
553 g_completion_prefix = g_strdup(str);
555 result = g_completion_complete(g_completion, d, NULL);
557 g_free(g_completion_prefix);
560 return g_list_length(result);
564 * Return a complete address from the index.
565 * \param index Index of entry that was found (by the previous call to
566 * <code>complete_address()</code>
567 * \return Completed address string; this should be freed when done.
569 gchar *get_complete_address(gint index)
571 const address_entry *p;
572 gchar *address = NULL;
574 if (index < g_completion_count) {
576 address = g_strdup(g_completion_prefix);
578 /* get something from the unique addresses */
579 p = (address_entry *)g_slist_nth_data
580 (g_completion_addresses, index - 1);
581 if (p != NULL && p->address != NULL) {
582 address = get_complete_address_from_name_email(p->name, p->address);
583 } else if (p != NULL && p->address == NULL && p->name != NULL) {
585 address = g_strdup_printf("%s (%s) <!--___group___-->", p->name, _("Group"));
586 if (!_groupAddresses_) {
587 _groupAddresses_ = g_hash_table_new(NULL, g_direct_equal);
589 if (!g_hash_table_lookup(_groupAddresses_, GINT_TO_POINTER(g_str_hash(address)))) {
590 g_hash_table_insert(_groupAddresses_, GINT_TO_POINTER(g_str_hash(address)), p->grp_emails);
601 * Return the next complete address match from the completion index.
602 * \return Completed address string; this should be freed when done.
604 static gchar *get_next_complete_address(void)
606 if (is_completion_pending()) {
609 res = get_complete_address(g_completion_next);
610 g_completion_next += 1;
611 if (g_completion_next >= g_completion_count)
612 g_completion_next = 0;
620 * Return a count of the completed matches in the completion index.
621 * \return Number of matched entries.
623 static guint get_completion_count(void)
625 if (is_completion_pending())
626 return g_completion_count;
632 * Invalidate address completion index. This function should be called whenever
633 * the address book changes. This forces data to be read into the completion
635 * \return Number of entries in index.
637 gint invalidate_address_completion(void)
640 /* simply the same as start_address_completion() */
641 debug_print("Invalidation request for address completion\n");
642 read_address_book(completion_folder_path);
643 clear_completion_cache();
646 return g_list_length(g_completion_list);
650 * Finished with completion index. This function should be called after
651 * matching addresses.
652 * \return Reference count.
654 gint end_address_completion(void)
656 gboolean different_folder = FALSE;
657 clear_completion_cache();
659 /* reset the folderpath to NULL */
660 if (completion_folder_path) {
661 g_free(completion_folder_path);
662 completion_folder_path = NULL;
663 different_folder = TRUE;
665 if (0 == --g_ref_count)
668 debug_print("end_address_completion ref count %d\n", g_ref_count);
669 if (g_ref_count && different_folder) {
670 debug_print("still ref'd, different folder\n");
671 invalidate_address_completion();
680 static CompletionWindow *_compWindow_ = NULL;
683 * Mutex to protect callback from multiple threads.
685 static pthread_mutex_t _completionMutex_ = PTHREAD_MUTEX_INITIALIZER;
688 * Completion queue list.
690 static GList *_displayQueue_ = NULL;
694 static gint _queryID_ = 0;
697 * Completion idle ID.
699 static guint _completionIdleID_ = 0;
702 * address completion entry ui. the ui (completion list was inspired by galeon's
703 * auto completion list). remaining things powered by claws's completion engine.
706 #define ENTRY_DATA_TAB_HOOK "tab_hook" /* used to lookup entry */
707 #define ENTRY_DATA_ALLOW_COMMAS "allowcommas" /* used to know whether to present groups */
709 static void address_completion_mainwindow_set_focus (GtkWindow *window,
712 static gboolean address_completion_entry_key_pressed (GtkEntry *entry,
715 static gboolean address_completion_complete_address_in_entry
718 static void address_completion_create_completion_window (GtkEntry *entry);
720 static gboolean completion_window_button_press
722 GdkEventButton *event,
723 CompletionWindow *compWin );
725 static gboolean completion_window_key_press
728 CompletionWindow *compWin );
729 static void address_completion_create_completion_window( GtkEntry *entry_ );
732 * Create a completion window object.
733 * \return Initialized completion window.
735 static CompletionWindow *addrcompl_create_window( void ) {
736 CompletionWindow *cw;
738 cw = g_new0( CompletionWindow, 1 );
740 cw->searchTerm = NULL;
743 cw->list_view = NULL;
744 cw->in_mouse = FALSE;
745 cw->destroying = FALSE;
751 * Destroy completion window.
752 * \param cw Window to destroy.
754 static void addrcompl_destroy_window( CompletionWindow *cw ) {
755 /* Stop all searches currently in progress */
756 addrindex_stop_search( _queryID_ );
758 /* Remove idler function... or application may not terminate */
759 if( _completionIdleID_ != 0 ) {
760 g_source_remove( _completionIdleID_ );
761 _completionIdleID_ = 0;
764 /* Now destroy window */
766 /* Clear references to widgets */
768 cw->list_view = NULL;
772 gtk_widget_hide( cw->window );
773 gtk_widget_destroy( cw->window );
776 cw->destroying = FALSE;
777 cw->in_mouse = FALSE;
783 * Free up completion window.
784 * \param cw Window to free.
786 static void addrcompl_free_window( CompletionWindow *cw ) {
788 addrcompl_destroy_window( cw );
790 g_free( cw->searchTerm );
791 cw->searchTerm = NULL;
793 /* Clear references */
802 * Advance selection to previous/next item in list.
803 * \param list_view List to process.
804 * \param forward Set to <i>TRUE</i> to select next or <i>FALSE</i> for
807 static void completion_window_advance_selection(GtkTreeView *list_view, gboolean forward)
809 GtkTreeSelection *selection;
813 cm_return_if_fail(list_view != NULL);
815 selection = gtk_tree_view_get_selection(list_view);
816 if (!gtk_tree_selection_get_selected(selection, &model, &iter))
820 forward = gtk_tree_model_iter_next(model, &iter);
822 gtk_tree_selection_select_iter(selection, &iter);
826 prev = gtk_tree_model_get_path(model, &iter);
830 if (gtk_tree_path_prev(prev))
831 gtk_tree_selection_select_path(selection, prev);
833 gtk_tree_path_free(prev);
838 * Resize window to accommodate maximum number of address entries.
839 * \param cw Completion window.
841 static void addrcompl_resize_window( CompletionWindow *cw ) {
843 gint x, y, width, height, depth;
845 /* Get current geometry of window */
846 gdk_window_get_geometry( gtk_widget_get_window( cw->window ), &x, &y, &width, &height, &depth );
848 /* simple _hide breaks size requisition !? */
849 gtk_widget_hide_all( cw->window );
850 gtk_widget_show_all( cw->window );
851 gtk_widget_size_request( cw->list_view, &r );
852 printf("%d + %d < %d\n", y, r.height, gdk_screen_height());
853 /* Adjust window height to available screen space */
854 if( y + r.height > gdk_screen_height())
855 r.height = gdk_screen_height() - y;
857 gtk_widget_set_size_request(cw->window, width, r.height);
859 gdk_pointer_grab(gtk_widget_get_window(cw->window), TRUE,
860 GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK |
861 GDK_BUTTON_RELEASE_MASK,
862 NULL, NULL, GDK_CURRENT_TIME);
863 gdk_keyboard_grab(gtk_widget_get_window(cw->window), FALSE, GDK_CURRENT_TIME);
864 gtk_grab_add(cw->window);
868 static GdkPixbuf *group_pixbuf = NULL;
869 static GdkPixbuf *email_pixbuf = NULL;
872 * Add an address the completion window address list.
873 * \param cw Completion window.
874 * \param address Address to add.
876 static void addrcompl_add_entry( CompletionWindow *cw, gchar *address ) {
879 GtkTreeSelection *selection;
880 gboolean is_group = FALSE;
881 GList *grp_emails = NULL;
882 store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(cw->list_view)));
886 stock_pixbuf_gdk(cw->list_view, STOCK_PIXMAP_ADDR_TWO, &group_pixbuf);
887 g_object_ref(G_OBJECT(group_pixbuf));
890 stock_pixbuf_gdk(cw->list_view, STOCK_PIXMAP_ADDR_ONE, &email_pixbuf);
891 g_object_ref(G_OBJECT(email_pixbuf));
893 /* g_print( "\t\tAdding :%s\n", address ); */
894 if (strstr(address, " <!--___group___-->")) {
896 if (_groupAddresses_)
897 grp_emails = g_hash_table_lookup(_groupAddresses_, GINT_TO_POINTER(g_str_hash(address)));
898 *(strstr(address, " <!--___group___-->")) = '\0';
899 pixbuf = group_pixbuf;
900 } else if (strchr(address, '@') && strchr(address, '<') &&
901 strchr(address, '>')) {
902 pixbuf = email_pixbuf;
906 if (is_group && !_allowCommas_)
908 gtk_list_store_append(store, &iter);
909 gtk_list_store_set(store, &iter,
910 ADDR_COMPL_ICON, pixbuf,
911 ADDR_COMPL_ADDRESS, address,
912 ADDR_COMPL_ISGROUP, is_group,
913 ADDR_COMPL_GROUPLIST, grp_emails,
918 addrcompl_resize_window( cw );
919 gtk_grab_add( cw->window );
921 selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(cw->list_view));
922 gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store), &iter);
924 if( cw->listCount == 1 ) {
925 /* Select first row for now */
926 gtk_tree_selection_select_iter(selection, &iter);
929 else if( cw->listCount == 2 ) {
930 gtk_tree_model_iter_next(GTK_TREE_MODEL(store), &iter);
931 /* Move off first row */
932 gtk_tree_selection_select_iter(selection, &iter);
938 * Completion idle function. This function is called by the main (UI) thread
939 * during UI idle time while an address search is in progress. Items from the
940 * display queue are processed and appended to the address list.
942 * \param data Target completion window to receive email addresses.
943 * \return <i>TRUE</i> to ensure that idle event do not get ignored.
945 static gboolean addrcompl_idle( gpointer data ) {
949 /* Process all entries in display queue */
950 pthread_mutex_lock( & _completionMutex_ );
951 if( _displayQueue_ ) {
952 node = _displayQueue_;
954 address = node->data;
955 /* g_print( "address ::: %s :::\n", address ); */
956 addrcompl_add_entry( _compWindow_, address );
958 node = g_list_next( node );
960 g_list_free( _displayQueue_ );
961 _displayQueue_ = NULL;
963 pthread_mutex_unlock( & _completionMutex_ );
970 * Callback entry point. The background thread (if any) appends the address
971 * list to the display queue.
972 * \param sender Sender of query.
973 * \param queryID Query ID of search request.
974 * \param listEMail List of zero of more email objects that met search
976 * \param data Query data.
978 static gint addrcompl_callback_entry(
979 gpointer sender, gint queryID, GList *listEMail, gpointer data )
984 /* g_print( "addrcompl_callback_entry::queryID=%d\n", queryID ); */
985 pthread_mutex_lock( & _completionMutex_ );
986 if( queryID == _queryID_ ) {
987 /* Append contents to end of display queue */
990 ItemEMail *email = node->data;
992 address = addritem_format_email( email );
993 /* g_print( "\temail/address ::%s::\n", address ); */
994 _displayQueue_ = g_list_append( _displayQueue_, address );
995 node = g_list_next( node );
998 g_list_free( listEMail );
999 pthread_mutex_unlock( & _completionMutex_ );
1005 * Clear the display queue.
1007 static void addrcompl_clear_queue( void ) {
1008 /* Clear out display queue */
1009 pthread_mutex_lock( & _completionMutex_ );
1011 g_list_free( _displayQueue_ );
1012 _displayQueue_ = NULL;
1014 pthread_mutex_unlock( & _completionMutex_ );
1018 * Add a single address entry into the display queue.
1019 * \param address Address to append.
1021 static void addrcompl_add_queue( gchar *address ) {
1022 pthread_mutex_lock( & _completionMutex_ );
1023 _displayQueue_ = g_list_append( _displayQueue_, address );
1024 pthread_mutex_unlock( & _completionMutex_ );
1028 * Load list with entries from local completion index.
1030 static void addrcompl_load_local( void ) {
1033 for (count = 0; count < get_completion_count(); count++) {
1036 address = get_complete_address( count );
1037 /* g_print( "\taddress ::%s::\n", address ); */
1039 /* Append contents to end of display queue */
1040 addrcompl_add_queue( address );
1047 static void addrcompl_start_search( void ) {
1050 searchTerm = g_strdup( _compWindow_->searchTerm );
1052 /* Setup the search */
1053 _queryID_ = addrindex_setup_search(
1054 searchTerm, NULL, addrcompl_callback_entry );
1055 g_free( searchTerm );
1056 /* g_print( "addrcompl_start_search::queryID=%d\n", _queryID_ ); */
1058 /* Load local stuff */
1059 addrcompl_load_local();
1061 /* Sit back and wait until something happens */
1062 _completionIdleID_ =
1063 g_idle_add( (GSourceFunc) addrcompl_idle, NULL );
1064 /* g_print( "addrindex_start_search::queryID=%d\n", _queryID_ ); */
1066 addrindex_start_search( _queryID_ );
1070 * Apply the current selection in the list to the entry field. Focus is also
1071 * moved to the next widget so that Tab key works correctly.
1072 * \param list_view List to process.
1073 * \param entry Address entry field.
1074 * \param move_focus Move focus to the next widget ?
1076 static void completion_window_apply_selection(GtkTreeView *list_view,
1078 gboolean move_focus)
1080 gchar *address = NULL, *text = NULL;
1083 GtkTreeSelection *selection;
1084 GtkTreeModel *model;
1086 gboolean is_group = FALSE;
1087 cm_return_if_fail(list_view != NULL);
1088 cm_return_if_fail(entry != NULL);
1089 GList *grp_emails = NULL;
1091 selection = gtk_tree_view_get_selection(list_view);
1092 if (! gtk_tree_selection_get_selected(selection, &model, &iter))
1095 /* First remove the idler */
1096 if( _completionIdleID_ != 0 ) {
1097 g_source_remove( _completionIdleID_ );
1098 _completionIdleID_ = 0;
1101 /* Process selected item */
1102 gtk_tree_model_get(model, &iter, ADDR_COMPL_ADDRESS, &text,
1103 ADDR_COMPL_ISGROUP, &is_group,
1104 ADDR_COMPL_GROUPLIST, &grp_emails,
1107 address = get_address_from_edit(entry, &cursor_pos);
1109 replace_address_in_edit(entry, text, cursor_pos, is_group, grp_emails);
1112 /* Move focus to next widget */
1113 parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1114 if( parent && move_focus) {
1115 gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1120 * Start address completion. Should be called when creating the main window
1121 * containing address completion entries.
1122 * \param mainwindow Main window.
1124 void address_completion_start(GtkWidget *mainwindow)
1126 start_address_completion(NULL);
1128 /* register focus change hook */
1129 g_signal_connect(G_OBJECT(mainwindow), "set_focus",
1130 G_CALLBACK(address_completion_mainwindow_set_focus),
1135 * Need unique data to make unregistering signal handler possible for the auto
1138 #define COMPLETION_UNIQUE_DATA (GINT_TO_POINTER(0xfeefaa))
1141 * Register specified entry widget for address completion.
1142 * \param entry Address entry field.
1144 void address_completion_register_entry(GtkEntry *entry, gboolean allow_commas)
1146 cm_return_if_fail(entry != NULL);
1147 cm_return_if_fail(GTK_IS_ENTRY(entry));
1149 /* add hooked property */
1150 g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, entry);
1151 g_object_set_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS, GINT_TO_POINTER(allow_commas));
1153 /* add keypress event */
1154 g_signal_connect_closure
1155 (G_OBJECT(entry), "key_press_event",
1156 g_cclosure_new(G_CALLBACK(address_completion_entry_key_pressed),
1157 COMPLETION_UNIQUE_DATA,
1163 * Unregister specified entry widget from address completion operations.
1164 * \param entry Address entry field.
1166 void address_completion_unregister_entry(GtkEntry *entry)
1170 cm_return_if_fail(entry != NULL);
1171 cm_return_if_fail(GTK_IS_ENTRY(entry));
1173 entry_obj = g_object_get_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK);
1174 cm_return_if_fail(entry_obj);
1175 cm_return_if_fail(G_OBJECT(entry_obj) == G_OBJECT(entry));
1177 /* has the hooked property? */
1178 g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, NULL);
1180 /* remove the hook */
1181 g_signal_handlers_disconnect_by_func(G_OBJECT(entry),
1182 G_CALLBACK(address_completion_entry_key_pressed),
1183 COMPLETION_UNIQUE_DATA);
1187 * End address completion. Should be called when main window with address
1188 * completion entries terminates. NOTE: this function assumes that it is
1189 * called upon destruction of the window.
1190 * \param mainwindow Main window.
1192 void address_completion_end(GtkWidget *mainwindow)
1194 /* if address_completion_end() is really called on closing the window,
1195 * we don't need to unregister the set_focus_cb */
1196 end_address_completion();
1199 /* if focus changes to another entry, then clear completion cache */
1200 static void address_completion_mainwindow_set_focus(GtkWindow *window,
1205 if (widget && GTK_IS_ENTRY(widget) &&
1206 g_object_get_data(G_OBJECT(widget), ENTRY_DATA_TAB_HOOK)) {
1207 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), ENTRY_DATA_ALLOW_COMMAS));
1208 clear_completion_cache();
1213 * Listener that watches for tab or other keystroke in address entry field.
1214 * \param entry Address entry field.
1215 * \param ev Event object.
1216 * \param data User data.
1217 * \return <i>TRUE</i>.
1219 static gboolean address_completion_entry_key_pressed(GtkEntry *entry,
1223 if (ev->keyval == GDK_KEY_Tab) {
1224 addrcompl_clear_queue();
1225 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS));
1226 if( address_completion_complete_address_in_entry( entry, TRUE ) ) {
1227 /* route a void character to the default handler */
1228 /* this is a dirty hack; we're actually changing a key
1229 * reported by the system. */
1230 ev->keyval = GDK_KEY_AudibleBell_Enable;
1231 ev->state &= ~GDK_SHIFT_MASK;
1234 address_completion_create_completion_window(entry);
1236 /* Start remote queries */
1237 addrcompl_start_search();
1244 } else if (ev->keyval == GDK_KEY_Shift_L
1245 || ev->keyval == GDK_KEY_Shift_R
1246 || ev->keyval == GDK_KEY_Control_L
1247 || ev->keyval == GDK_KEY_Control_R
1248 || ev->keyval == GDK_KEY_Caps_Lock
1249 || ev->keyval == GDK_KEY_Shift_Lock
1250 || ev->keyval == GDK_KEY_Meta_L
1251 || ev->keyval == GDK_KEY_Meta_R
1252 || ev->keyval == GDK_KEY_Alt_L
1253 || ev->keyval == GDK_KEY_Alt_R) {
1254 /* these buttons should not clear the cache... */
1256 clear_completion_cache();
1261 * Initialize search term for address completion.
1262 * \param entry Address entry field.
1264 static gboolean address_completion_complete_address_in_entry(GtkEntry *entry,
1267 gint ncount, cursor_pos;
1268 gchar *searchTerm, *new = NULL;
1270 cm_return_val_if_fail(entry != NULL, FALSE);
1272 if (!gtk_widget_has_focus(GTK_WIDGET(entry))) return FALSE;
1274 /* get an address component from the cursor */
1275 searchTerm = get_address_from_edit( entry, &cursor_pos );
1276 if( ! searchTerm ) return FALSE;
1277 /* g_print( "search for :::%s:::\n", searchTerm ); */
1279 /* Clear any existing search */
1280 g_free( _compWindow_->searchTerm );
1281 _compWindow_->searchTerm = g_strdup( searchTerm );
1283 /* Perform search on local completion index */
1284 ncount = complete_address( searchTerm );
1286 new = get_next_complete_address();
1289 #if (!defined(USE_LDAP) && !defined(GENERIC_UMPC))
1290 /* Select the address if there is only one match */
1292 /* Display selected address in entry field */
1293 gchar *addr = get_complete_address(1);
1294 if (addr && !strstr(addr, " <!--___group___-->")) {
1295 replace_address_in_edit(entry, addr, cursor_pos, FALSE, NULL);
1296 /* Discard the window */
1297 clear_completion_cache();
1301 /* Make sure that drop-down appears uniform! */
1305 addrcompl_add_queue( g_strdup( searchTerm ) );
1307 g_free( searchTerm );
1313 * Create new address completion window for specified entry.
1314 * \param entry_ Entry widget to associate with window.
1316 static void address_completion_create_completion_window( GtkEntry *entry_ )
1318 gint x, y, height, width, depth;
1319 GtkWidget *scroll, *list_view;
1322 GtkWidget *entry = GTK_WIDGET(entry_);
1325 /* Create new window and list */
1326 window = gtk_window_new(GTK_WINDOW_POPUP);
1327 list_view = addr_compl_list_view_create(_compWindow_);
1329 /* Destroy any existing window */
1330 addrcompl_destroy_window( _compWindow_ );
1332 /* Create new object */
1333 _compWindow_->window = window;
1334 _compWindow_->entry = entry;
1335 _compWindow_->list_view = list_view;
1336 _compWindow_->listCount = 0;
1337 _compWindow_->in_mouse = FALSE;
1339 scroll = gtk_scrolled_window_new(NULL, NULL);
1340 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
1341 GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
1342 gtk_container_add(GTK_CONTAINER(window), scroll);
1343 gtk_container_add(GTK_CONTAINER(scroll), list_view);
1344 gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll),
1346 /* Use entry widget to create initial window */
1347 gdkwin = gtk_widget_get_window(entry),
1348 gdk_window_get_geometry(gdkwin, &x, &y, &width, &height, &depth);
1349 gdk_window_get_origin (gdkwin, &x, &y);
1351 gtk_window_move(GTK_WINDOW(window), x, y);
1353 /* Resize window to fit initial (empty) address list */
1354 gtk_widget_size_request( list_view, &r );
1355 gtk_widget_set_size_request( window, width, r.height );
1356 gtk_widget_show_all( window );
1357 gtk_widget_size_request( list_view, &r );
1359 /* Setup handlers */
1360 g_signal_connect(G_OBJECT(list_view), "button_press_event",
1361 G_CALLBACK(list_view_button_press),
1364 g_signal_connect(G_OBJECT(list_view), "button_release_event",
1365 G_CALLBACK(list_view_button_release),
1368 g_signal_connect(G_OBJECT(window),
1369 "button-press-event",
1370 G_CALLBACK(completion_window_button_press),
1372 g_signal_connect(G_OBJECT(window),
1374 G_CALLBACK(completion_window_key_press),
1376 gdk_pointer_grab(gtk_widget_get_window(window), TRUE,
1377 GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK |
1378 GDK_BUTTON_RELEASE_MASK,
1379 NULL, NULL, GDK_CURRENT_TIME);
1380 gdk_keyboard_grab(gtk_widget_get_window(window), FALSE, GDK_CURRENT_TIME);
1381 gtk_grab_add( window );
1385 * Respond to button press in completion window. Check if mouse click is
1386 * anywhere outside the completion window. In that case the completion
1387 * window is destroyed, and the original searchTerm is restored.
1389 * \param widget Window object.
1390 * \param event Event.
1391 * \param compWin Reference to completion window.
1393 static gboolean completion_window_button_press(GtkWidget *widget,
1394 GdkEventButton *event,
1395 CompletionWindow *compWin )
1397 GtkWidget *event_widget, *entry;
1400 gboolean restore = TRUE;
1402 cm_return_val_if_fail(compWin != NULL, FALSE);
1404 entry = compWin->entry;
1405 cm_return_val_if_fail(entry != NULL, FALSE);
1407 /* Test where mouse was clicked */
1408 event_widget = gtk_get_event_widget((GdkEvent *)event);
1409 if (event_widget != widget) {
1410 while (event_widget) {
1411 if (event_widget == widget)
1413 else if (event_widget == entry) {
1417 event_widget = gtk_widget_get_parent(event_widget);
1422 /* Clicked outside of completion window - restore */
1423 searchTerm = _compWindow_->searchTerm;
1424 g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1425 replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos, FALSE, NULL);
1428 clear_completion_cache();
1429 addrcompl_destroy_window( _compWindow_ );
1435 * Respond to key press in completion window.
1436 * \param widget Window object.
1437 * \param event Event.
1438 * \param compWind Reference to completion window.
1440 static gboolean completion_window_key_press(GtkWidget *widget,
1442 CompletionWindow *compWin )
1444 GdkEventKey tmp_event;
1448 GtkWidget *list_view;
1450 cm_return_val_if_fail(compWin != NULL, FALSE);
1452 entry = compWin->entry;
1453 list_view = compWin->list_view;
1454 cm_return_val_if_fail(entry != NULL, FALSE);
1456 /* allow keyboard navigation in the alternatives tree view */
1457 if (event->keyval == GDK_KEY_Up || event->keyval == GDK_KEY_Down ||
1458 event->keyval == GDK_KEY_Page_Up || event->keyval == GDK_KEY_Page_Down) {
1459 completion_window_advance_selection
1460 (GTK_TREE_VIEW(list_view),
1461 event->keyval == GDK_KEY_Down ||
1462 event->keyval == GDK_KEY_Page_Down ? TRUE : FALSE);
1466 /* make tab move to next field */
1467 if( event->keyval == GDK_KEY_Tab ) {
1468 /* Reference to parent */
1469 parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1471 /* Discard the window */
1472 clear_completion_cache();
1473 addrcompl_destroy_window( _compWindow_ );
1475 /* Move focus to next widget */
1477 gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1482 /* make backtab move to previous field */
1483 if( event->keyval == GDK_KEY_ISO_Left_Tab ) {
1484 /* Reference to parent */
1485 parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1487 /* Discard the window */
1488 clear_completion_cache();
1489 addrcompl_destroy_window( _compWindow_ );
1491 /* Move focus to previous widget */
1493 gtk_widget_child_focus( parent, GTK_DIR_TAB_BACKWARD );
1497 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS));
1499 /* look for presses that accept the selection */
1500 if (event->keyval == GDK_KEY_Return || event->keyval == GDK_KEY_space ||
1501 event->keyval == GDK_KEY_KP_Enter ||
1502 (_allowCommas_ && event->keyval == GDK_KEY_comma)) {
1503 /* User selected address with a key press */
1505 /* Display selected address in entry field */
1506 completion_window_apply_selection(
1507 GTK_TREE_VIEW(list_view), GTK_ENTRY(entry),
1508 event->keyval != GDK_KEY_comma);
1510 if (event->keyval == GDK_KEY_comma) {
1511 gint pos = gtk_editable_get_position(GTK_EDITABLE(entry));
1512 gtk_editable_insert_text(GTK_EDITABLE(entry), ", ", 2, &pos);
1513 gtk_editable_set_position(GTK_EDITABLE(entry), pos + 1);
1516 /* Discard the window */
1517 clear_completion_cache();
1518 addrcompl_destroy_window( _compWindow_ );
1522 /* key state keys should never be handled */
1523 if (event->keyval == GDK_KEY_Shift_L
1524 || event->keyval == GDK_KEY_Shift_R
1525 || event->keyval == GDK_KEY_Control_L
1526 || event->keyval == GDK_KEY_Control_R
1527 || event->keyval == GDK_KEY_Caps_Lock
1528 || event->keyval == GDK_KEY_Shift_Lock
1529 || event->keyval == GDK_KEY_Meta_L
1530 || event->keyval == GDK_KEY_Meta_R
1531 || event->keyval == GDK_KEY_Alt_L
1532 || event->keyval == GDK_KEY_Alt_R) {
1536 /* some other key, let's restore the searchTerm (orignal text) */
1537 searchTerm = _compWindow_->searchTerm;
1538 g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1539 replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos, FALSE, NULL);
1541 /* make sure anything we typed comes in the edit box */
1542 tmp_event.type = event->type;
1543 tmp_event.window = gtk_widget_get_window(GTK_WIDGET(entry));
1544 tmp_event.send_event = TRUE;
1545 tmp_event.time = event->time;
1546 tmp_event.state = event->state;
1547 tmp_event.keyval = event->keyval;
1548 tmp_event.length = event->length;
1549 tmp_event.string = event->string;
1550 gtk_widget_event(entry, (GdkEvent *)&tmp_event);
1552 /* and close the completion window */
1553 clear_completion_cache();
1554 addrcompl_destroy_window( _compWindow_ );
1560 * ============================================================================
1561 * Publically accessible functions.
1562 * ============================================================================
1566 * Setup completion object.
1568 void addrcompl_initialize( void ) {
1569 /* g_print( "addrcompl_initialize...\n" ); */
1570 if( ! _compWindow_ ) {
1571 _compWindow_ = addrcompl_create_window();
1574 _completionIdleID_ = 0;
1575 /* g_print( "addrcompl_initialize...done\n" ); */
1579 * Teardown completion object.
1581 void addrcompl_teardown( void ) {
1582 /* g_print( "addrcompl_teardown...\n" ); */
1583 addrcompl_free_window( _compWindow_ );
1584 _compWindow_ = NULL;
1585 if( _displayQueue_ ) {
1586 g_list_free( _displayQueue_ );
1588 _displayQueue_ = NULL;
1589 _completionIdleID_ = 0;
1590 /* g_print( "addrcompl_teardown...done\n" ); */
1594 * tree view functions
1597 static GtkListStore *addr_compl_create_store(void)
1599 return gtk_list_store_new(N_ADDR_COMPL_COLUMNS,
1607 static GtkWidget *addr_compl_list_view_create(CompletionWindow *window)
1609 GtkTreeView *list_view;
1610 GtkTreeSelection *selector;
1611 GtkTreeModel *model;
1613 model = GTK_TREE_MODEL(addr_compl_create_store());
1614 list_view = GTK_TREE_VIEW(gtk_tree_view_new_with_model(model));
1615 g_object_unref(model);
1617 gtk_tree_view_set_rules_hint(list_view, prefs_common.use_stripes_everywhere);
1618 gtk_tree_view_set_headers_visible(list_view, FALSE);
1620 selector = gtk_tree_view_get_selection(list_view);
1621 gtk_tree_selection_set_mode(selector, GTK_SELECTION_BROWSE);
1622 gtk_tree_selection_set_select_function(selector, addr_compl_selected,
1625 /* create the columns */
1626 addr_compl_create_list_view_columns(GTK_WIDGET(list_view));
1628 return GTK_WIDGET(list_view);
1631 static void addr_compl_create_list_view_columns(GtkWidget *list_view)
1633 GtkTreeViewColumn *column;
1634 GtkCellRenderer *renderer;
1636 renderer = gtk_cell_renderer_pixbuf_new();
1637 column = gtk_tree_view_column_new_with_attributes
1639 "pixbuf", ADDR_COMPL_ICON, NULL);
1640 gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);
1641 renderer = gtk_cell_renderer_text_new();
1642 column = gtk_tree_view_column_new_with_attributes
1643 ("", renderer, "text", ADDR_COMPL_ADDRESS, NULL);
1644 gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);
1647 static gboolean list_view_button_press(GtkWidget *widget, GdkEventButton *event,
1648 CompletionWindow *window)
1650 if (window && event && event->type == GDK_BUTTON_PRESS) {
1651 window->in_mouse = TRUE;
1656 static gboolean list_view_button_release(GtkWidget *widget, GdkEventButton *event,
1657 CompletionWindow *window)
1659 if (window && event && event->type == GDK_BUTTON_RELEASE) {
1660 window->in_mouse = FALSE;
1665 static gboolean addr_compl_selected(GtkTreeSelection *selector,
1666 GtkTreeModel *model,
1668 gboolean currently_selected,
1671 CompletionWindow *window = data;
1673 if (currently_selected)
1676 if (!window->in_mouse)
1679 /* XXX: select the entry and kill window later... select is called before
1680 * any other mouse events handlers including the tree view internal one;
1681 * not using a time out would result in a crash. if this doesn't work
1682 * safely, maybe we should set variables when receiving button presses
1683 * in the tree view. */
1684 if (!window->destroying) {
1685 window->destroying = TRUE;
1686 g_idle_add((GSourceFunc) addr_compl_defer_select_destruct, data);
1692 static gboolean addr_compl_defer_select_destruct(CompletionWindow *window)
1694 GtkEntry *entry = GTK_ENTRY(window->entry);
1696 completion_window_apply_selection(GTK_TREE_VIEW(window->list_view),
1699 clear_completion_cache();
1701 addrcompl_destroy_window(window);