2 * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
4 * Copyright (C) 2000-2009 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"
47 *\brief For the GtkListStore
60 * The address book is read into memory. We set up an address list
61 * containing all address book entries. Next we make the completion
62 * list, which contains all the completable strings, and store a
63 * reference to the address entry it belongs to.
64 * After calling the g_completion_complete(), we get a reference
65 * to a valid email address.
67 * Completion is very simplified. We never complete on another prefix,
68 * i.e. we neglect the next smallest possible prefix for the current
69 * completion cache. This is simply done so we might break up the
70 * addresses a little more (e.g. break up alfons@proteus.demon.nl into
71 * something like alfons, proteus, demon, nl; and then completing on
72 * any of those words).
76 * completion_entry - structure used to complete addresses, with a reference
77 * the the real address information.
81 gchar *string; /* string to complete */
82 address_entry *ref; /* address the string belongs to */
85 /*******************************************************************************/
87 static gint g_ref_count; /* list ref count */
88 static GList *g_completion_list = NULL; /* list of strings to be checked */
89 static GList *g_address_list = NULL; /* address storage */
90 static GCompletion *g_completion; /* completion object */
92 static GHashTable *_groupAddresses_ = NULL;
93 static gboolean _allowCommas_ = TRUE;
95 /* To allow for continuing completion we have to keep track of the state
96 * using the following variables. No need to create a context object. */
98 static gint g_completion_count; /* nr of addresses incl. the prefix */
99 static gint g_completion_next; /* next prev address */
100 static GSList *g_completion_addresses; /* unique addresses found in the
102 static gchar *g_completion_prefix; /* last prefix. (this is cached here
103 * because the prefix passed to g_completion
104 * is g_utf8_strdown()'ed */
106 static gchar *completion_folder_path = NULL;
108 /*******************************************************************************/
111 * Define the structure of the completion window.
113 typedef struct _CompletionWindow CompletionWindow;
114 struct _CompletionWindow {
119 GtkWidget *list_view;
121 gboolean in_mouse; /*!< mouse press pending... */
122 gboolean destroying; /*!< destruction in progress */
125 static GtkListStore *addr_compl_create_store (void);
127 static GtkWidget *addr_compl_list_view_create (CompletionWindow *window);
129 static void addr_compl_create_list_view_columns (GtkWidget *list_view);
131 static gboolean list_view_button_press (GtkWidget *widget,
132 GdkEventButton *event,
133 CompletionWindow *window);
135 static gboolean list_view_button_release (GtkWidget *widget,
136 GdkEventButton *event,
137 CompletionWindow *window);
139 static gboolean addr_compl_selected (GtkTreeSelection *selector,
142 gboolean currently_selected,
145 static gboolean addr_compl_defer_select_destruct(CompletionWindow *window);
148 * Function used by GTK to find the string data to be used for completion.
149 * \param data Pointer to data being processed.
151 static gchar *completion_func(gpointer data)
153 cm_return_val_if_fail(data != NULL, NULL);
155 return ((completion_entry *)data)->string;
159 * Initialize all completion index data.
161 static void init_all(void)
163 g_completion = g_completion_new(completion_func);
164 cm_return_if_fail(g_completion != NULL);
167 static void free_all_addresses(void)
172 walk = g_address_list;
173 for (; walk != NULL; walk = g_list_next(walk)) {
174 address_entry *ae = (address_entry *) walk->data;
177 g_list_free(ae->grp_emails);
180 g_list_free(g_address_list);
181 g_address_list = NULL;
182 if (_groupAddresses_)
183 g_hash_table_destroy(_groupAddresses_);
184 _groupAddresses_ = NULL;
187 static void clear_completion_cache(void);
188 static void free_completion_list(void)
191 if (!g_completion_list)
194 clear_completion_cache();
196 g_completion_clear_items(g_completion);
198 walk = g_list_first(g_completion_list);
199 for (; walk != NULL; walk = g_list_next(walk)) {
200 completion_entry *ce = (completion_entry *) walk->data;
204 g_list_free(g_completion_list);
205 g_completion_list = NULL;
208 * Free up all completion index data.
210 static void free_all(void)
212 free_completion_list();
213 free_all_addresses();
214 g_completion_free(g_completion);
219 * Append specified address entry to the index.
220 * \param str Index string value.
221 * \param ae Entry containing address data.
223 void addr_compl_add_address1(const char *str, address_entry *ae)
225 completion_entry *ce1;
226 ce1 = g_new0(completion_entry, 1),
227 /* GCompletion list is case sensitive */
228 ce1->string = g_utf8_strdown(str, -1);
231 g_completion_list = g_list_prepend(g_completion_list, ce1);
235 * Adds address to the completion list. This function looks complicated, but
236 * it's only allocation checks. Each value will be included in the index.
237 * \param name Recipient name.
238 * \param address EMail address.
239 * \param alias Alias to append.
240 * \param grp_emails the emails in case of a group. List should be freed later,
241 * but not its strings
242 * \return <code>0</code> if entry appended successfully, or <code>-1</code>
245 static gint add_address(const gchar *name, const gchar *address,
246 const gchar *nick, const gchar *alias, GList *grp_emails)
249 gboolean is_group = FALSE;
251 if (!name || !address) {
252 if (!address && !nick && !alias && grp_emails) {
258 ae = g_new0(address_entry, 1);
260 cm_return_val_if_fail(ae != NULL, -1);
262 ae->name = g_strdup(name);
263 ae->address = g_strdup(address);
264 ae->grp_emails = grp_emails;
265 g_address_list = g_list_prepend(g_address_list, ae);
267 addr_compl_add_address1(name, ae);
268 if (address != NULL && *address != '\0')
269 addr_compl_add_address1(address, ae);
271 if (nick != NULL && *nick != '\0')
272 addr_compl_add_address1(nick, ae);
274 if ( alias != NULL && *alias != '\0') {
275 addr_compl_add_address1(alias, ae);
282 * Read address book, creating all entries in the completion index.
284 static void read_address_book(gchar *folderpath) {
285 free_all_addresses();
286 free_completion_list();
288 addrindex_load_completion( add_address, folderpath );
290 /* plugins may hook in here to modify/extend the completion list */
291 hooks_invoke(ADDDRESS_COMPLETION_BUILD_ADDRESS_LIST_HOOKLIST, &g_address_list);
293 g_address_list = g_list_reverse(g_address_list);
294 g_completion_list = g_list_reverse(g_completion_list);
295 /* merge the completion entry list into g_completion */
296 if (g_completion_list) {
297 g_completion_add_items(g_completion, g_completion_list);
298 if (debug_get_mode())
299 debug_print("read %d items in %s\n",
300 g_list_length(g_completion_list),
301 folderpath?folderpath:"(null)");
306 * Test whether there is a completion pending.
307 * \return <code>TRUE</code> if pending.
309 static gboolean is_completion_pending(void)
311 /* check if completion pending, i.e. we might satisfy a request for the next
312 * or previous address */
313 return g_completion_count;
317 * Clear the completion cache.
319 static void clear_completion_cache(void)
321 if (is_completion_pending()) {
322 g_free(g_completion_prefix);
324 if (g_completion_addresses) {
325 g_slist_free(g_completion_addresses);
326 g_completion_addresses = NULL;
329 g_completion_count = g_completion_next = 0;
334 * Prepare completion index. This function should be called prior to attempting
335 * address completion.
336 * \return The number of addresses in the completion list.
338 gint start_address_completion(gchar *folderpath)
340 gboolean different_book = FALSE;
341 clear_completion_cache();
343 if (strcmp2(completion_folder_path,folderpath))
344 different_book = TRUE;
346 g_free(completion_folder_path);
347 if (folderpath != NULL)
348 completion_folder_path = g_strdup(folderpath);
350 completion_folder_path = NULL;
354 /* open the address book */
355 read_address_book(folderpath);
356 } else if (different_book)
357 read_address_book(folderpath);
360 debug_print("start_address_completion(%s) ref count %d\n",
361 folderpath?folderpath:"(null)", g_ref_count);
363 return g_list_length(g_completion_list);
367 * Retrieve a possible address (or a part) from an entry box. To make life
368 * easier, we only look at the last valid address component; address
369 * completion only works at the last string component in the entry box.
371 * \param entry Address entry field.
372 * \param start_pos Address of start position of address.
373 * \return Possible address.
375 static gchar *get_address_from_edit(GtkEntry *entry, gint *start_pos)
377 const gchar *edit_text, *p;
379 gboolean in_quote = FALSE;
380 gboolean in_bracket = FALSE;
383 edit_text = gtk_entry_get_text(entry);
384 if (edit_text == NULL) return NULL;
386 cur_pos = gtk_editable_get_position(GTK_EDITABLE(entry));
388 /* scan for a separator. doesn't matter if walk points at null byte. */
389 for (p = g_utf8_offset_to_pointer(edit_text, cur_pos);
391 p = g_utf8_prev_char(p)) {
394 } else if (!in_quote) {
395 if (!in_bracket && *p == ',') {
397 } else if (*p == '<')
404 /* have something valid */
405 if (g_utf8_strlen(p, -1) == 0)
408 #define IS_VALID_CHAR(x) \
409 (g_ascii_isalnum(x) || (x) == '"' || (x) == '<' || (((unsigned char)(x)) > 0x7f))
411 /* now scan back until we hit a valid character */
412 for (; *p && !IS_VALID_CHAR(*p); p = g_utf8_next_char(p))
417 if (g_utf8_strlen(p, -1) == 0)
420 if (start_pos) *start_pos = g_utf8_pointer_to_offset(edit_text, p);
427 static gchar *get_complete_address_from_name_email(const gchar *name, const gchar *email)
429 gchar *address = NULL;
430 if (!name || name[0] == '\0')
431 address = g_strdup_printf("<%s>", email);
432 else if (strchr_with_skip_quote(name, '"', ','))
433 address = g_strdup_printf
434 ("\"%s\" <%s>", name, email);
436 address = g_strdup_printf
437 ("%s <%s>", name, email);
442 * Replace an incompleted address with a completed one.
443 * \param entry Address entry field.
444 * \param newtext New text.
445 * \param start_pos Insertion point in entry field.
447 static void replace_address_in_edit(GtkEntry *entry, const gchar *newtext,
448 gint start_pos, gboolean is_group, GList *grp_emails)
450 if (!newtext) return;
451 gtk_editable_delete_text(GTK_EDITABLE(entry), start_pos, -1);
453 gtk_editable_insert_text(GTK_EDITABLE(entry), newtext, strlen(newtext),
456 gchar *addresses = NULL;
457 GList *cur = grp_emails;
458 for (; cur; cur = cur->next) {
460 ItemEMail *email = (ItemEMail *)cur->data;
461 ItemPerson *person = ( ItemPerson * ) ADDRITEM_PARENT(email);
463 gchar *addr = get_complete_address_from_name_email(
464 ADDRITEM_NAME(person), email->address);
466 tmp = g_strdup_printf("%s, %s", addresses, addr);
468 tmp = g_strdup_printf("%s", addr);
473 gtk_editable_insert_text(GTK_EDITABLE(entry), addresses, strlen(addresses),
477 gtk_editable_set_position(GTK_EDITABLE(entry), -1);
481 * Attempt to complete an address, and returns the number of addresses found.
482 * Use <code>get_complete_address()</code> to get an entry from the index.
484 * \param str Search string to find.
485 * \return Zero if no match was found, otherwise the number of addresses; the
486 * original prefix (search string) will appear at index 0.
488 guint complete_address(const gchar *str)
490 GList *result = NULL;
494 completion_entry *ce = NULL;
496 cm_return_val_if_fail(str != NULL, 0);
498 /* g_completion is case sensitive */
499 d = g_utf8_strdown(str, -1);
501 clear_completion_cache();
502 g_completion_prefix = g_strdup(str);
504 result = g_completion_complete(g_completion, d, NULL);
506 count = g_list_length(result);
508 /* create list with unique addresses */
509 for (cpl = 0, result = g_list_first(result);
511 result = g_list_next(result)) {
512 ce = (completion_entry *)(result->data);
513 if (NULL == g_slist_find(g_completion_addresses,
516 g_completion_addresses =
517 g_slist_append(g_completion_addresses,
521 count = cpl + 1; /* index 0 is the original prefix */
522 g_completion_next = 1; /* we start at the first completed one */
524 g_free(g_completion_prefix);
525 g_completion_prefix = NULL;
528 g_completion_count = count;
536 * complete_matches_found() returns the number of matched addresses according
537 * to the completion mechanism. Unlike complete_address(), the returned value
538 * doesn't count str itself. If there's no match, it returns 0.
539 * To get a list of completion matches, see complete_address() instead.
541 guint complete_matches_found(const gchar *str)
543 GList *result = NULL;
546 cm_return_val_if_fail(str != NULL, 0);
548 /* g_completion is case sensitive */
549 d = g_utf8_strdown(str, -1);
551 clear_completion_cache();
552 g_completion_prefix = g_strdup(str);
554 result = g_completion_complete(g_completion, d, NULL);
556 g_free(g_completion_prefix);
559 return g_list_length(result);
563 * Return a complete address from the index.
564 * \param index Index of entry that was found (by the previous call to
565 * <code>complete_address()</code>
566 * \return Completed address string; this should be freed when done.
568 gchar *get_complete_address(gint index)
570 const address_entry *p;
571 gchar *address = NULL;
573 if (index < g_completion_count) {
575 address = g_strdup(g_completion_prefix);
577 /* get something from the unique addresses */
578 p = (address_entry *)g_slist_nth_data
579 (g_completion_addresses, index - 1);
580 if (p != NULL && p->address != NULL) {
581 address = get_complete_address_from_name_email(p->name, p->address);
582 } else if (p != NULL && p->address == NULL && p->name != NULL) {
584 address = g_strdup_printf("%s (%s) <!--___group___-->", p->name, _("Group"));
585 if (!_groupAddresses_) {
586 _groupAddresses_ = g_hash_table_new(NULL, g_direct_equal);
588 if (!g_hash_table_lookup(_groupAddresses_, GINT_TO_POINTER(g_str_hash(address)))) {
589 g_hash_table_insert(_groupAddresses_, GINT_TO_POINTER(g_str_hash(address)), p->grp_emails);
600 * Return the next complete address match from the completion index.
601 * \return Completed address string; this should be freed when done.
603 static gchar *get_next_complete_address(void)
605 if (is_completion_pending()) {
608 res = get_complete_address(g_completion_next);
609 g_completion_next += 1;
610 if (g_completion_next >= g_completion_count)
611 g_completion_next = 0;
619 * Return a count of the completed matches in the completion index.
620 * \return Number of matched entries.
622 static guint get_completion_count(void)
624 if (is_completion_pending())
625 return g_completion_count;
631 * Invalidate address completion index. This function should be called whenever
632 * the address book changes. This forces data to be read into the completion
634 * \return Number of entries in index.
636 gint invalidate_address_completion(void)
639 /* simply the same as start_address_completion() */
640 debug_print("Invalidation request for address completion\n");
641 read_address_book(completion_folder_path);
642 clear_completion_cache();
645 return g_list_length(g_completion_list);
649 * Finished with completion index. This function should be called after
650 * matching addresses.
651 * \return Reference count.
653 gint end_address_completion(void)
655 gboolean different_folder = FALSE;
656 clear_completion_cache();
658 /* reset the folderpath to NULL */
659 if (completion_folder_path) {
660 g_free(completion_folder_path);
661 completion_folder_path = NULL;
662 different_folder = TRUE;
664 if (0 == --g_ref_count)
667 debug_print("end_address_completion ref count %d\n", g_ref_count);
668 if (g_ref_count && different_folder) {
669 debug_print("still ref'd, different folder\n");
670 invalidate_address_completion();
679 static CompletionWindow *_compWindow_ = NULL;
682 * Mutex to protect callback from multiple threads.
684 static pthread_mutex_t _completionMutex_ = PTHREAD_MUTEX_INITIALIZER;
687 * Completion queue list.
689 static GList *_displayQueue_ = NULL;
693 static gint _queryID_ = 0;
696 * Completion idle ID.
698 static guint _completionIdleID_ = 0;
701 * address completion entry ui. the ui (completion list was inspired by galeon's
702 * auto completion list). remaining things powered by claws's completion engine.
705 #define ENTRY_DATA_TAB_HOOK "tab_hook" /* used to lookup entry */
706 #define ENTRY_DATA_ALLOW_COMMAS "allowcommas" /* used to know whether to present groups */
708 static void address_completion_mainwindow_set_focus (GtkWindow *window,
711 static gboolean address_completion_entry_key_pressed (GtkEntry *entry,
714 static gboolean address_completion_complete_address_in_entry
717 static void address_completion_create_completion_window (GtkEntry *entry);
719 static gboolean completion_window_button_press
721 GdkEventButton *event,
722 CompletionWindow *compWin );
724 static gboolean completion_window_key_press
727 CompletionWindow *compWin );
728 static void address_completion_create_completion_window( GtkEntry *entry_ );
731 * Create a completion window object.
732 * \return Initialized completion window.
734 static CompletionWindow *addrcompl_create_window( void ) {
735 CompletionWindow *cw;
737 cw = g_new0( CompletionWindow, 1 );
739 cw->searchTerm = NULL;
742 cw->list_view = NULL;
743 cw->in_mouse = FALSE;
744 cw->destroying = FALSE;
750 * Destroy completion window.
751 * \param cw Window to destroy.
753 static void addrcompl_destroy_window( CompletionWindow *cw ) {
754 /* Stop all searches currently in progress */
755 addrindex_stop_search( _queryID_ );
757 /* Remove idler function... or application may not terminate */
758 if( _completionIdleID_ != 0 ) {
759 g_source_remove( _completionIdleID_ );
760 _completionIdleID_ = 0;
763 /* Now destroy window */
765 /* Clear references to widgets */
767 cw->list_view = NULL;
771 gtk_widget_hide( cw->window );
772 gtk_widget_destroy( cw->window );
775 cw->destroying = FALSE;
776 cw->in_mouse = FALSE;
782 * Free up completion window.
783 * \param cw Window to free.
785 static void addrcompl_free_window( CompletionWindow *cw ) {
787 addrcompl_destroy_window( cw );
789 g_free( cw->searchTerm );
790 cw->searchTerm = NULL;
792 /* Clear references */
801 * Advance selection to previous/next item in list.
802 * \param list_view List to process.
803 * \param forward Set to <i>TRUE</i> to select next or <i>FALSE</i> for
806 static void completion_window_advance_selection(GtkTreeView *list_view, gboolean forward)
808 GtkTreeSelection *selection;
812 cm_return_if_fail(list_view != NULL);
814 selection = gtk_tree_view_get_selection(list_view);
815 if (!gtk_tree_selection_get_selected(selection, &model, &iter))
819 forward = gtk_tree_model_iter_next(model, &iter);
821 gtk_tree_selection_select_iter(selection, &iter);
825 prev = gtk_tree_model_get_path(model, &iter);
829 if (gtk_tree_path_prev(prev))
830 gtk_tree_selection_select_path(selection, prev);
832 gtk_tree_path_free(prev);
837 * Resize window to accommodate maximum number of address entries.
838 * \param cw Completion window.
840 static void addrcompl_resize_window( CompletionWindow *cw ) {
842 gint x, y, width, height, depth;
844 /* Get current geometry of window */
845 gdk_window_get_geometry( cw->window->window, &x, &y, &width, &height, &depth );
847 gtk_widget_hide_all( cw->window );
848 gtk_widget_show_all( cw->window );
849 gtk_widget_size_request( cw->list_view, &r );
851 /* Adjust window height to available screen space */
852 if( ( y + r.height ) > gdk_screen_height() ) {
853 gtk_window_set_resizable(GTK_WINDOW(cw->window), FALSE);
854 gtk_widget_set_size_request( cw->window, width, gdk_screen_height() - y );
856 gtk_widget_set_size_request(cw->window, width, r.height);
859 static GdkPixbuf *group_pixbuf = NULL;
860 static GdkPixbuf *email_pixbuf = NULL;
863 * Add an address the completion window address list.
864 * \param cw Completion window.
865 * \param address Address to add.
867 static void addrcompl_add_entry( CompletionWindow *cw, gchar *address ) {
870 GtkTreeSelection *selection;
871 gboolean is_group = FALSE;
872 GList *grp_emails = NULL;
873 store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(cw->list_view)));
877 stock_pixbuf_gdk(cw->list_view, STOCK_PIXMAP_ADDR_TWO, &group_pixbuf);
878 g_object_ref(G_OBJECT(group_pixbuf));
881 stock_pixbuf_gdk(cw->list_view, STOCK_PIXMAP_ADDR_ONE, &email_pixbuf);
882 g_object_ref(G_OBJECT(email_pixbuf));
884 /* g_print( "\t\tAdding :%s\n", address ); */
885 if (strstr(address, " <!--___group___-->")) {
887 if (_groupAddresses_)
888 grp_emails = g_hash_table_lookup(_groupAddresses_, GINT_TO_POINTER(g_str_hash(address)));
889 *(strstr(address, " <!--___group___-->")) = '\0';
890 pixbuf = group_pixbuf;
891 } else if (strchr(address, '@') && strchr(address, '<') &&
892 strchr(address, '>')) {
893 pixbuf = email_pixbuf;
897 if (is_group && !_allowCommas_)
899 gtk_list_store_append(store, &iter);
900 gtk_list_store_set(store, &iter,
901 ADDR_COMPL_ICON, pixbuf,
902 ADDR_COMPL_ADDRESS, address,
903 ADDR_COMPL_ISGROUP, is_group,
904 ADDR_COMPL_GROUPLIST, grp_emails,
909 addrcompl_resize_window( cw );
910 gtk_grab_add( cw->window );
912 selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(cw->list_view));
913 gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store), &iter);
915 if( cw->listCount == 1 ) {
916 /* Select first row for now */
917 gtk_tree_selection_select_iter(selection, &iter);
920 else if( cw->listCount == 2 ) {
921 gtk_tree_model_iter_next(GTK_TREE_MODEL(store), &iter);
922 /* Move off first row */
923 gtk_tree_selection_select_iter(selection, &iter);
929 * Completion idle function. This function is called by the main (UI) thread
930 * during UI idle time while an address search is in progress. Items from the
931 * display queue are processed and appended to the address list.
933 * \param data Target completion window to receive email addresses.
934 * \return <i>TRUE</i> to ensure that idle event do not get ignored.
936 static gboolean addrcompl_idle( gpointer data ) {
940 /* Process all entries in display queue */
941 pthread_mutex_lock( & _completionMutex_ );
942 if( _displayQueue_ ) {
943 node = _displayQueue_;
945 address = node->data;
946 /* g_print( "address ::: %s :::\n", address ); */
947 addrcompl_add_entry( _compWindow_, address );
949 node = g_list_next( node );
951 g_list_free( _displayQueue_ );
952 _displayQueue_ = NULL;
954 pthread_mutex_unlock( & _completionMutex_ );
961 * Callback entry point. The background thread (if any) appends the address
962 * list to the display queue.
963 * \param sender Sender of query.
964 * \param queryID Query ID of search request.
965 * \param listEMail List of zero of more email objects that met search
967 * \param data Query data.
969 static gint addrcompl_callback_entry(
970 gpointer sender, gint queryID, GList *listEMail, gpointer data )
975 /* g_print( "addrcompl_callback_entry::queryID=%d\n", queryID ); */
976 pthread_mutex_lock( & _completionMutex_ );
977 if( queryID == _queryID_ ) {
978 /* Append contents to end of display queue */
981 ItemEMail *email = node->data;
983 address = addritem_format_email( email );
984 /* g_print( "\temail/address ::%s::\n", address ); */
985 _displayQueue_ = g_list_append( _displayQueue_, address );
986 node = g_list_next( node );
989 g_list_free( listEMail );
990 pthread_mutex_unlock( & _completionMutex_ );
996 * Clear the display queue.
998 static void addrcompl_clear_queue( void ) {
999 /* Clear out display queue */
1000 pthread_mutex_lock( & _completionMutex_ );
1002 g_list_free( _displayQueue_ );
1003 _displayQueue_ = NULL;
1005 pthread_mutex_unlock( & _completionMutex_ );
1009 * Add a single address entry into the display queue.
1010 * \param address Address to append.
1012 static void addrcompl_add_queue( gchar *address ) {
1013 pthread_mutex_lock( & _completionMutex_ );
1014 _displayQueue_ = g_list_append( _displayQueue_, address );
1015 pthread_mutex_unlock( & _completionMutex_ );
1019 * Load list with entries from local completion index.
1021 static void addrcompl_load_local( void ) {
1024 for (count = 0; count < get_completion_count(); count++) {
1027 address = get_complete_address( count );
1028 /* g_print( "\taddress ::%s::\n", address ); */
1030 /* Append contents to end of display queue */
1031 addrcompl_add_queue( address );
1038 static void addrcompl_start_search( void ) {
1041 searchTerm = g_strdup( _compWindow_->searchTerm );
1043 /* Setup the search */
1044 _queryID_ = addrindex_setup_search(
1045 searchTerm, NULL, addrcompl_callback_entry );
1046 g_free( searchTerm );
1047 /* g_print( "addrcompl_start_search::queryID=%d\n", _queryID_ ); */
1049 /* Load local stuff */
1050 addrcompl_load_local();
1052 /* Sit back and wait until something happens */
1053 _completionIdleID_ =
1054 g_idle_add( ( GtkFunction ) addrcompl_idle, NULL );
1055 /* g_print( "addrindex_start_search::queryID=%d\n", _queryID_ ); */
1057 addrindex_start_search( _queryID_ );
1061 * Apply the current selection in the list to the entry field. Focus is also
1062 * moved to the next widget so that Tab key works correctly.
1063 * \param list_view List to process.
1064 * \param entry Address entry field.
1065 * \param move_focus Move focus to the next widget ?
1067 static void completion_window_apply_selection(GtkTreeView *list_view,
1069 gboolean move_focus)
1071 gchar *address = NULL, *text = NULL;
1074 GtkTreeSelection *selection;
1075 GtkTreeModel *model;
1077 gboolean is_group = FALSE;
1078 cm_return_if_fail(list_view != NULL);
1079 cm_return_if_fail(entry != NULL);
1080 GList *grp_emails = NULL;
1082 selection = gtk_tree_view_get_selection(list_view);
1083 if (! gtk_tree_selection_get_selected(selection, &model, &iter))
1086 /* First remove the idler */
1087 if( _completionIdleID_ != 0 ) {
1088 g_source_remove( _completionIdleID_ );
1089 _completionIdleID_ = 0;
1092 /* Process selected item */
1093 gtk_tree_model_get(model, &iter, ADDR_COMPL_ADDRESS, &text,
1094 ADDR_COMPL_ISGROUP, &is_group,
1095 ADDR_COMPL_GROUPLIST, &grp_emails,
1098 address = get_address_from_edit(entry, &cursor_pos);
1100 replace_address_in_edit(entry, text, cursor_pos, is_group, grp_emails);
1103 /* Move focus to next widget */
1104 parent = GTK_WIDGET(entry)->parent;
1105 if( parent && move_focus) {
1106 gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1111 * Start address completion. Should be called when creating the main window
1112 * containing address completion entries.
1113 * \param mainwindow Main window.
1115 void address_completion_start(GtkWidget *mainwindow)
1117 start_address_completion(NULL);
1119 /* register focus change hook */
1120 g_signal_connect(G_OBJECT(mainwindow), "set_focus",
1121 G_CALLBACK(address_completion_mainwindow_set_focus),
1126 * Need unique data to make unregistering signal handler possible for the auto
1129 #define COMPLETION_UNIQUE_DATA (GINT_TO_POINTER(0xfeefaa))
1132 * Register specified entry widget for address completion.
1133 * \param entry Address entry field.
1135 void address_completion_register_entry(GtkEntry *entry, gboolean allow_commas)
1137 cm_return_if_fail(entry != NULL);
1138 cm_return_if_fail(GTK_IS_ENTRY(entry));
1140 /* add hooked property */
1141 g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, entry);
1142 g_object_set_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS, GINT_TO_POINTER(allow_commas));
1144 /* add keypress event */
1145 g_signal_connect_closure
1146 (G_OBJECT(entry), "key_press_event",
1147 g_cclosure_new(G_CALLBACK(address_completion_entry_key_pressed),
1148 COMPLETION_UNIQUE_DATA,
1154 * Unregister specified entry widget from address completion operations.
1155 * \param entry Address entry field.
1157 void address_completion_unregister_entry(GtkEntry *entry)
1159 GtkObject *entry_obj;
1161 cm_return_if_fail(entry != NULL);
1162 cm_return_if_fail(GTK_IS_ENTRY(entry));
1164 entry_obj = g_object_get_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK);
1165 cm_return_if_fail(entry_obj);
1166 cm_return_if_fail(G_OBJECT(entry_obj) == G_OBJECT(entry));
1168 /* has the hooked property? */
1169 g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, NULL);
1171 /* remove the hook */
1172 g_signal_handlers_disconnect_by_func(G_OBJECT(entry),
1173 G_CALLBACK(address_completion_entry_key_pressed),
1174 COMPLETION_UNIQUE_DATA);
1178 * End address completion. Should be called when main window with address
1179 * completion entries terminates. NOTE: this function assumes that it is
1180 * called upon destruction of the window.
1181 * \param mainwindow Main window.
1183 void address_completion_end(GtkWidget *mainwindow)
1185 /* if address_completion_end() is really called on closing the window,
1186 * we don't need to unregister the set_focus_cb */
1187 end_address_completion();
1190 /* if focus changes to another entry, then clear completion cache */
1191 static void address_completion_mainwindow_set_focus(GtkWindow *window,
1196 if (widget && GTK_IS_ENTRY(widget) &&
1197 g_object_get_data(G_OBJECT(widget), ENTRY_DATA_TAB_HOOK)) {
1198 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), ENTRY_DATA_ALLOW_COMMAS));
1199 clear_completion_cache();
1204 * Listener that watches for tab or other keystroke in address entry field.
1205 * \param entry Address entry field.
1206 * \param ev Event object.
1207 * \param data User data.
1208 * \return <i>TRUE</i>.
1210 static gboolean address_completion_entry_key_pressed(GtkEntry *entry,
1214 if (ev->keyval == GDK_Tab) {
1215 addrcompl_clear_queue();
1216 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS));
1217 if( address_completion_complete_address_in_entry( entry, TRUE ) ) {
1218 /* route a void character to the default handler */
1219 /* this is a dirty hack; we're actually changing a key
1220 * reported by the system. */
1221 ev->keyval = GDK_AudibleBell_Enable;
1222 ev->state &= ~GDK_SHIFT_MASK;
1225 address_completion_create_completion_window(entry);
1227 /* Start remote queries */
1228 addrcompl_start_search();
1235 } else if (ev->keyval == GDK_Shift_L
1236 || ev->keyval == GDK_Shift_R
1237 || ev->keyval == GDK_Control_L
1238 || ev->keyval == GDK_Control_R
1239 || ev->keyval == GDK_Caps_Lock
1240 || ev->keyval == GDK_Shift_Lock
1241 || ev->keyval == GDK_Meta_L
1242 || ev->keyval == GDK_Meta_R
1243 || ev->keyval == GDK_Alt_L
1244 || ev->keyval == GDK_Alt_R) {
1245 /* these buttons should not clear the cache... */
1247 clear_completion_cache();
1252 * Initialize search term for address completion.
1253 * \param entry Address entry field.
1255 static gboolean address_completion_complete_address_in_entry(GtkEntry *entry,
1258 gint ncount, cursor_pos;
1259 gchar *searchTerm, *new = NULL;
1261 cm_return_val_if_fail(entry != NULL, FALSE);
1263 if (!GTK_WIDGET_HAS_FOCUS(entry)) return FALSE;
1265 /* get an address component from the cursor */
1266 searchTerm = get_address_from_edit( entry, &cursor_pos );
1267 if( ! searchTerm ) return FALSE;
1268 /* g_print( "search for :::%s:::\n", searchTerm ); */
1270 /* Clear any existing search */
1271 g_free( _compWindow_->searchTerm );
1272 _compWindow_->searchTerm = g_strdup( searchTerm );
1274 /* Perform search on local completion index */
1275 ncount = complete_address( searchTerm );
1277 new = get_next_complete_address();
1280 #if (!defined(USE_LDAP) && !defined(GENERIC_UMPC))
1281 /* Select the address if there is only one match */
1283 /* Display selected address in entry field */
1284 gchar *addr = get_complete_address(1);
1285 if (addr && !strstr(addr, " <!--___group___-->")) {
1286 replace_address_in_edit(entry, addr, cursor_pos, FALSE, NULL);
1287 /* Discard the window */
1288 clear_completion_cache();
1292 /* Make sure that drop-down appears uniform! */
1296 addrcompl_add_queue( g_strdup( searchTerm ) );
1298 g_free( searchTerm );
1304 * Create new address completion window for specified entry.
1305 * \param entry_ Entry widget to associate with window.
1307 static void address_completion_create_completion_window( GtkEntry *entry_ )
1309 gint x, y, height, width, depth;
1310 GtkWidget *scroll, *list_view;
1313 GtkWidget *entry = GTK_WIDGET(entry_);
1315 /* Create new window and list */
1316 window = gtk_window_new(GTK_WINDOW_POPUP);
1317 list_view = addr_compl_list_view_create(_compWindow_);
1319 /* Destroy any existing window */
1320 addrcompl_destroy_window( _compWindow_ );
1322 /* Create new object */
1323 _compWindow_->window = window;
1324 _compWindow_->entry = entry;
1325 _compWindow_->list_view = list_view;
1326 _compWindow_->listCount = 0;
1327 _compWindow_->in_mouse = FALSE;
1329 scroll = gtk_scrolled_window_new(NULL, NULL);
1330 gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
1331 GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
1332 gtk_container_add(GTK_CONTAINER(window), scroll);
1333 gtk_container_add(GTK_CONTAINER(scroll), list_view);
1334 gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll),
1336 /* Use entry widget to create initial window */
1337 gdk_window_get_geometry(entry->window, &x, &y, &width, &height, &depth);
1338 gdk_window_get_origin (entry->window, &x, &y);
1340 gtk_window_move(GTK_WINDOW(window), x, y);
1342 /* Resize window to fit initial (empty) address list */
1343 gtk_widget_size_request( list_view, &r );
1344 gtk_widget_set_size_request( window, width, r.height );
1345 gtk_widget_show_all( window );
1346 gtk_widget_size_request( list_view, &r );
1348 /* Setup handlers */
1349 g_signal_connect(G_OBJECT(list_view), "button_press_event",
1350 G_CALLBACK(list_view_button_press),
1353 g_signal_connect(G_OBJECT(list_view), "button_release_event",
1354 G_CALLBACK(list_view_button_release),
1357 g_signal_connect(G_OBJECT(window),
1358 "button-press-event",
1359 G_CALLBACK(completion_window_button_press),
1361 g_signal_connect(G_OBJECT(window),
1363 G_CALLBACK(completion_window_key_press),
1365 gdk_pointer_grab(window->window, TRUE,
1366 GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK |
1367 GDK_BUTTON_RELEASE_MASK,
1368 NULL, NULL, GDK_CURRENT_TIME);
1369 gtk_grab_add( window );
1373 * GTK1: this gets rid of the irritating focus rectangle that doesn't
1374 * follow the selection */
1375 GTK_WIDGET_UNSET_FLAGS(list_view, GTK_CAN_FOCUS);
1379 * Respond to button press in completion window. Check if mouse click is
1380 * anywhere outside the completion window. In that case the completion
1381 * window is destroyed, and the original searchTerm is restored.
1383 * \param widget Window object.
1384 * \param event Event.
1385 * \param compWin Reference to completion window.
1387 static gboolean completion_window_button_press(GtkWidget *widget,
1388 GdkEventButton *event,
1389 CompletionWindow *compWin )
1391 GtkWidget *event_widget, *entry;
1394 gboolean restore = TRUE;
1396 cm_return_val_if_fail(compWin != NULL, FALSE);
1398 entry = compWin->entry;
1399 cm_return_val_if_fail(entry != NULL, FALSE);
1401 /* Test where mouse was clicked */
1402 event_widget = gtk_get_event_widget((GdkEvent *)event);
1403 if (event_widget != widget) {
1404 while (event_widget) {
1405 if (event_widget == widget)
1407 else if (event_widget == entry) {
1411 event_widget = event_widget->parent;
1416 /* Clicked outside of completion window - restore */
1417 searchTerm = _compWindow_->searchTerm;
1418 g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1419 replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos, FALSE, NULL);
1422 clear_completion_cache();
1423 addrcompl_destroy_window( _compWindow_ );
1429 * Respond to key press in completion window.
1430 * \param widget Window object.
1431 * \param event Event.
1432 * \param compWind Reference to completion window.
1434 static gboolean completion_window_key_press(GtkWidget *widget,
1436 CompletionWindow *compWin )
1438 GdkEventKey tmp_event;
1442 GtkWidget *list_view;
1444 cm_return_val_if_fail(compWin != NULL, FALSE);
1446 entry = compWin->entry;
1447 list_view = compWin->list_view;
1448 cm_return_val_if_fail(entry != NULL, FALSE);
1450 /* allow keyboard navigation in the alternatives tree view */
1451 if (event->keyval == GDK_Up || event->keyval == GDK_Down ||
1452 event->keyval == GDK_Page_Up || event->keyval == GDK_Page_Down) {
1453 completion_window_advance_selection
1454 (GTK_TREE_VIEW(list_view),
1455 event->keyval == GDK_Down ||
1456 event->keyval == GDK_Page_Down ? TRUE : FALSE);
1460 /* make tab move to next field */
1461 if( event->keyval == GDK_Tab ) {
1462 /* Reference to parent */
1463 parent = GTK_WIDGET(entry)->parent;
1465 /* Discard the window */
1466 clear_completion_cache();
1467 addrcompl_destroy_window( _compWindow_ );
1469 /* Move focus to next widget */
1471 gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1476 /* make backtab move to previous field */
1477 if( event->keyval == GDK_ISO_Left_Tab ) {
1478 /* Reference to parent */
1479 parent = GTK_WIDGET(entry)->parent;
1481 /* Discard the window */
1482 clear_completion_cache();
1483 addrcompl_destroy_window( _compWindow_ );
1485 /* Move focus to previous widget */
1487 gtk_widget_child_focus( parent, GTK_DIR_TAB_BACKWARD );
1491 _allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS));
1493 /* look for presses that accept the selection */
1494 if (event->keyval == GDK_Return || event->keyval == GDK_space ||
1495 event->keyval == GDK_KP_Enter ||
1496 (_allowCommas_ && event->keyval == GDK_comma)) {
1497 /* User selected address with a key press */
1499 /* Display selected address in entry field */
1500 completion_window_apply_selection(
1501 GTK_TREE_VIEW(list_view), GTK_ENTRY(entry),
1502 event->keyval != GDK_comma);
1504 if (event->keyval == GDK_comma) {
1505 gint pos = gtk_editable_get_position(GTK_EDITABLE(entry));
1506 gtk_editable_insert_text(GTK_EDITABLE(entry), ", ", 2, &pos);
1507 gtk_editable_set_position(GTK_EDITABLE(entry), pos + 1);
1510 /* Discard the window */
1511 clear_completion_cache();
1512 addrcompl_destroy_window( _compWindow_ );
1516 /* key state keys should never be handled */
1517 if (event->keyval == GDK_Shift_L
1518 || event->keyval == GDK_Shift_R
1519 || event->keyval == GDK_Control_L
1520 || event->keyval == GDK_Control_R
1521 || event->keyval == GDK_Caps_Lock
1522 || event->keyval == GDK_Shift_Lock
1523 || event->keyval == GDK_Meta_L
1524 || event->keyval == GDK_Meta_R
1525 || event->keyval == GDK_Alt_L
1526 || event->keyval == GDK_Alt_R) {
1530 /* some other key, let's restore the searchTerm (orignal text) */
1531 searchTerm = _compWindow_->searchTerm;
1532 g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1533 replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos, FALSE, NULL);
1535 /* make sure anything we typed comes in the edit box */
1536 tmp_event.type = event->type;
1537 tmp_event.window = entry->window;
1538 tmp_event.send_event = TRUE;
1539 tmp_event.time = event->time;
1540 tmp_event.state = event->state;
1541 tmp_event.keyval = event->keyval;
1542 tmp_event.length = event->length;
1543 tmp_event.string = event->string;
1544 gtk_widget_event(entry, (GdkEvent *)&tmp_event);
1546 /* and close the completion window */
1547 clear_completion_cache();
1548 addrcompl_destroy_window( _compWindow_ );
1554 * ============================================================================
1555 * Publically accessible functions.
1556 * ============================================================================
1560 * Setup completion object.
1562 void addrcompl_initialize( void ) {
1563 /* g_print( "addrcompl_initialize...\n" ); */
1564 if( ! _compWindow_ ) {
1565 _compWindow_ = addrcompl_create_window();
1568 _completionIdleID_ = 0;
1569 /* g_print( "addrcompl_initialize...done\n" ); */
1573 * Teardown completion object.
1575 void addrcompl_teardown( void ) {
1576 /* g_print( "addrcompl_teardown...\n" ); */
1577 addrcompl_free_window( _compWindow_ );
1578 _compWindow_ = NULL;
1579 if( _displayQueue_ ) {
1580 g_list_free( _displayQueue_ );
1582 _displayQueue_ = NULL;
1583 _completionIdleID_ = 0;
1584 /* g_print( "addrcompl_teardown...done\n" ); */
1588 * tree view functions
1591 static GtkListStore *addr_compl_create_store(void)
1593 return gtk_list_store_new(N_ADDR_COMPL_COLUMNS,
1601 static GtkWidget *addr_compl_list_view_create(CompletionWindow *window)
1603 GtkTreeView *list_view;
1604 GtkTreeSelection *selector;
1605 GtkTreeModel *model;
1607 model = GTK_TREE_MODEL(addr_compl_create_store());
1608 list_view = GTK_TREE_VIEW(gtk_tree_view_new_with_model(model));
1609 g_object_unref(model);
1611 gtk_tree_view_set_rules_hint(list_view, prefs_common.use_stripes_everywhere);
1612 gtk_tree_view_set_headers_visible(list_view, FALSE);
1614 selector = gtk_tree_view_get_selection(list_view);
1615 gtk_tree_selection_set_mode(selector, GTK_SELECTION_BROWSE);
1616 gtk_tree_selection_set_select_function(selector, addr_compl_selected,
1619 /* create the columns */
1620 addr_compl_create_list_view_columns(GTK_WIDGET(list_view));
1622 return GTK_WIDGET(list_view);
1625 static void addr_compl_create_list_view_columns(GtkWidget *list_view)
1627 GtkTreeViewColumn *column;
1628 GtkCellRenderer *renderer;
1630 renderer = gtk_cell_renderer_pixbuf_new();
1631 column = gtk_tree_view_column_new_with_attributes
1633 "pixbuf", ADDR_COMPL_ICON, NULL);
1634 gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);
1635 renderer = gtk_cell_renderer_text_new();
1636 column = gtk_tree_view_column_new_with_attributes
1637 ("", renderer, "text", ADDR_COMPL_ADDRESS, NULL);
1638 gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);
1641 static gboolean list_view_button_press(GtkWidget *widget, GdkEventButton *event,
1642 CompletionWindow *window)
1644 if (window && event && event->type == GDK_BUTTON_PRESS) {
1645 window->in_mouse = TRUE;
1650 static gboolean list_view_button_release(GtkWidget *widget, GdkEventButton *event,
1651 CompletionWindow *window)
1653 if (window && event && event->type == GDK_BUTTON_RELEASE) {
1654 window->in_mouse = FALSE;
1659 static gboolean addr_compl_selected(GtkTreeSelection *selector,
1660 GtkTreeModel *model,
1662 gboolean currently_selected,
1665 CompletionWindow *window = data;
1667 if (currently_selected)
1670 if (!window->in_mouse)
1673 /* XXX: select the entry and kill window later... select is called before
1674 * any other mouse events handlers including the tree view internal one;
1675 * not using a time out would result in a crash. if this doesn't work
1676 * safely, maybe we should set variables when receiving button presses
1677 * in the tree view. */
1678 if (!window->destroying) {
1679 window->destroying = TRUE;
1680 g_idle_add((GSourceFunc) addr_compl_defer_select_destruct, data);
1686 static gboolean addr_compl_defer_select_destruct(CompletionWindow *window)
1688 GtkEntry *entry = GTK_ENTRY(window->entry);
1690 completion_window_apply_selection(GTK_TREE_VIEW(window->list_view),
1693 clear_completion_cache();
1695 addrcompl_destroy_window(window);