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 );
853 /* Adjust window height to available screen space */
854 if( ( y + r.height ) > gdk_screen_height() ) {
855 gtk_window_set_resizable(GTK_WINDOW(cw->window), FALSE);
856 gtk_widget_set_size_request( cw->window, width, gdk_screen_height() - y );
858 gtk_widget_set_size_request(cw->window, width, r.height);
861 static GdkPixbuf *group_pixbuf = NULL;
862 static GdkPixbuf *email_pixbuf = NULL;
865 * Add an address the completion window address list.
866 * \param cw Completion window.
867 * \param address Address to add.
869 static void addrcompl_add_entry( CompletionWindow *cw, gchar *address ) {
872 GtkTreeSelection *selection;
873 gboolean is_group = FALSE;
874 GList *grp_emails = NULL;
875 store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(cw->list_view)));
879 stock_pixbuf_gdk(cw->list_view, STOCK_PIXMAP_ADDR_TWO, &group_pixbuf);
880 g_object_ref(G_OBJECT(group_pixbuf));
883 stock_pixbuf_gdk(cw->list_view, STOCK_PIXMAP_ADDR_ONE, &email_pixbuf);
884 g_object_ref(G_OBJECT(email_pixbuf));
886 /* g_print( "\t\tAdding :%s\n", address ); */
887 if (strstr(address, " <!--___group___-->")) {
889 if (_groupAddresses_)
890 grp_emails = g_hash_table_lookup(_groupAddresses_, GINT_TO_POINTER(g_str_hash(address)));
891 *(strstr(address, " <!--___group___-->")) = '\0';
892 pixbuf = group_pixbuf;
893 } else if (strchr(address, '@') && strchr(address, '<') &&
894 strchr(address, '>')) {
895 pixbuf = email_pixbuf;
899 if (is_group && !_allowCommas_)
901 gtk_list_store_append(store, &iter);
902 gtk_list_store_set(store, &iter,
903 ADDR_COMPL_ICON, pixbuf,
904 ADDR_COMPL_ADDRESS, address,
905 ADDR_COMPL_ISGROUP, is_group,
906 ADDR_COMPL_GROUPLIST, grp_emails,
911 addrcompl_resize_window( cw );
912 gtk_grab_add( cw->window );
914 selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(cw->list_view));
915 gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store), &iter);
917 if( cw->listCount == 1 ) {
918 /* Select first row for now */
919 gtk_tree_selection_select_iter(selection, &iter);
922 else if( cw->listCount == 2 ) {
923 gtk_tree_model_iter_next(GTK_TREE_MODEL(store), &iter);
924 /* Move off first row */
925 gtk_tree_selection_select_iter(selection, &iter);
931 * Completion idle function. This function is called by the main (UI) thread
932 * during UI idle time while an address search is in progress. Items from the
933 * display queue are processed and appended to the address list.
935 * \param data Target completion window to receive email addresses.
936 * \return <i>TRUE</i> to ensure that idle event do not get ignored.
938 static gboolean addrcompl_idle( gpointer data ) {
942 /* Process all entries in display queue */
943 pthread_mutex_lock( & _completionMutex_ );
944 if( _displayQueue_ ) {
945 node = _displayQueue_;
947 address = node->data;
948 /* g_print( "address ::: %s :::\n", address ); */
949 addrcompl_add_entry( _compWindow_, address );
951 node = g_list_next( node );
953 g_list_free( _displayQueue_ );
954 _displayQueue_ = NULL;
956 pthread_mutex_unlock( & _completionMutex_ );
963 * Callback entry point. The background thread (if any) appends the address
964 * list to the display queue.
965 * \param sender Sender of query.
966 * \param queryID Query ID of search request.
967 * \param listEMail List of zero of more email objects that met search
969 * \param data Query data.
971 static gint addrcompl_callback_entry(
972 gpointer sender, gint queryID, GList *listEMail, gpointer data )
977 /* g_print( "addrcompl_callback_entry::queryID=%d\n", queryID ); */
978 pthread_mutex_lock( & _completionMutex_ );
979 if( queryID == _queryID_ ) {
980 /* Append contents to end of display queue */
983 ItemEMail *email = node->data;
985 address = addritem_format_email( email );
986 /* g_print( "\temail/address ::%s::\n", address ); */
987 _displayQueue_ = g_list_append( _displayQueue_, address );
988 node = g_list_next( node );
991 g_list_free( listEMail );
992 pthread_mutex_unlock( & _completionMutex_ );
998 * Clear the display queue.
1000 static void addrcompl_clear_queue( void ) {
1001 /* Clear out display queue */
1002 pthread_mutex_lock( & _completionMutex_ );
1004 g_list_free( _displayQueue_ );
1005 _displayQueue_ = NULL;
1007 pthread_mutex_unlock( & _completionMutex_ );
1011 * Add a single address entry into the display queue.
1012 * \param address Address to append.
1014 static void addrcompl_add_queue( gchar *address ) {
1015 pthread_mutex_lock( & _completionMutex_ );
1016 _displayQueue_ = g_list_append( _displayQueue_, address );
1017 pthread_mutex_unlock( & _completionMutex_ );
1021 * Load list with entries from local completion index.
1023 static void addrcompl_load_local( void ) {
1026 for (count = 0; count < get_completion_count(); count++) {
1029 address = get_complete_address( count );
1030 /* g_print( "\taddress ::%s::\n", address ); */
1032 /* Append contents to end of display queue */
1033 addrcompl_add_queue( address );
1040 static void addrcompl_start_search( void ) {
1043 searchTerm = g_strdup( _compWindow_->searchTerm );
1045 /* Setup the search */
1046 _queryID_ = addrindex_setup_search(
1047 searchTerm, NULL, addrcompl_callback_entry );
1048 g_free( searchTerm );
1049 /* g_print( "addrcompl_start_search::queryID=%d\n", _queryID_ ); */
1051 /* Load local stuff */
1052 addrcompl_load_local();
1054 /* Sit back and wait until something happens */
1055 _completionIdleID_ =
1056 g_idle_add( (GSourceFunc) addrcompl_idle, NULL );
1057 /* g_print( "addrindex_start_search::queryID=%d\n", _queryID_ ); */
1059 addrindex_start_search( _queryID_ );
1063 * Apply the current selection in the list to the entry field. Focus is also
1064 * moved to the next widget so that Tab key works correctly.
1065 * \param list_view List to process.
1066 * \param entry Address entry field.
1067 * \param move_focus Move focus to the next widget ?
1069 static void completion_window_apply_selection(GtkTreeView *list_view,
1071 gboolean move_focus)
1073 gchar *address = NULL, *text = NULL;
1076 GtkTreeSelection *selection;
1077 GtkTreeModel *model;
1079 gboolean is_group = FALSE;
1080 cm_return_if_fail(list_view != NULL);
1081 cm_return_if_fail(entry != NULL);
1082 GList *grp_emails = NULL;
1084 selection = gtk_tree_view_get_selection(list_view);
1085 if (! gtk_tree_selection_get_selected(selection, &model, &iter))
1088 /* First remove the idler */
1089 if( _completionIdleID_ != 0 ) {
1090 g_source_remove( _completionIdleID_ );
1091 _completionIdleID_ = 0;
1094 /* Process selected item */
1095 gtk_tree_model_get(model, &iter, ADDR_COMPL_ADDRESS, &text,
1096 ADDR_COMPL_ISGROUP, &is_group,
1097 ADDR_COMPL_GROUPLIST, &grp_emails,
1100 address = get_address_from_edit(entry, &cursor_pos);
1102 replace_address_in_edit(entry, text, cursor_pos, is_group, grp_emails);
1105 /* Move focus to next widget */
1106 parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1107 if( parent && move_focus) {
1108 gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1113 * Start address completion. Should be called when creating the main window
1114 * containing address completion entries.
1115 * \param mainwindow Main window.
1117 void address_completion_start(GtkWidget *mainwindow)
1119 start_address_completion(NULL);
1121 /* register focus change hook */
1122 g_signal_connect(G_OBJECT(mainwindow), "set_focus",
1123 G_CALLBACK(address_completion_mainwindow_set_focus),
1128 * Need unique data to make unregistering signal handler possible for the auto
1131 #define COMPLETION_UNIQUE_DATA (GINT_TO_POINTER(0xfeefaa))
1134 * Register specified entry widget for address completion.
1135 * \param entry Address entry field.
1137 void address_completion_register_entry(GtkEntry *entry, gboolean allow_commas)
1139 cm_return_if_fail(entry != NULL);
1140 cm_return_if_fail(GTK_IS_ENTRY(entry));
1142 /* add hooked property */
1143 g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, entry);
1144 g_object_set_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS, GINT_TO_POINTER(allow_commas));
1146 /* add keypress event */
1147 g_signal_connect_closure
1148 (G_OBJECT(entry), "key_press_event",
1149 g_cclosure_new(G_CALLBACK(address_completion_entry_key_pressed),
1150 COMPLETION_UNIQUE_DATA,
1156 * Unregister specified entry widget from address completion operations.
1157 * \param entry Address entry field.
1159 void address_completion_unregister_entry(GtkEntry *entry)
1163 cm_return_if_fail(entry != NULL);
1164 cm_return_if_fail(GTK_IS_ENTRY(entry));
1166 entry_obj = g_object_get_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK);
1167 cm_return_if_fail(entry_obj);
1168 cm_return_if_fail(G_OBJECT(entry_obj) == G_OBJECT(entry));
1170 /* has the hooked property? */
1171 g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, NULL);
1173 /* remove the hook */
1174 g_signal_handlers_disconnect_by_func(G_OBJECT(entry),
1175 G_CALLBACK(address_completion_entry_key_pressed),
1176 COMPLETION_UNIQUE_DATA);
1180 * End address completion. Should be called when main window with address
1181 * completion entries terminates. NOTE: this function assumes that it is
1182 * called upon destruction of the window.
1183 * \param mainwindow Main window.
1185 void address_completion_end(GtkWidget *mainwindow)
1187 /* if address_completion_end() is really called on closing the window,
1188 * we don't need to unregister the set_focus_cb */
1189 end_address_completion();
1192 /* if focus changes to another entry, then clear completion cache */
1193 static void address_completion_mainwindow_set_focus(GtkWindow *window,
1198 if (widget && GTK_IS_ENTRY(widget) &&
1199 g_object_get_data(G_OBJECT(widget), ENTRY_DATA_TAB_HOOK)) {
1200 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), ENTRY_DATA_ALLOW_COMMAS));
1201 clear_completion_cache();
1206 * Listener that watches for tab or other keystroke in address entry field.
1207 * \param entry Address entry field.
1208 * \param ev Event object.
1209 * \param data User data.
1210 * \return <i>TRUE</i>.
1212 static gboolean address_completion_entry_key_pressed(GtkEntry *entry,
1216 if (ev->keyval == GDK_KEY_Tab) {
1217 addrcompl_clear_queue();
1218 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS));
1219 if( address_completion_complete_address_in_entry( entry, TRUE ) ) {
1220 /* route a void character to the default handler */
1221 /* this is a dirty hack; we're actually changing a key
1222 * reported by the system. */
1223 ev->keyval = GDK_KEY_AudibleBell_Enable;
1224 ev->state &= ~GDK_SHIFT_MASK;
1227 address_completion_create_completion_window(entry);
1229 /* Start remote queries */
1230 addrcompl_start_search();
1237 } else if (ev->keyval == GDK_KEY_Shift_L
1238 || ev->keyval == GDK_KEY_Shift_R
1239 || ev->keyval == GDK_KEY_Control_L
1240 || ev->keyval == GDK_KEY_Control_R
1241 || ev->keyval == GDK_KEY_Caps_Lock
1242 || ev->keyval == GDK_KEY_Shift_Lock
1243 || ev->keyval == GDK_KEY_Meta_L
1244 || ev->keyval == GDK_KEY_Meta_R
1245 || ev->keyval == GDK_KEY_Alt_L
1246 || ev->keyval == GDK_KEY_Alt_R) {
1247 /* these buttons should not clear the cache... */
1249 clear_completion_cache();
1254 * Initialize search term for address completion.
1255 * \param entry Address entry field.
1257 static gboolean address_completion_complete_address_in_entry(GtkEntry *entry,
1260 gint ncount, cursor_pos;
1261 gchar *searchTerm, *new = NULL;
1263 cm_return_val_if_fail(entry != NULL, FALSE);
1265 if (!gtkut_widget_has_focus(GTK_WIDGET(entry))) return FALSE;
1267 /* get an address component from the cursor */
1268 searchTerm = get_address_from_edit( entry, &cursor_pos );
1269 if( ! searchTerm ) return FALSE;
1270 /* g_print( "search for :::%s:::\n", searchTerm ); */
1272 /* Clear any existing search */
1273 g_free( _compWindow_->searchTerm );
1274 _compWindow_->searchTerm = g_strdup( searchTerm );
1276 /* Perform search on local completion index */
1277 ncount = complete_address( searchTerm );
1279 new = get_next_complete_address();
1282 #if (!defined(USE_LDAP) && !defined(GENERIC_UMPC))
1283 /* Select the address if there is only one match */
1285 /* Display selected address in entry field */
1286 gchar *addr = get_complete_address(1);
1287 if (addr && !strstr(addr, " <!--___group___-->")) {
1288 replace_address_in_edit(entry, addr, cursor_pos, FALSE, NULL);
1289 /* Discard the window */
1290 clear_completion_cache();
1294 /* Make sure that drop-down appears uniform! */
1298 addrcompl_add_queue( g_strdup( searchTerm ) );
1300 g_free( searchTerm );
1306 * Create new address completion window for specified entry.
1307 * \param entry_ Entry widget to associate with window.
1309 static void address_completion_create_completion_window( GtkEntry *entry_ )
1311 gint x, y, height, width, depth;
1312 GtkWidget *scroll, *list_view;
1315 GtkWidget *entry = GTK_WIDGET(entry_);
1318 /* Create new window and list */
1319 window = gtk_window_new(GTK_WINDOW_POPUP);
1320 list_view = addr_compl_list_view_create(_compWindow_);
1322 /* Destroy any existing window */
1323 addrcompl_destroy_window( _compWindow_ );
1325 /* Create new object */
1326 _compWindow_->window = window;
1327 _compWindow_->entry = entry;
1328 _compWindow_->list_view = list_view;
1329 _compWindow_->listCount = 0;
1330 _compWindow_->in_mouse = FALSE;
1332 scroll = gtk_scrolled_window_new(NULL, NULL);
1333 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
1334 GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
1335 gtk_container_add(GTK_CONTAINER(window), scroll);
1336 gtk_container_add(GTK_CONTAINER(scroll), list_view);
1337 gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll),
1339 /* Use entry widget to create initial window */
1340 gdkwin = gtk_widget_get_window(entry),
1341 gdk_window_get_geometry(gdkwin, &x, &y, &width, &height, &depth);
1342 gdk_window_get_origin (gdkwin, &x, &y);
1344 gtk_window_move(GTK_WINDOW(window), x, y);
1346 /* Resize window to fit initial (empty) address list */
1347 gtk_widget_size_request( list_view, &r );
1348 gtk_widget_set_size_request( window, width, r.height );
1349 gtk_widget_show_all( window );
1350 gtk_widget_size_request( list_view, &r );
1352 /* Setup handlers */
1353 g_signal_connect(G_OBJECT(list_view), "button_press_event",
1354 G_CALLBACK(list_view_button_press),
1357 g_signal_connect(G_OBJECT(list_view), "button_release_event",
1358 G_CALLBACK(list_view_button_release),
1361 g_signal_connect(G_OBJECT(window),
1362 "button-press-event",
1363 G_CALLBACK(completion_window_button_press),
1365 g_signal_connect(G_OBJECT(window),
1367 G_CALLBACK(completion_window_key_press),
1369 gdk_pointer_grab(gtk_widget_get_window(window), TRUE,
1370 GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK |
1371 GDK_BUTTON_RELEASE_MASK,
1372 NULL, NULL, GDK_CURRENT_TIME);
1373 gtk_grab_add( window );
1377 * GTK1: this gets rid of the irritating focus rectangle that doesn't
1378 * follow the selection */
1379 gtkut_widget_set_can_focus(list_view, FALSE);
1383 * Respond to button press in completion window. Check if mouse click is
1384 * anywhere outside the completion window. In that case the completion
1385 * window is destroyed, and the original searchTerm is restored.
1387 * \param widget Window object.
1388 * \param event Event.
1389 * \param compWin Reference to completion window.
1391 static gboolean completion_window_button_press(GtkWidget *widget,
1392 GdkEventButton *event,
1393 CompletionWindow *compWin )
1395 GtkWidget *event_widget, *entry;
1398 gboolean restore = TRUE;
1400 cm_return_val_if_fail(compWin != NULL, FALSE);
1402 entry = compWin->entry;
1403 cm_return_val_if_fail(entry != NULL, FALSE);
1405 /* Test where mouse was clicked */
1406 event_widget = gtk_get_event_widget((GdkEvent *)event);
1407 if (event_widget != widget) {
1408 while (event_widget) {
1409 if (event_widget == widget)
1411 else if (event_widget == entry) {
1415 event_widget = gtk_widget_get_parent(event_widget);
1420 /* Clicked outside of completion window - restore */
1421 searchTerm = _compWindow_->searchTerm;
1422 g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1423 replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos, FALSE, NULL);
1426 clear_completion_cache();
1427 addrcompl_destroy_window( _compWindow_ );
1433 * Respond to key press in completion window.
1434 * \param widget Window object.
1435 * \param event Event.
1436 * \param compWind Reference to completion window.
1438 static gboolean completion_window_key_press(GtkWidget *widget,
1440 CompletionWindow *compWin )
1442 GdkEventKey tmp_event;
1446 GtkWidget *list_view;
1448 cm_return_val_if_fail(compWin != NULL, FALSE);
1450 entry = compWin->entry;
1451 list_view = compWin->list_view;
1452 cm_return_val_if_fail(entry != NULL, FALSE);
1454 /* allow keyboard navigation in the alternatives tree view */
1455 if (event->keyval == GDK_KEY_Up || event->keyval == GDK_KEY_Down ||
1456 event->keyval == GDK_KEY_Page_Up || event->keyval == GDK_KEY_Page_Down) {
1457 completion_window_advance_selection
1458 (GTK_TREE_VIEW(list_view),
1459 event->keyval == GDK_KEY_Down ||
1460 event->keyval == GDK_KEY_Page_Down ? TRUE : FALSE);
1464 /* make tab move to next field */
1465 if( event->keyval == GDK_KEY_Tab ) {
1466 /* Reference to parent */
1467 parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1469 /* Discard the window */
1470 clear_completion_cache();
1471 addrcompl_destroy_window( _compWindow_ );
1473 /* Move focus to next widget */
1475 gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1480 /* make backtab move to previous field */
1481 if( event->keyval == GDK_KEY_ISO_Left_Tab ) {
1482 /* Reference to parent */
1483 parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1485 /* Discard the window */
1486 clear_completion_cache();
1487 addrcompl_destroy_window( _compWindow_ );
1489 /* Move focus to previous widget */
1491 gtk_widget_child_focus( parent, GTK_DIR_TAB_BACKWARD );
1495 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS));
1497 /* look for presses that accept the selection */
1498 if (event->keyval == GDK_KEY_Return || event->keyval == GDK_KEY_space ||
1499 event->keyval == GDK_KEY_KP_Enter ||
1500 (_allowCommas_ && event->keyval == GDK_KEY_comma)) {
1501 /* User selected address with a key press */
1503 /* Display selected address in entry field */
1504 completion_window_apply_selection(
1505 GTK_TREE_VIEW(list_view), GTK_ENTRY(entry),
1506 event->keyval != GDK_KEY_comma);
1508 if (event->keyval == GDK_KEY_comma) {
1509 gint pos = gtk_editable_get_position(GTK_EDITABLE(entry));
1510 gtk_editable_insert_text(GTK_EDITABLE(entry), ", ", 2, &pos);
1511 gtk_editable_set_position(GTK_EDITABLE(entry), pos + 1);
1514 /* Discard the window */
1515 clear_completion_cache();
1516 addrcompl_destroy_window( _compWindow_ );
1520 /* key state keys should never be handled */
1521 if (event->keyval == GDK_KEY_Shift_L
1522 || event->keyval == GDK_KEY_Shift_R
1523 || event->keyval == GDK_KEY_Control_L
1524 || event->keyval == GDK_KEY_Control_R
1525 || event->keyval == GDK_KEY_Caps_Lock
1526 || event->keyval == GDK_KEY_Shift_Lock
1527 || event->keyval == GDK_KEY_Meta_L
1528 || event->keyval == GDK_KEY_Meta_R
1529 || event->keyval == GDK_KEY_Alt_L
1530 || event->keyval == GDK_KEY_Alt_R) {
1534 /* some other key, let's restore the searchTerm (orignal text) */
1535 searchTerm = _compWindow_->searchTerm;
1536 g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1537 replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos, FALSE, NULL);
1539 /* make sure anything we typed comes in the edit box */
1540 tmp_event.type = event->type;
1541 tmp_event.window = gtk_widget_get_window(GTK_WIDGET(entry));
1542 tmp_event.send_event = TRUE;
1543 tmp_event.time = event->time;
1544 tmp_event.state = event->state;
1545 tmp_event.keyval = event->keyval;
1546 tmp_event.length = event->length;
1547 tmp_event.string = event->string;
1548 gtk_widget_event(entry, (GdkEvent *)&tmp_event);
1550 /* and close the completion window */
1551 clear_completion_cache();
1552 addrcompl_destroy_window( _compWindow_ );
1558 * ============================================================================
1559 * Publically accessible functions.
1560 * ============================================================================
1564 * Setup completion object.
1566 void addrcompl_initialize( void ) {
1567 /* g_print( "addrcompl_initialize...\n" ); */
1568 if( ! _compWindow_ ) {
1569 _compWindow_ = addrcompl_create_window();
1572 _completionIdleID_ = 0;
1573 /* g_print( "addrcompl_initialize...done\n" ); */
1577 * Teardown completion object.
1579 void addrcompl_teardown( void ) {
1580 /* g_print( "addrcompl_teardown...\n" ); */
1581 addrcompl_free_window( _compWindow_ );
1582 _compWindow_ = NULL;
1583 if( _displayQueue_ ) {
1584 g_list_free( _displayQueue_ );
1586 _displayQueue_ = NULL;
1587 _completionIdleID_ = 0;
1588 /* g_print( "addrcompl_teardown...done\n" ); */
1592 * tree view functions
1595 static GtkListStore *addr_compl_create_store(void)
1597 return gtk_list_store_new(N_ADDR_COMPL_COLUMNS,
1605 static GtkWidget *addr_compl_list_view_create(CompletionWindow *window)
1607 GtkTreeView *list_view;
1608 GtkTreeSelection *selector;
1609 GtkTreeModel *model;
1611 model = GTK_TREE_MODEL(addr_compl_create_store());
1612 list_view = GTK_TREE_VIEW(gtk_tree_view_new_with_model(model));
1613 g_object_unref(model);
1615 gtk_tree_view_set_rules_hint(list_view, prefs_common.use_stripes_everywhere);
1616 gtk_tree_view_set_headers_visible(list_view, FALSE);
1618 selector = gtk_tree_view_get_selection(list_view);
1619 gtk_tree_selection_set_mode(selector, GTK_SELECTION_BROWSE);
1620 gtk_tree_selection_set_select_function(selector, addr_compl_selected,
1623 /* create the columns */
1624 addr_compl_create_list_view_columns(GTK_WIDGET(list_view));
1626 return GTK_WIDGET(list_view);
1629 static void addr_compl_create_list_view_columns(GtkWidget *list_view)
1631 GtkTreeViewColumn *column;
1632 GtkCellRenderer *renderer;
1634 renderer = gtk_cell_renderer_pixbuf_new();
1635 column = gtk_tree_view_column_new_with_attributes
1637 "pixbuf", ADDR_COMPL_ICON, NULL);
1638 gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);
1639 renderer = gtk_cell_renderer_text_new();
1640 column = gtk_tree_view_column_new_with_attributes
1641 ("", renderer, "text", ADDR_COMPL_ADDRESS, NULL);
1642 gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);
1645 static gboolean list_view_button_press(GtkWidget *widget, GdkEventButton *event,
1646 CompletionWindow *window)
1648 if (window && event && event->type == GDK_BUTTON_PRESS) {
1649 window->in_mouse = TRUE;
1654 static gboolean list_view_button_release(GtkWidget *widget, GdkEventButton *event,
1655 CompletionWindow *window)
1657 if (window && event && event->type == GDK_BUTTON_RELEASE) {
1658 window->in_mouse = FALSE;
1663 static gboolean addr_compl_selected(GtkTreeSelection *selector,
1664 GtkTreeModel *model,
1666 gboolean currently_selected,
1669 CompletionWindow *window = data;
1671 if (currently_selected)
1674 if (!window->in_mouse)
1677 /* XXX: select the entry and kill window later... select is called before
1678 * any other mouse events handlers including the tree view internal one;
1679 * not using a time out would result in a crash. if this doesn't work
1680 * safely, maybe we should set variables when receiving button presses
1681 * in the tree view. */
1682 if (!window->destroying) {
1683 window->destroying = TRUE;
1684 g_idle_add((GSourceFunc) addr_compl_defer_select_destruct, data);
1690 static gboolean addr_compl_defer_select_destruct(CompletionWindow *window)
1692 GtkEntry *entry = GTK_ENTRY(window->entry);
1694 completion_window_apply_selection(GTK_TREE_VIEW(window->list_view),
1697 clear_completion_cache();
1699 addrcompl_destroy_window(window);