1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  *
4  * Copyright (C) 2000-2012 by Alfons Hoogervorst & The Claws Mail Team.
5  *
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.
10  *
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.
15  *
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/>.
18  *
19  */
20 
21 #ifdef HAVE_CONFIG_H
22 #  include "config.h"
23 #include "claws-features.h"
24 #endif
25 #include "defs.h"
26 
27 #include <glib.h>
28 #include <glib/gi18n.h>
29 #include <gdk/gdkkeysyms.h>
30 #include <gtk/gtk.h>
31 
32 #include <string.h>
33 #include <ctype.h>
34 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
35 #  include <wchar.h>
36 #  include <wctype.h>
37 #endif
38 
39 #include "addr_compl.h"
40 #include "addritem.h"
41 #include "utils.h"
42 #include "prefs_common.h"
43 #include "claws.h"
44 #include "hooks.h"
45 #include "gtkutils.h"
46 #include "stock_pixmap.h"
47 #include <pthread.h>
48 
49 #ifndef USE_ALT_ADDRBOOK
50 	#include "addrindex.h"
51 #else
52 	#include "addressbook-dbus.h"
53 #endif
54 
55 /*!
56  *\brief	For the GtkListStore
57  */
58 enum {
59 	ADDR_COMPL_ICON,
60 	ADDR_COMPL_ADDRESS,
61 	ADDR_COMPL_ISGROUP,
62 	ADDR_COMPL_GROUPLIST,
63 	N_ADDR_COMPL_COLUMNS
64 };
65 
66 /*
67  * How it works:
68  *
69  * The address book is read into memory. We set up an address list
70  * containing all address book entries. Next we make the completion
71  * list, which contains all the completable strings, and store a
72  * reference to the address entry it belongs to.
73  * After calling the g_completion_complete(), we get a reference
74  * to a valid email address.
75  *
76  * Completion is very simplified. We never complete on another prefix,
77  * i.e. we neglect the next smallest possible prefix for the current
78  * completion cache. This is simply done so we might break up the
79  * addresses a little more (e.g. break up alfons@proteus.demon.nl into
80  * something like alfons, proteus, demon, nl; and then completing on
81  * any of those words).
82  */
83 
84 /**
85  * completion_entry - structure used to complete addresses, with a reference
86  * the the real address information.
87  */
88 typedef struct
89 {
90 	gchar		*string; /* string to complete */
91 	address_entry	*ref;	 /* address the string belongs to  */
92 } completion_entry;
93 
94 /*******************************************************************************/
95 
96 static gint	    g_ref_count;	/* list ref count */
97 static GList 	   *g_completion_list = NULL;	/* list of strings to be checked */
98 static GList 	   *g_address_list = NULL;	/* address storage */
99 static GCompletion *g_completion;	/* completion object */
100 
101 static GHashTable *_groupAddresses_ = NULL;
102 static gboolean _allowCommas_ = TRUE;
103 
104 /* To allow for continuing completion we have to keep track of the state
105  * using the following variables. No need to create a context object. */
106 
107 static gint	    g_completion_count;		/* nr of addresses incl. the prefix */
108 static gint	    g_completion_next;		/* next prev address */
109 static GSList	   *g_completion_addresses;	/* unique addresses found in the
110 						   completion cache. */
111 static gchar	   *g_completion_prefix;	/* last prefix. (this is cached here
112 						 * because the prefix passed to g_completion
113 						 * is g_utf8_strdown()'ed */
114 
115 static gchar *completion_folder_path = NULL;
116 
117 /*******************************************************************************/
118 
119 /*
120  * Define the structure of the completion window.
121  */
122 typedef struct _CompletionWindow CompletionWindow;
123 struct _CompletionWindow {
124 	gint      listCount;
125 	gchar     *searchTerm;
126 	GtkWidget *window;
127 	GtkWidget *entry;
128 	GtkWidget *list_view;
129 
130 	gboolean   in_mouse;	/*!< mouse press pending... */
131 	gboolean   destroying;  /*!< destruction in progress */
132 };
133 
134 static GtkListStore *addr_compl_create_store	(void);
135 
136 static GtkWidget *addr_compl_list_view_create	(CompletionWindow *window);
137 
138 static void addr_compl_create_list_view_columns	(GtkWidget *list_view);
139 
140 static gboolean list_view_button_press		(GtkWidget *widget,
141 						 GdkEventButton *event,
142 						 CompletionWindow *window);
143 
144 static gboolean list_view_button_release	(GtkWidget *widget,
145 						 GdkEventButton *event,
146 						 CompletionWindow *window);
147 
148 static gboolean addr_compl_selected		(GtkTreeSelection *selector,
149 						 GtkTreeModel *model,
150 						 GtkTreePath *path,
151 						 gboolean currently_selected,
152 						 gpointer data);
153 
154 static gboolean addr_compl_defer_select_destruct(CompletionWindow *window);
155 
156 /**
157  * Function used by GTK to find the string data to be used for completion.
158  * \param data Pointer to data being processed.
159  */
completion_func(gpointer data)160 static gchar *completion_func(gpointer data)
161 {
162 	cm_return_val_if_fail(data != NULL, NULL);
163 
164 	return ((completion_entry *)data)->string;
165 }
166 
addr_completion_func(const gchar * needle,const gchar * haystack,gsize n)167 static gint addr_completion_func(const gchar *needle, const gchar *haystack,
168 		gsize n)
169 {
170 	if (needle == NULL || haystack == NULL)
171 		return 1;
172 
173 	return (strcasestr(haystack, needle) != NULL ? 0 : 1);
174 }
175 
176 /**
177  * Function used by GTK to compare elements for sorting
178  * name match beginning > name match after space > email address
179  *   match beginning and full match before @ > email adress
180  *   match beginning. Otherwise match position in string.
181  * \param a first element in comparsion
182  * \param b second element in comparison
183  */
weight_addr_match(const address_entry * addr)184 static gint weight_addr_match(const address_entry* addr)
185 {
186 	gint	n_weight = addr->name ? strlen(addr->name): 0;
187 	gint	a_weight = addr->address ? strlen(addr->address) : n_weight;
188 	gchar* 	match = NULL;
189 
190 	if (addr->name)
191 		match = strcasestr(addr->name, g_completion_prefix);
192 
193 	if (match != NULL) {
194 		if (match == addr->name)
195 			n_weight = -4;
196 		else if (match > addr->name && *(match - 1) == ' ')
197 			n_weight = -3;
198 		else
199 			n_weight = match - addr->name;
200 	}
201 
202 	if (addr->address) {
203 		match = strcasestr(addr->address, g_completion_prefix);
204 		if (match != NULL) {
205 			if (match == addr->address)
206 				a_weight = -1;
207 			else
208 				a_weight = match - addr->address;
209 
210 			if (strlen(match) > strlen(g_completion_prefix)
211 			 && *(match + strlen(g_completion_prefix)) == '@')
212 				a_weight--;
213 		}
214 	}
215 
216 	if (n_weight == -4 && a_weight < 0)
217 		n_weight = -5;
218 
219 	return MIN(a_weight, n_weight);
220 }
221 
addr_comparison_func(gconstpointer a,gconstpointer b)222 static gint addr_comparison_func(gconstpointer a, gconstpointer b)
223 {
224 	const address_entry*	a_ref = (const address_entry*)a;
225 	const address_entry*	b_ref = (const address_entry*)b;
226 	gint			a_weight = weight_addr_match(a_ref);
227 	gint			b_weight = weight_addr_match(b_ref);
228 	gint			cmp;
229 
230 	if (a_weight < b_weight)
231 		return -1;
232 	else if (a_weight > b_weight)
233 		return 1;
234 	else {
235                 if (!a_ref->name || !b_ref->name)
236                   cmp = !!a_ref->name - !!b_ref->name;
237                 else
238                   cmp = strcmp(a_ref->name, b_ref->name);
239                 if (!cmp)
240                   {
241                     if (!a_ref->address || !b_ref->address)
242                       cmp = !!a_ref->address - !!b_ref->address;
243                     else
244                       cmp = g_strcmp0(a_ref->address, b_ref->address);
245                   }
246                 return cmp;
247 	}
248 }
249 
250 /**
251  * Initialize all completion index data.
252  */
init_all(void)253 static void init_all(void)
254 {
255 	g_completion = g_completion_new(completion_func);
256 	cm_return_if_fail(g_completion != NULL);
257 }
258 
259 /**
260  * set the compare function (default is strncmp)
261  */
set_match_any_part(const gboolean any_part)262 static void set_match_any_part(const gboolean any_part)
263 {
264 	if (any_part && prefs_common.address_search_wildcard)
265 		g_completion_set_compare(g_completion, addr_completion_func);
266 	else
267 		g_completion_set_compare(g_completion, strncmp);
268 }
269 
free_all_addresses(void)270 static void free_all_addresses(void)
271 {
272 	GList *walk;
273 	if (!g_address_list)
274 		return;
275 	walk = g_address_list;
276 	for (; walk != NULL; walk = g_list_next(walk)) {
277 		address_entry *ae = (address_entry *) walk->data;
278 		g_free(ae->name);
279 		g_free(ae->address);
280 		g_list_free(ae->grp_emails);
281 		g_free(walk->data);
282 	}
283 	g_list_free(g_address_list);
284 	g_address_list = NULL;
285 	if (_groupAddresses_)
286 		g_hash_table_destroy(_groupAddresses_);
287 	_groupAddresses_ = NULL;
288 }
289 
290 static void clear_completion_cache(void);
free_completion_list(void)291 static void free_completion_list(void)
292 {
293 	GList *walk;
294 	if (!g_completion_list)
295 		return;
296 
297 	clear_completion_cache();
298 	if (g_completion)
299 		g_completion_clear_items(g_completion);
300 
301 	walk = g_list_first(g_completion_list);
302 	for (; walk != NULL; walk = g_list_next(walk)) {
303 		completion_entry *ce = (completion_entry *) walk->data;
304 		g_free(ce->string);
305 		g_free(walk->data);
306 	}
307 	g_list_free(g_completion_list);
308 	g_completion_list = NULL;
309 }
310 /**
311  * Free up all completion index data.
312  */
free_all(void)313 static void free_all(void)
314 {
315 	free_completion_list();
316 	free_all_addresses();
317 	g_completion_free(g_completion);
318 	g_completion = NULL;
319 }
320 
321 /**
322  * Append specified address entry to the index.
323  * \param str Index string value.
324  * \param ae  Entry containing address data.
325  */
addr_compl_add_address1(const char * str,address_entry * ae)326 void addr_compl_add_address1(const char *str, address_entry *ae)
327 {
328 	completion_entry *ce1;
329 	ce1 = g_new0(completion_entry, 1),
330 	/* GCompletion list is case sensitive */
331 	ce1->string = g_utf8_strdown(str, -1);
332 	ce1->ref = ae;
333 
334 	g_completion_list = g_list_prepend(g_completion_list, ce1);
335 }
336 
337 /**
338  * Adds address to the completion list. This function looks complicated, but
339  * it's only allocation checks. Each value will be included in the index.
340  * \param name    Recipient name.
341  * \param address EMail address.
342  * \param alias   Alias to append.
343  * \param grp_emails the emails in case of a group. List should be freed later,
344  * but not its strings
345  * \return <code>0</code> if entry appended successfully, or <code>-1</code>
346  *         if failure.
347  */
add_address(const gchar * name,const gchar * address,const gchar * nick,const gchar * alias,GList * grp_emails)348 static gint add_address(const gchar *name, const gchar *address,
349 			const gchar *nick, const gchar *alias, GList *grp_emails)
350 {
351 	address_entry *ae;
352 
353 	if (!address && !grp_emails)
354 		return -1;
355 
356 	if (!name)
357 		name = "";
358 
359 	ae = g_new0(address_entry, 1);
360 	cm_return_val_if_fail(ae != NULL, -1);
361 
362 	ae->name = g_strdup(name);
363 	ae->address = g_strdup(address);
364 	ae->grp_emails = grp_emails;
365 	g_address_list = g_list_prepend(g_address_list, ae);
366 
367 	addr_compl_add_address1(name, ae);
368 
369 	if (address != NULL && *address != '\0')
370 		addr_compl_add_address1(address, ae);
371 
372 	if (nick != NULL && *nick != '\0')
373 		addr_compl_add_address1(nick, ae);
374 
375 	if (alias != NULL && *alias != '\0')
376 		addr_compl_add_address1(alias, ae);
377 
378 	return 0;
379 }
380 
381 /**
382  * Read address book, creating all entries in the completion index.
383  */
read_address_book(gchar * folderpath)384 static void read_address_book(gchar *folderpath) {
385 	free_all_addresses();
386 	free_completion_list();
387 
388 #ifndef USE_ALT_ADDRBOOK
389 	addrindex_load_completion( add_address, folderpath );
390 #else
391 	GError* error = NULL;
392 
393 	addrcompl_initialize();
394 	if (! addrindex_dbus_load_completion(add_address, &error)) {
395 		g_warning("Failed to populate address completion list");
396         g_error_free(error);
397 		return;
398 	}
399 #endif
400 	/* plugins may hook in here to modify/extend the completion list */
401 	if(!folderpath) {
402 		hooks_invoke(ADDDRESS_COMPLETION_BUILD_ADDRESS_LIST_HOOKLIST, &g_address_list);
403 	}
404 
405 	g_address_list = g_list_reverse(g_address_list);
406 	g_completion_list = g_list_reverse(g_completion_list);
407 	/* merge the completion entry list into g_completion */
408 	if (g_completion_list) {
409 		g_completion_add_items(g_completion, g_completion_list);
410 		if (debug_get_mode())
411 			debug_print("read %d items in %s\n",
412 				g_list_length(g_completion_list),
413 				folderpath?folderpath:"(null)");
414 	}
415 }
416 
417 /**
418  * Test whether there is a completion pending.
419  * \return <code>TRUE</code> if pending.
420  */
is_completion_pending(void)421 static gboolean is_completion_pending(void)
422 {
423 	/* check if completion pending, i.e. we might satisfy a request for the next
424 	 * or previous address */
425 	 return g_completion_count;
426 }
427 
428 /**
429  * Clear the completion cache.
430  */
clear_completion_cache(void)431 static void clear_completion_cache(void)
432 {
433 	if (is_completion_pending()) {
434 		g_free(g_completion_prefix);
435 
436 		if (g_completion_addresses) {
437 			g_slist_free(g_completion_addresses);
438 			g_completion_addresses = NULL;
439 		}
440 
441 		g_completion_count = g_completion_next = 0;
442 	}
443 }
444 
445 /**
446  * Prepare completion index. This function should be called prior to attempting
447  * address completion.
448  * \return The number of addresses in the completion list.
449  */
start_address_completion(gchar * folderpath)450 guint start_address_completion(gchar *folderpath)
451 {
452 	gboolean different_book = FALSE;
453 	clear_completion_cache();
454 
455 	if (g_strcmp0(completion_folder_path,folderpath))
456 		different_book = TRUE;
457 
458 	g_free(completion_folder_path);
459 	if (folderpath != NULL)
460 		completion_folder_path = g_strdup(folderpath);
461 	else
462 		completion_folder_path = NULL;
463 
464 	if (!g_ref_count) {
465 		init_all();
466 		/* open the address book */
467 		read_address_book(folderpath);
468 	} else if (different_book)
469 		read_address_book(folderpath);
470 
471 	g_ref_count++;
472 	debug_print("start_address_completion(%s) ref count %d\n",
473 				folderpath?folderpath:"(null)", g_ref_count);
474 
475 	return g_list_length(g_completion_list);
476 }
477 
478 /**
479  * Retrieve a possible address (or a part) from an entry box. To make life
480  * easier, we only look at the last valid address component; address
481  * completion only works at the last string component in the entry box.
482  *
483  * \param entry Address entry field.
484  * \param start_pos Address of start position of address.
485  * \return Possible address.
486  */
get_address_from_edit(GtkEntry * entry,gint * start_pos)487 static gchar *get_address_from_edit(GtkEntry *entry, gint *start_pos)
488 {
489 	const gchar *edit_text, *p;
490 	gint cur_pos;
491 	gboolean in_quote = FALSE;
492 	gboolean in_bracket = FALSE;
493 	gchar *str;
494 
495 	edit_text = gtk_entry_get_text(entry);
496 	if (edit_text == NULL) return NULL;
497 
498 	cur_pos = gtk_editable_get_position(GTK_EDITABLE(entry));
499 
500 	/* scan for a separator. doesn't matter if walk points at null byte. */
501 	for (p = g_utf8_offset_to_pointer(edit_text, cur_pos);
502 	     p > edit_text;
503 	     p = g_utf8_prev_char(p)) {
504 		if (*p == '"') {
505 			in_quote = TRUE;
506 		} else if (!in_quote) {
507 			if (!in_bracket && *p == ',') {
508 				break;
509 			} else if (*p == '<')
510 				in_bracket = TRUE;
511 			else if (*p == '>')
512 				in_bracket = FALSE;
513 		}
514 	}
515 
516 	/* have something valid */
517 	if (g_utf8_strlen(p, -1) == 0)
518 		return NULL;
519 
520 #define IS_VALID_CHAR(x) \
521 	(g_ascii_isalnum(x) || (x) == '"' || (x) == '<' || (((unsigned char)(x)) > 0x7f))
522 
523 	/* now scan back until we hit a valid character */
524 	for (; *p && !IS_VALID_CHAR(*p); p = g_utf8_next_char(p))
525 		;
526 
527 #undef IS_VALID_CHAR
528 
529 	if (g_utf8_strlen(p, -1) == 0)
530 		return NULL;
531 
532 	if (start_pos) *start_pos = g_utf8_pointer_to_offset(edit_text, p);
533 
534 	str = g_strdup(p);
535 
536 	return str;
537 }
538 
get_complete_address_from_name_email(const gchar * name,const gchar * email)539 static gchar *get_complete_address_from_name_email(const gchar *name, const gchar *email)
540 {
541 	gchar *address = NULL;
542 	if (!name || name[0] == '\0')
543 		address = g_strdup_printf("<%s>", email);
544 	else if (strchr_with_skip_quote(name, '"', ','))
545 		address = g_strdup_printf
546 			("\"%s\" <%s>", name, email);
547 	else
548 		address = g_strdup_printf
549 			("%s <%s>", name, email);
550 	return address;
551 }
552 
553 /**
554  * Replace an incompleted address with a completed one.
555  * \param entry     Address entry field.
556  * \param newtext   New text.
557  * \param start_pos Insertion point in entry field.
558  */
replace_address_in_edit(GtkEntry * entry,const gchar * newtext,gint start_pos,gboolean is_group,GList * grp_emails)559 static void replace_address_in_edit(GtkEntry *entry, const gchar *newtext,
560 			     gint start_pos, gboolean is_group, GList *grp_emails)
561 {
562 	if (!newtext) return;
563 	gtk_editable_delete_text(GTK_EDITABLE(entry), start_pos, -1);
564 	if (!is_group) {
565 		gtk_editable_insert_text(GTK_EDITABLE(entry), newtext, strlen(newtext),
566 				 &start_pos);
567 	} else {
568 		gchar *addresses = NULL;
569 		GList *cur = grp_emails;
570 		for (; cur; cur = cur->next) {
571 			gchar *tmp;
572 			ItemEMail *email = (ItemEMail *)cur->data;
573 			ItemPerson *person = ( ItemPerson * ) ADDRITEM_PARENT(email);
574 
575 			gchar *addr = get_complete_address_from_name_email(
576 				ADDRITEM_NAME(person), email->address);
577 			if (addresses)
578 				tmp = g_strdup_printf("%s, %s", addresses, addr);
579 			else
580 				tmp = g_strdup_printf("%s", addr);
581 			g_free(addr);
582 			g_free(addresses);
583 			addresses = tmp;
584 		}
585 		gtk_editable_insert_text(GTK_EDITABLE(entry), addresses, strlen(addresses),
586 				 &start_pos);
587 		g_free(addresses);
588 	}
589 	gtk_editable_set_position(GTK_EDITABLE(entry), -1);
590 }
591 
592 /**
593  * Attempt to complete an address, and returns the number of addresses found.
594  * Use <code>get_complete_address()</code> to get an entry from the index.
595  *
596  * \param  str Search string to find.
597  * \return Zero if no match was found, otherwise the number of addresses; the
598  *         original prefix (search string) will appear at index 0.
599  */
complete_address(const gchar * str)600 guint complete_address(const gchar *str)
601 {
602 	GList *result = NULL;
603 	gchar *d = NULL;
604 	guint  count = 0;
605 	guint  cpl = 0;
606 	completion_entry *ce = NULL;
607 
608 	cm_return_val_if_fail(str != NULL, 0);
609 
610 	/* g_completion is case sensitive */
611 	d = g_utf8_strdown(str, -1);
612 
613 	clear_completion_cache();
614 	g_completion_prefix = g_strdup(str);
615 
616 	result = g_completion_complete(g_completion, d, NULL);
617 
618 	count = g_list_length(result);
619 	if (count) {
620 		/* create list with unique addresses  */
621 		for (cpl = 0, result = g_list_first(result);
622 		     result != NULL;
623 		     result = g_list_next(result)) {
624 			ce = (completion_entry *)(result->data);
625 			if (NULL == g_slist_find(g_completion_addresses,
626 						 ce->ref)) {
627 				cpl++;
628 				g_completion_addresses =
629 					g_slist_append(g_completion_addresses,
630 						       ce->ref);
631 			}
632 		}
633 		count = cpl + 1;	/* index 0 is the original prefix */
634 		g_completion_next = 1;	/* we start at the first completed one */
635 		if (prefs_common.address_search_wildcard)
636 		    g_completion_addresses = g_slist_sort(g_completion_addresses,
637 							  addr_comparison_func);
638 	} else {
639 		g_free(g_completion_prefix);
640 		g_completion_prefix = NULL;
641 	}
642 
643 	g_completion_count = count;
644 
645 	g_free(d);
646 
647 	return count;
648 }
649 
650 /**
651  * complete_matches_found() returns the number of matched addresses according
652  * to the completion mechanism. Unlike complete_address(), the returned value
653  * doesn't count str itself. If there's no match, it returns 0.
654  * To get a list of completion matches, see complete_address() instead.
655  */
complete_matches_found(const gchar * str)656 guint complete_matches_found(const gchar *str)
657 {
658 	GList *result = NULL;
659 	gchar *d = NULL;
660 
661 	cm_return_val_if_fail(str != NULL, 0);
662 
663 	/* g_completion is case sensitive */
664 	d = g_utf8_strdown(str, -1);
665 
666 	clear_completion_cache();
667 	g_completion_prefix = g_strdup(str);
668 
669 	result = g_completion_complete(g_completion, d, NULL);
670 
671 	g_free(g_completion_prefix);
672 	g_free(d);
673 
674 	return g_list_length(result);
675 }
676 
677 /**
678  * Return a complete address from the index.
679  * \param index Index of entry that was found (by the previous call to
680  *              <code>complete_address()</code>
681  * \return Completed address string; this should be freed when done.
682  */
get_complete_address(gint index)683 gchar *get_complete_address(gint index)
684 {
685 	const address_entry *p;
686 	gchar *address = NULL;
687 
688 	if (index < g_completion_count) {
689 		if (index == 0)
690 			address = g_strdup(g_completion_prefix);
691 		else {
692 			/* get something from the unique addresses */
693 			p = (address_entry *)g_slist_nth_data
694 				(g_completion_addresses, index - 1);
695 			if (p != NULL && p->address != NULL) {
696 				address = get_complete_address_from_name_email(p->name, p->address);
697 			} else if (p != NULL && p->address == NULL && p->name != NULL) {
698 				/* that's a group */
699 				address = g_strdup_printf("%s (%s) <!--___group___-->", p->name, _("Group"));
700 				if (!_groupAddresses_) {
701 					_groupAddresses_ = g_hash_table_new(NULL, g_direct_equal);
702 				}
703 				if (!g_hash_table_lookup(_groupAddresses_, GINT_TO_POINTER(g_str_hash(address)))) {
704 					g_hash_table_insert(_groupAddresses_, GINT_TO_POINTER(g_str_hash(address)), p->grp_emails);
705 
706 				}
707 			}
708 		}
709 	}
710 
711 	return address;
712 }
713 
714 /**
715  * Return the next complete address match from the completion index.
716  * \return Completed address string; this should be freed when done.
717  */
get_next_complete_address(void)718 static gchar *get_next_complete_address(void)
719 {
720 	if (is_completion_pending()) {
721 		gchar *res;
722 
723 		res = get_complete_address(g_completion_next);
724 		g_completion_next += 1;
725 		if (g_completion_next >= g_completion_count)
726 			g_completion_next = 0;
727 
728 		return res;
729 	} else
730 		return NULL;
731 }
732 
733 /**
734  * Return a count of the completed matches in the completion index.
735  * \return Number of matched entries.
736  */
get_completion_count(void)737 static guint get_completion_count(void)
738 {
739 	if (is_completion_pending())
740 		return g_completion_count;
741 	else
742 		return 0;
743 }
744 
745 /**
746  * Invalidate address completion index. This function should be called whenever
747  * the address book changes. This forces data to be read into the completion
748  * data.
749  * \return Number of entries in index.
750  */
invalidate_address_completion(void)751 gint invalidate_address_completion(void)
752 {
753 	if (g_ref_count) {
754 		/* simply the same as start_address_completion() */
755 		debug_print("Invalidation request for address completion\n");
756 		read_address_book(completion_folder_path);
757 		clear_completion_cache();
758 	}
759 
760 	return g_list_length(g_completion_list);
761 }
762 
763 /**
764  * Finished with completion index. This function should be called after
765  * matching addresses.
766  * \return Reference count.
767  */
end_address_completion(void)768 gint end_address_completion(void)
769 {
770 	gboolean different_folder = FALSE;
771 	clear_completion_cache();
772 
773 	/* reset the folderpath to NULL */
774 	if (completion_folder_path) {
775 		g_free(completion_folder_path);
776 		completion_folder_path = NULL;
777 		different_folder = TRUE;
778 	}
779 	if (0 == --g_ref_count)
780 		free_all();
781 
782 	debug_print("end_address_completion ref count %d\n", g_ref_count);
783 	if (g_ref_count && different_folder) {
784 		debug_print("still ref'd, different folder\n");
785 		invalidate_address_completion();
786 	}
787 
788 	return g_ref_count;
789 }
790 
791 /**
792  * Completion window.
793  */
794 static CompletionWindow *_compWindow_ = NULL;
795 
796 /**
797  * Mutex to protect callback from multiple threads.
798  */
799 static pthread_mutex_t _completionMutex_ = PTHREAD_MUTEX_INITIALIZER;
800 
801 /**
802  * Completion queue list.
803  */
804 static GList *_displayQueue_ = NULL;
805 /**
806  * Current query ID.
807  */
808 static gint _queryID_ = 0;
809 
810 /**
811  * Completion idle ID.
812  */
813 static guint _completionIdleID_ = 0;
814 
815 /*
816  * address completion entry ui. the ui (completion list was inspired by galeon's
817  * auto completion list). remaining things powered by claws's completion engine.
818  */
819 
820 #define ENTRY_DATA_TAB_HOOK	"tab_hook"	/* used to lookup entry */
821 #define ENTRY_DATA_ALLOW_COMMAS	"allowcommas"	/* used to know whether to present groups */
822 
823 static void address_completion_mainwindow_set_focus	(GtkWindow   *window,
824 							 GtkWidget   *widget,
825 							 gpointer     data);
826 static gboolean address_completion_entry_key_pressed	(GtkEntry    *entry,
827 							 GdkEventKey *ev,
828 							 gpointer     data);
829 static gboolean address_completion_complete_address_in_entry
830 							(GtkEntry    *entry,
831 							 gboolean     next);
832 static void address_completion_create_completion_window	(GtkEntry    *entry);
833 
834 static gboolean completion_window_button_press
835 					(GtkWidget	 *widget,
836 					 GdkEventButton  *event,
837 					 CompletionWindow *compWin );
838 
839 static gboolean completion_window_key_press
840 					(GtkWidget	 *widget,
841 					 GdkEventKey	 *event,
842 					 CompletionWindow *compWin );
843 static void address_completion_create_completion_window( GtkEntry *entry_ );
844 
845 /**
846  * Create a completion window object.
847  * \return Initialized completion window.
848  */
addrcompl_create_window(void)849 static CompletionWindow *addrcompl_create_window( void ) {
850 	CompletionWindow *cw;
851 
852 	cw = g_new0( CompletionWindow, 1 );
853 	cw->listCount = 0;
854 	cw->searchTerm = NULL;
855 	cw->window = NULL;
856 	cw->entry = NULL;
857 	cw->list_view = NULL;
858 	cw->in_mouse = FALSE;
859 	cw->destroying = FALSE;
860 
861 	return cw;
862 }
863 
864 /**
865  * Destroy completion window.
866  * \param cw Window to destroy.
867  */
addrcompl_destroy_window(CompletionWindow * cw)868 static void addrcompl_destroy_window( CompletionWindow *cw ) {
869 	/* Stop all searches currently in progress */
870 #ifndef USE_ALT_ADDRBOOK
871 	addrindex_stop_search( _queryID_ );
872 #endif
873 	/* Remove idler function... or application may not terminate */
874 	if( _completionIdleID_ != 0 ) {
875 		g_source_remove( _completionIdleID_ );
876 		_completionIdleID_ = 0;
877 	}
878 
879 	/* Now destroy window */
880 	if( cw ) {
881 		/* Clear references to widgets */
882 		cw->entry = NULL;
883 		cw->list_view = NULL;
884 
885 		/* Free objects */
886 		if( cw->window ) {
887 			gtk_widget_hide( cw->window );
888 			gtk_widget_destroy( cw->window );
889 		}
890 		cw->window = NULL;
891 		cw->destroying = FALSE;
892 		cw->in_mouse = FALSE;
893 	}
894 
895 	/* Re-enable keyboard, required at least for Gtk3/Win32 */
896 	gdk_keyboard_ungrab(GDK_CURRENT_TIME);
897 }
898 
899 /**
900  * Free up completion window.
901  * \param cw Window to free.
902  */
addrcompl_free_window(CompletionWindow * cw)903 static void addrcompl_free_window( CompletionWindow *cw ) {
904 	if( cw ) {
905 		addrcompl_destroy_window( cw );
906 
907 		g_free( cw->searchTerm );
908 		cw->searchTerm = NULL;
909 
910 		/* Clear references */
911 		cw->listCount = 0;
912 
913 		/* Free object */
914 		g_free( cw );
915 	}
916 }
917 
918 /**
919  * Advance selection to previous/next item in list.
920  * \param list_view List to process.
921  * \param forward Set to <i>TRUE</i> to select next or <i>FALSE</i> for
922  *                previous entry.
923  */
completion_window_advance_selection(GtkTreeView * list_view,gboolean forward)924 static void completion_window_advance_selection(GtkTreeView *list_view, gboolean forward)
925 {
926 	GtkTreeSelection *selection;
927 	GtkTreeIter iter;
928 	GtkTreeModel *model;
929 
930 	cm_return_if_fail(list_view != NULL);
931 
932 	selection = gtk_tree_view_get_selection(list_view);
933 	if (!gtk_tree_selection_get_selected(selection, &model, &iter))
934 		return;
935 
936 	if (forward) {
937 		forward = gtk_tree_model_iter_next(model, &iter);
938 		if (forward)
939 			gtk_tree_selection_select_iter(selection, &iter);
940 	} else {
941 		GtkTreePath *prev;
942 
943 		prev = gtk_tree_model_get_path(model, &iter);
944 		if (!prev)
945 			return;
946 
947 		if (gtk_tree_path_prev(prev))
948 			gtk_tree_selection_select_path(selection, prev);
949 
950 		gtk_tree_path_free(prev);
951 	}
952 }
953 
954 /**
955  * Resize window to accommodate maximum number of address entries.
956  * \param cw Completion window.
957  */
addrcompl_resize_window(CompletionWindow * cw)958 static void addrcompl_resize_window( CompletionWindow *cw ) {
959 	GtkRequisition r;
960 	GdkGrabStatus status;
961 	gint x, y, width, height, depth;
962 
963 	/* Get current geometry of window */
964 	gdk_window_get_geometry( gtk_widget_get_window( cw->window ), &x, &y, &width, &height, &depth );
965 
966 	gtk_widget_queue_resize_no_redraw(cw->list_view);
967 	gtk_widget_size_request( cw->list_view, &r );
968 
969 	/* Adjust window height to available screen space */
970 	if( y + r.height > gdk_screen_height())
971 		r.height = gdk_screen_height() - y;
972 
973 	gtk_widget_set_size_request(cw->window, width, r.height);
974 
975 	gdk_pointer_grab(gtk_widget_get_window(cw->window), TRUE,
976 			 GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK |
977 			 GDK_BUTTON_RELEASE_MASK,
978 			 NULL, NULL, GDK_CURRENT_TIME);
979 	status = gdk_keyboard_grab(gtk_widget_get_window(cw->window), FALSE, GDK_CURRENT_TIME);
980 	if (status != GDK_GRAB_SUCCESS)
981 		g_warning("gdk_keyboard_grab failed with status %d", status);
982 	gtk_grab_add(cw->window);
983 
984 }
985 
986 static GdkPixbuf *group_pixbuf = NULL;
987 static GdkPixbuf *email_pixbuf = NULL;
988 
989 /**
990  * Add an address the completion window address list.
991  * \param cw      Completion window.
992  * \param address Address to add.
993  */
addrcompl_add_entry(CompletionWindow * cw,gchar * address)994 static void addrcompl_add_entry( CompletionWindow *cw, gchar *address ) {
995 	GtkListStore *store;
996 	GtkTreeIter iter;
997 	GtkTreeSelection *selection;
998 	gboolean is_group = FALSE;
999 	GList *grp_emails = NULL;
1000 	store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(cw->list_view)));
1001 	GdkPixbuf *pixbuf;
1002 
1003 	if (!group_pixbuf) {
1004 		stock_pixbuf_gdk(STOCK_PIXMAP_ADDR_TWO, &group_pixbuf);
1005 		g_object_ref(G_OBJECT(group_pixbuf));
1006 	}
1007 	if (!email_pixbuf) {
1008 		stock_pixbuf_gdk(STOCK_PIXMAP_ADDR_ONE, &email_pixbuf);
1009 		g_object_ref(G_OBJECT(email_pixbuf));
1010 	}
1011 	/* g_print( "\t\tAdding :%s\n", address ); */
1012 	if (strstr(address, " <!--___group___-->")) {
1013 		is_group = TRUE;
1014 		if (_groupAddresses_)
1015 			grp_emails = g_hash_table_lookup(_groupAddresses_, GINT_TO_POINTER(g_str_hash(address)));
1016 		*(strstr(address, " <!--___group___-->")) = '\0';
1017 		pixbuf = group_pixbuf;
1018 	} else if (strchr(address, '@') && strchr(address, '<') &&
1019 		   strchr(address, '>')) {
1020 		pixbuf = email_pixbuf;
1021 	} else
1022 		pixbuf = NULL;
1023 
1024 	if (is_group && !_allowCommas_)
1025 		return;
1026 	gtk_list_store_append(store, &iter);
1027 	gtk_list_store_set(store, &iter,
1028 				ADDR_COMPL_ICON, pixbuf,
1029 				ADDR_COMPL_ADDRESS, address,
1030 				ADDR_COMPL_ISGROUP, is_group,
1031 				ADDR_COMPL_GROUPLIST, grp_emails,
1032 				-1);
1033 	cw->listCount++;
1034 
1035 	/* Resize window */
1036 	addrcompl_resize_window( cw );
1037 	gtk_grab_add( cw->window );
1038 
1039 	selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(cw->list_view));
1040 	if (!gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store), &iter))
1041 		return;
1042 
1043 	if (cw->listCount == 1) {
1044 		/* Select first row for now */
1045 		gtk_tree_selection_select_iter(selection, &iter);
1046 	}
1047 #ifndef GENERIC_UMPC
1048 	else if (cw->listCount == 2) {
1049 		if (gtk_tree_model_iter_next(GTK_TREE_MODEL(store), &iter)) {
1050 			/* Move off first row */
1051 			gtk_tree_selection_select_iter(selection, &iter);
1052 		}
1053 	}
1054 #endif
1055 }
1056 
addrcompl_reflect_prefs_pixmap_theme(void)1057 void addrcompl_reflect_prefs_pixmap_theme(void) {
1058 	if (group_pixbuf) {
1059 		g_object_unref(G_OBJECT(group_pixbuf));
1060 		group_pixbuf = NULL;
1061 	}
1062 	if (email_pixbuf) {
1063 		g_object_unref(G_OBJECT(email_pixbuf));
1064 		email_pixbuf = NULL;
1065 	}
1066 }
1067 
1068 /**
1069  * Completion idle function. This function is called by the main (UI) thread
1070  * during UI idle time while an address search is in progress. Items from the
1071  * display queue are processed and appended to the address list.
1072  *
1073  * \param data Target completion window to receive email addresses.
1074  * \return <i>TRUE</i> to ensure that idle event do not get ignored.
1075  */
addrcompl_idle(gpointer data)1076 static gboolean addrcompl_idle( gpointer data ) {
1077 	GList *node;
1078 	gchar *address;
1079 
1080 	/* Process all entries in display queue */
1081 	pthread_mutex_lock( & _completionMutex_ );
1082 	if( _displayQueue_ ) {
1083 		node = _displayQueue_;
1084 		while( node ) {
1085 			address = node->data;
1086 			/* g_print( "address ::: %s :::\n", address ); */
1087 			addrcompl_add_entry( _compWindow_, address );
1088 			g_free( address );
1089 			node = g_list_next( node );
1090 		}
1091 		g_list_free( _displayQueue_ );
1092 		_displayQueue_ = NULL;
1093 	}
1094 	pthread_mutex_unlock( & _completionMutex_ );
1095 	claws_do_idle();
1096 
1097 	return TRUE;
1098 }
1099 
1100 /**
1101  * Callback entry point. The background thread (if any) appends the address
1102  * list to the display queue.
1103  * \param sender     Sender of query.
1104  * \param queryID    Query ID of search request.
1105  * \param listEMail  List of zero of more email objects that met search
1106  *                   criteria.
1107  * \param data       Query data.
1108  */
1109 #ifndef USE_ALT_ADDRBOOK
addrcompl_callback_entry(gpointer sender,gint queryID,GList * listEMail,gpointer data)1110 static gint addrcompl_callback_entry(
1111 	gpointer sender, gint queryID, GList *listEMail, gpointer data )
1112 {
1113 	GList *node;
1114 	gchar *address;
1115 
1116 	/* g_print( "addrcompl_callback_entry::queryID=%d\n", queryID ); */
1117 	pthread_mutex_lock( & _completionMutex_ );
1118 	if( queryID == _queryID_ ) {
1119 		/* Append contents to end of display queue */
1120 		node = listEMail;
1121 		while( node ) {
1122 			ItemEMail *email = node->data;
1123 
1124 			address = addritem_format_email( email );
1125 			/* g_print( "\temail/address ::%s::\n", address ); */
1126 			_displayQueue_ = g_list_append( _displayQueue_, address );
1127 			node = g_list_next( node );
1128 		}
1129 	}
1130 	g_list_free( listEMail );
1131 	pthread_mutex_unlock( & _completionMutex_ );
1132 
1133 	return 0;
1134 }
1135 #endif
1136 
1137 /**
1138  * Clear the display queue.
1139  */
addrcompl_clear_queue(void)1140 static void addrcompl_clear_queue( void ) {
1141 	/* Clear out display queue */
1142 	pthread_mutex_lock( & _completionMutex_ );
1143 
1144 	g_list_free_full( _displayQueue_, g_free );
1145 	_displayQueue_ = NULL;
1146 
1147 	pthread_mutex_unlock( & _completionMutex_ );
1148 }
1149 
1150 /**
1151  * Add a single address entry into the display queue.
1152  * \param address Address to append.
1153  */
addrcompl_add_queue(gchar * address)1154 static void addrcompl_add_queue( gchar *address ) {
1155 	pthread_mutex_lock( & _completionMutex_ );
1156 	_displayQueue_ = g_list_append( _displayQueue_, address );
1157 	pthread_mutex_unlock( & _completionMutex_ );
1158 }
1159 
1160 /**
1161  * Load list with entries from local completion index.
1162  */
addrcompl_load_local(void)1163 static void addrcompl_load_local( void ) {
1164 	guint count = 0;
1165 
1166 	for (count = 0; count < get_completion_count(); count++) {
1167 		gchar *address;
1168 
1169 		address = get_complete_address( count );
1170 		/* g_print( "\taddress ::%s::\n", address ); */
1171 
1172 		/* Append contents to end of display queue */
1173 		addrcompl_add_queue( address );
1174 	}
1175 }
1176 
1177 /**
1178  * Start the search.
1179  */
addrcompl_start_search(void)1180 static void addrcompl_start_search( void ) {
1181 #ifndef USE_ALT_ADDRBOOK
1182 	gchar *searchTerm;
1183 
1184 	searchTerm = g_strdup( _compWindow_->searchTerm );
1185 
1186 	/* Setup the search */
1187 	_queryID_ = addrindex_setup_search(
1188 		searchTerm, NULL, addrcompl_callback_entry );
1189 	g_free( searchTerm );
1190 #endif
1191 	/* g_print( "addrcompl_start_search::queryID=%d\n", _queryID_ ); */
1192 
1193 	/* Load local stuff */
1194 	addrcompl_load_local();
1195 
1196 	/* Sit back and wait until something happens */
1197 	_completionIdleID_ =
1198 		g_idle_add( (GSourceFunc) addrcompl_idle, NULL );
1199 	/* g_print( "addrindex_start_search::queryID=%d\n", _queryID_ ); */
1200 
1201 #ifndef USE_ALT_ADDRBOOK
1202 	addrindex_start_search( _queryID_ );
1203 #else
1204 
1205 #endif
1206 }
1207 
1208 /**
1209  * Apply the current selection in the list to the entry field. Focus is also
1210  * moved to the next widget so that Tab key works correctly.
1211  * \param list_view List to process.
1212  * \param entry Address entry field.
1213  * \param move_focus Move focus to the next widget ?
1214  */
completion_window_apply_selection(GtkTreeView * list_view,GtkEntry * entry,gboolean move_focus)1215 static void completion_window_apply_selection(GtkTreeView *list_view,
1216 						GtkEntry *entry,
1217 						gboolean move_focus)
1218 {
1219 	gchar *address = NULL, *text = NULL;
1220 	gint   cursor_pos;
1221 	GtkWidget *parent;
1222 	GtkTreeSelection *selection;
1223 	GtkTreeModel *model;
1224 	GtkTreeIter iter;
1225 	gboolean is_group = FALSE;
1226 	cm_return_if_fail(list_view != NULL);
1227 	cm_return_if_fail(entry != NULL);
1228 	GList *grp_emails = NULL;
1229 
1230 	selection = gtk_tree_view_get_selection(list_view);
1231 	if (!gtk_tree_selection_get_selected(selection, &model, &iter))
1232 		return;
1233 
1234 	/* First remove the idler */
1235 	if( _completionIdleID_ != 0 ) {
1236 		g_source_remove( _completionIdleID_ );
1237 		_completionIdleID_ = 0;
1238 	}
1239 
1240 	/* Process selected item */
1241 	gtk_tree_model_get(model, &iter, ADDR_COMPL_ADDRESS, &text,
1242 				ADDR_COMPL_ISGROUP, &is_group,
1243 				ADDR_COMPL_GROUPLIST, &grp_emails,
1244 				-1);
1245 
1246 	address = get_address_from_edit(entry, &cursor_pos);
1247 	g_free(address);
1248 	replace_address_in_edit(entry, text, cursor_pos, is_group, grp_emails);
1249 	g_free(text);
1250 
1251 	/* Move focus to next widget */
1252 	parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1253 	if( parent && move_focus) {
1254 		gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1255 	}
1256 }
1257 
1258 /**
1259  * Start address completion. Should be called when creating the main window
1260  * containing address completion entries.
1261  * \param mainwindow Main window.
1262  */
address_completion_start(GtkWidget * mainwindow)1263 void address_completion_start(GtkWidget *mainwindow)
1264 {
1265 	start_address_completion(NULL);
1266 	set_match_any_part(TRUE);
1267 
1268 	/* register focus change hook */
1269 	g_signal_connect(G_OBJECT(mainwindow), "set_focus",
1270 			 G_CALLBACK(address_completion_mainwindow_set_focus),
1271 			 mainwindow);
1272 }
1273 
1274 /**
1275  * Need unique data to make unregistering signal handler possible for the auto
1276  * completed entry.
1277  */
1278 #define COMPLETION_UNIQUE_DATA (GINT_TO_POINTER(0xfeefaa))
1279 
1280 /**
1281  * Register specified entry widget for address completion.
1282  * \param entry Address entry field.
1283  */
address_completion_register_entry(GtkEntry * entry,gboolean allow_commas)1284 void address_completion_register_entry(GtkEntry *entry, gboolean allow_commas)
1285 {
1286 	cm_return_if_fail(entry != NULL);
1287 	cm_return_if_fail(GTK_IS_ENTRY(entry));
1288 
1289 	/* add hooked property */
1290 	g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, entry);
1291 	g_object_set_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS, GINT_TO_POINTER(allow_commas));
1292 
1293 	/* add keypress event */
1294 	g_signal_connect_closure
1295 		(G_OBJECT(entry), "key_press_event",
1296 		 g_cclosure_new(G_CALLBACK(address_completion_entry_key_pressed),
1297 				COMPLETION_UNIQUE_DATA,
1298 				NULL),
1299 		 FALSE); /* magic */
1300 }
1301 
1302 /**
1303  * Unregister specified entry widget from address completion operations.
1304  * \param entry Address entry field.
1305  */
address_completion_unregister_entry(GtkEntry * entry)1306 void address_completion_unregister_entry(GtkEntry *entry)
1307 {
1308 	GObject *entry_obj;
1309 
1310 	cm_return_if_fail(entry != NULL);
1311 	cm_return_if_fail(GTK_IS_ENTRY(entry));
1312 
1313 	entry_obj = g_object_get_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK);
1314 	cm_return_if_fail(entry_obj);
1315 	cm_return_if_fail(G_OBJECT(entry_obj) == G_OBJECT(entry));
1316 
1317 	/* has the hooked property? */
1318 	g_object_set_data(G_OBJECT(entry), ENTRY_DATA_TAB_HOOK, NULL);
1319 
1320 	/* remove the hook */
1321 	g_signal_handlers_disconnect_by_func(G_OBJECT(entry),
1322 			G_CALLBACK(address_completion_entry_key_pressed),
1323 			COMPLETION_UNIQUE_DATA);
1324 }
1325 
1326 /**
1327  * End address completion. Should be called when main window with address
1328  * completion entries terminates. NOTE: this function assumes that it is
1329  * called upon destruction of the window.
1330  * \param mainwindow Main window.
1331  */
address_completion_end(GtkWidget * mainwindow)1332 void address_completion_end(GtkWidget *mainwindow)
1333 {
1334 	/* if address_completion_end() is really called on closing the window,
1335 	 * we don't need to unregister the set_focus_cb */
1336 	end_address_completion();
1337 }
1338 
1339 /* if focus changes to another entry, then clear completion cache */
address_completion_mainwindow_set_focus(GtkWindow * window,GtkWidget * widget,gpointer data)1340 static void address_completion_mainwindow_set_focus(GtkWindow *window,
1341 						    GtkWidget *widget,
1342 						    gpointer   data)
1343 {
1344 
1345 	if (widget && GTK_IS_ENTRY(widget) &&
1346 	    g_object_get_data(G_OBJECT(widget), ENTRY_DATA_TAB_HOOK)) {
1347 		_allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(widget), ENTRY_DATA_ALLOW_COMMAS));
1348 		clear_completion_cache();
1349 	}
1350 }
1351 
1352 /**
1353  * Listener that watches for tab or other keystroke in address entry field.
1354  * \param entry Address entry field.
1355  * \param ev    Event object.
1356  * \param data  User data.
1357  * \return <i>TRUE</i>.
1358  */
address_completion_entry_key_pressed(GtkEntry * entry,GdkEventKey * ev,gpointer data)1359 static gboolean address_completion_entry_key_pressed(GtkEntry    *entry,
1360 						     GdkEventKey *ev,
1361 						     gpointer     data)
1362 {
1363 	if (ev->keyval == GDK_KEY_Tab) {
1364 		addrcompl_clear_queue();
1365 		_allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS));
1366 		if( address_completion_complete_address_in_entry( entry, TRUE ) ) {
1367 			/* route a void character to the default handler */
1368 			/* this is a dirty hack; we're actually changing a key
1369 			 * reported by the system. */
1370 			ev->keyval = GDK_KEY_AudibleBell_Enable;
1371 			ev->state &= ~GDK_SHIFT_MASK;
1372 
1373 			/* Create window */
1374 			address_completion_create_completion_window(entry);
1375 
1376 			/* Start remote queries */
1377 			addrcompl_start_search();
1378 
1379 			return TRUE;
1380 		}
1381 		else {
1382 			/* old behaviour */
1383 		}
1384 	} else if (ev->keyval == GDK_KEY_Shift_L
1385 		|| ev->keyval == GDK_KEY_Shift_R
1386 		|| ev->keyval == GDK_KEY_Control_L
1387 		|| ev->keyval == GDK_KEY_Control_R
1388 		|| ev->keyval == GDK_KEY_Caps_Lock
1389 		|| ev->keyval == GDK_KEY_Shift_Lock
1390 		|| ev->keyval == GDK_KEY_Meta_L
1391 		|| ev->keyval == GDK_KEY_Meta_R
1392 		|| ev->keyval == GDK_KEY_Alt_L
1393 		|| ev->keyval == GDK_KEY_Alt_R) {
1394 		/* these buttons should not clear the cache... */
1395 	} else
1396 		clear_completion_cache();
1397 
1398 	return FALSE;
1399 }
1400 /**
1401  * Initialize search term for address completion.
1402  * \param entry Address entry field.
1403  */
address_completion_complete_address_in_entry(GtkEntry * entry,gboolean next)1404 static gboolean address_completion_complete_address_in_entry(GtkEntry *entry,
1405 							     gboolean  next)
1406 {
1407 	gint ncount, cursor_pos;
1408 	gchar *searchTerm, *new = NULL;
1409 
1410 	cm_return_val_if_fail(entry != NULL, FALSE);
1411 
1412 	if (!gtk_widget_has_focus(GTK_WIDGET(entry))) return FALSE;
1413 
1414 	/* get an address component from the cursor */
1415 	searchTerm = get_address_from_edit( entry, &cursor_pos );
1416 	if( ! searchTerm ) return FALSE;
1417 	/* g_print( "search for :::%s:::\n", searchTerm ); */
1418 
1419 	/* Clear any existing search */
1420 	g_free( _compWindow_->searchTerm );
1421 	_compWindow_->searchTerm = g_strdup( searchTerm );
1422 
1423 	/* Perform search on local completion index */
1424 	ncount = complete_address( searchTerm );
1425 	if( 0 < ncount ) {
1426 		new = get_next_complete_address();
1427 		g_free( new );
1428 	}
1429 #if (!defined(USE_LDAP) && !defined(GENERIC_UMPC))
1430 	/* Select the address if there is only one match */
1431 	if (ncount == 2) {
1432 		/* Display selected address in entry field */
1433 		gchar *addr = get_complete_address(1);
1434 		if (addr && !strstr(addr, " <!--___group___-->")) {
1435 			replace_address_in_edit(entry, addr, cursor_pos, FALSE, NULL);
1436 			/* Discard the window */
1437 			clear_completion_cache();
1438 		}
1439 		g_free(addr);
1440 	}
1441 	/* Make sure that drop-down appears uniform! */
1442 	else
1443 #endif
1444 	if( ncount == 0 ) {
1445 		addrcompl_add_queue( searchTerm );
1446 	} else {
1447 		g_free( searchTerm );
1448 	}
1449 
1450 	return TRUE;
1451 }
1452 
1453 /**
1454  * Create new address completion window for specified entry.
1455  * \param entry_ Entry widget to associate with window.
1456  */
address_completion_create_completion_window(GtkEntry * entry_)1457 static void address_completion_create_completion_window( GtkEntry *entry_ )
1458 {
1459 	gint x, y, height, width, depth;
1460 	GtkWidget *scroll, *list_view;
1461 	GdkGrabStatus status;
1462 	GtkRequisition r;
1463 	GtkWidget *window;
1464 	GtkWidget *entry = GTK_WIDGET(entry_);
1465 	GdkWindow *gdkwin;
1466 
1467 	/* Create new window and list */
1468 	window = gtk_window_new(GTK_WINDOW_POPUP);
1469 	list_view  = addr_compl_list_view_create(_compWindow_);
1470 
1471 	/* Destroy any existing window */
1472 	addrcompl_destroy_window( _compWindow_ );
1473 
1474 	/* Create new object */
1475 	_compWindow_->window    = window;
1476 	_compWindow_->entry     = entry;
1477 	_compWindow_->list_view = list_view;
1478 	_compWindow_->listCount = 0;
1479 	_compWindow_->in_mouse  = FALSE;
1480 
1481 	scroll = gtk_scrolled_window_new(NULL, NULL);
1482 	gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll),
1483 				       GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
1484 	gtk_container_add(GTK_CONTAINER(window), scroll);
1485 	gtk_container_add(GTK_CONTAINER(scroll), list_view);
1486 	gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll),
1487 		GTK_SHADOW_OUT);
1488 	/* Use entry widget to create initial window */
1489 	gdkwin = gtk_widget_get_window(entry),
1490 	gdk_window_get_geometry(gdkwin, &x, &y, &width, &height, &depth);
1491 	gdk_window_get_origin (gdkwin, &x, &y);
1492 	y += height;
1493 	gtk_window_move(GTK_WINDOW(window), x, y);
1494 
1495 	/* Resize window to fit initial (empty) address list */
1496 	gtk_widget_size_request( list_view, &r );
1497 	gtk_widget_set_size_request( window, width, r.height );
1498 	gtk_widget_show_all( window );
1499 	gtk_widget_size_request( list_view, &r );
1500 
1501 	/* Setup handlers */
1502 	g_signal_connect(G_OBJECT(list_view), "button_press_event",
1503 			 G_CALLBACK(list_view_button_press),
1504 			 _compWindow_);
1505 
1506 	g_signal_connect(G_OBJECT(list_view), "button_release_event",
1507 			 G_CALLBACK(list_view_button_release),
1508 			 _compWindow_);
1509 
1510 	g_signal_connect(G_OBJECT(window),
1511 			 "button-press-event",
1512 			 G_CALLBACK(completion_window_button_press),
1513 			 _compWindow_ );
1514 	g_signal_connect(G_OBJECT(window),
1515 			 "key-press-event",
1516 			 G_CALLBACK(completion_window_key_press),
1517 			 _compWindow_ );
1518 	gdk_pointer_grab(gtk_widget_get_window(window), TRUE,
1519 			 GDK_POINTER_MOTION_MASK | GDK_BUTTON_PRESS_MASK |
1520 			 GDK_BUTTON_RELEASE_MASK,
1521 			 NULL, NULL, GDK_CURRENT_TIME);
1522 	status = gdk_keyboard_grab(gtk_widget_get_window(window), FALSE, GDK_CURRENT_TIME);
1523 	if (status != GDK_GRAB_SUCCESS)
1524 		g_warning("gdk_keyboard_grab failed with status %d", status);
1525 	gtk_grab_add( window );
1526 }
1527 
1528 /**
1529  * Respond to button press in completion window. Check if mouse click is
1530  * anywhere outside the completion window. In that case the completion
1531  * window is destroyed, and the original searchTerm is restored.
1532  *
1533  * \param widget   Window object.
1534  * \param event    Event.
1535  * \param compWin  Reference to completion window.
1536  */
completion_window_button_press(GtkWidget * widget,GdkEventButton * event,CompletionWindow * compWin)1537 static gboolean completion_window_button_press(GtkWidget *widget,
1538 					       GdkEventButton *event,
1539 					       CompletionWindow *compWin )
1540 {
1541 	GtkWidget *event_widget, *entry;
1542 	gchar *searchTerm;
1543 	gint cursor_pos;
1544 	gboolean restore = TRUE;
1545 
1546 	cm_return_val_if_fail(compWin != NULL, FALSE);
1547 
1548 	entry = compWin->entry;
1549 	cm_return_val_if_fail(entry != NULL, FALSE);
1550 
1551 	/* Test where mouse was clicked */
1552 	event_widget = gtk_get_event_widget((GdkEvent *)event);
1553 	if (event_widget != widget) {
1554 		while (event_widget) {
1555 			if (event_widget == widget)
1556 				return FALSE;
1557 			else if (event_widget == entry) {
1558 				restore = FALSE;
1559 				break;
1560 			}
1561 			event_widget = gtk_widget_get_parent(event_widget);
1562 		}
1563 	}
1564 
1565 	if (restore) {
1566 		/* Clicked outside of completion window - restore */
1567 		searchTerm = _compWindow_->searchTerm;
1568 		g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1569 		replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos, FALSE, NULL);
1570 	}
1571 
1572 	clear_completion_cache();
1573 	addrcompl_destroy_window( _compWindow_ );
1574 
1575 	return TRUE;
1576 }
1577 
1578 /**
1579  * Respond to key press in completion window.
1580  * \param widget   Window object.
1581  * \param event    Event.
1582  * \param compWind Reference to completion window.
1583  */
completion_window_key_press(GtkWidget * widget,GdkEventKey * event,CompletionWindow * compWin)1584 static gboolean completion_window_key_press(GtkWidget *widget,
1585 					    GdkEventKey *event,
1586 					    CompletionWindow *compWin )
1587 {
1588 	GdkEventKey tmp_event;
1589 	GtkWidget *entry;
1590 	gchar *searchTerm;
1591 	gint cursor_pos;
1592 	GtkWidget *list_view;
1593 	GtkWidget *parent;
1594 	cm_return_val_if_fail(compWin != NULL, FALSE);
1595 
1596 	entry = compWin->entry;
1597 	list_view = compWin->list_view;
1598 	cm_return_val_if_fail(entry != NULL, FALSE);
1599 
1600 	/* allow keyboard navigation in the alternatives tree view */
1601 	if (event->keyval == GDK_KEY_Up || event->keyval == GDK_KEY_Down ||
1602 	    event->keyval == GDK_KEY_Page_Up || event->keyval == GDK_KEY_Page_Down) {
1603 		completion_window_advance_selection
1604 			(GTK_TREE_VIEW(list_view),
1605 			 event->keyval == GDK_KEY_Down ||
1606 			 event->keyval == GDK_KEY_Page_Down ? TRUE : FALSE);
1607 		return TRUE;
1608 	}
1609 
1610 	/* make tab move to next field */
1611 	if( event->keyval == GDK_KEY_Tab ) {
1612 		/* Reference to parent */
1613 		parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1614 
1615 		/* Discard the window */
1616 		clear_completion_cache();
1617 		addrcompl_destroy_window( _compWindow_ );
1618 
1619 		/* Move focus to next widget */
1620 		if( parent ) {
1621 			gtk_widget_child_focus( parent, GTK_DIR_TAB_FORWARD );
1622 		}
1623 		return FALSE;
1624 	}
1625 
1626 	/* make backtab move to previous field */
1627 	if( event->keyval == GDK_KEY_ISO_Left_Tab ) {
1628 		/* Reference to parent */
1629 		parent = gtk_widget_get_parent(GTK_WIDGET(entry));
1630 
1631 		/* Discard the window */
1632 		clear_completion_cache();
1633 		addrcompl_destroy_window( _compWindow_ );
1634 
1635 		/* Move focus to previous widget */
1636 		if( parent ) {
1637 			gtk_widget_child_focus( parent, GTK_DIR_TAB_BACKWARD );
1638 		}
1639 		return FALSE;
1640 	}
1641 	_allowCommas_ = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(entry), ENTRY_DATA_ALLOW_COMMAS));
1642 
1643 	/* look for presses that accept the selection */
1644 	if (event->keyval == GDK_KEY_Return || event->keyval == GDK_KEY_space ||
1645 			event->keyval == GDK_KEY_KP_Enter ||
1646 			(_allowCommas_ && event->keyval == GDK_KEY_comma)) {
1647 		/* User selected address with a key press */
1648 
1649 		/* Display selected address in entry field */
1650 		completion_window_apply_selection(
1651 			GTK_TREE_VIEW(list_view), GTK_ENTRY(entry),
1652 			event->keyval != GDK_KEY_comma);
1653 
1654 		if (event->keyval == GDK_KEY_comma) {
1655 			gint pos = gtk_editable_get_position(GTK_EDITABLE(entry));
1656 			gtk_editable_insert_text(GTK_EDITABLE(entry), ", ", 2, &pos);
1657 			gtk_editable_set_position(GTK_EDITABLE(entry), pos + 1);
1658 		}
1659 
1660 		/* Discard the window */
1661 		clear_completion_cache();
1662 		addrcompl_destroy_window( _compWindow_ );
1663 		return FALSE;
1664 	}
1665 
1666 	/* key state keys should never be handled */
1667 	if (event->keyval == GDK_KEY_Shift_L
1668 		 || event->keyval == GDK_KEY_Shift_R
1669 		 || event->keyval == GDK_KEY_Control_L
1670 		 || event->keyval == GDK_KEY_Control_R
1671 		 || event->keyval == GDK_KEY_Caps_Lock
1672 		 || event->keyval == GDK_KEY_Shift_Lock
1673 		 || event->keyval == GDK_KEY_Meta_L
1674 		 || event->keyval == GDK_KEY_Meta_R
1675 		 || event->keyval == GDK_KEY_Alt_L
1676 		 || event->keyval == GDK_KEY_Alt_R) {
1677 		return FALSE;
1678 	}
1679 
1680 	/* some other key, let's restore the searchTerm (orignal text) */
1681 	searchTerm = _compWindow_->searchTerm;
1682 	g_free(get_address_from_edit(GTK_ENTRY(entry), &cursor_pos));
1683 	replace_address_in_edit(GTK_ENTRY(entry), searchTerm, cursor_pos, FALSE, NULL);
1684 
1685 	/* make sure anything we typed comes in the edit box */
1686 	tmp_event.type       = event->type;
1687 	tmp_event.window     = gtk_widget_get_window(GTK_WIDGET(entry));
1688 	tmp_event.send_event = TRUE;
1689 	tmp_event.time       = event->time;
1690 	tmp_event.state      = event->state;
1691 	tmp_event.keyval     = event->keyval;
1692 	tmp_event.length     = event->length;
1693 	tmp_event.string     = event->string;
1694 	gtk_widget_event(entry, (GdkEvent *)&tmp_event);
1695 
1696 	/* and close the completion window */
1697 	clear_completion_cache();
1698 	addrcompl_destroy_window( _compWindow_ );
1699 
1700 	return TRUE;
1701 }
1702 
1703 /*
1704  * ============================================================================
1705  * Publically accessible functions.
1706  * ============================================================================
1707  */
1708 
1709 /**
1710  * Setup completion object.
1711  */
addrcompl_initialize(void)1712 void addrcompl_initialize( void ) {
1713 	/* g_print( "addrcompl_initialize...\n" ); */
1714 	if( ! _compWindow_ ) {
1715 		_compWindow_ = addrcompl_create_window();
1716 	}
1717 	_queryID_ = 0;
1718 	_completionIdleID_ = 0;
1719 	/* g_print( "addrcompl_initialize...done\n" ); */
1720 }
1721 
1722 /**
1723  * Teardown completion object.
1724  */
addrcompl_teardown(void)1725 void addrcompl_teardown( void ) {
1726 	/* g_print( "addrcompl_teardown...\n" ); */
1727 	addrcompl_free_window( _compWindow_ );
1728 	_compWindow_ = NULL;
1729 
1730 	addrcompl_clear_queue();
1731 
1732 	_completionIdleID_ = 0;
1733 	/* g_print( "addrcompl_teardown...done\n" ); */
1734 }
1735 
1736 /*
1737  * tree view functions
1738  */
1739 
addr_compl_create_store(void)1740 static GtkListStore *addr_compl_create_store(void)
1741 {
1742 	return gtk_list_store_new(N_ADDR_COMPL_COLUMNS,
1743 				  GDK_TYPE_PIXBUF,
1744 				  G_TYPE_STRING,
1745 				  G_TYPE_BOOLEAN,
1746 				  G_TYPE_POINTER,
1747 				  -1);
1748 }
1749 
addr_compl_list_view_create(CompletionWindow * window)1750 static GtkWidget *addr_compl_list_view_create(CompletionWindow *window)
1751 {
1752 	GtkTreeView *list_view;
1753 	GtkTreeSelection *selector;
1754 	GtkTreeModel *model;
1755 
1756 	model = GTK_TREE_MODEL(addr_compl_create_store());
1757 	list_view = GTK_TREE_VIEW(gtk_tree_view_new_with_model(model));
1758 	g_object_unref(model);
1759 
1760 	gtk_tree_view_set_rules_hint(list_view, prefs_common.use_stripes_everywhere);
1761 	gtk_tree_view_set_headers_visible(list_view, FALSE);
1762 
1763 	selector = gtk_tree_view_get_selection(list_view);
1764 	gtk_tree_selection_set_mode(selector, GTK_SELECTION_BROWSE);
1765 	gtk_tree_selection_set_select_function(selector, addr_compl_selected,
1766 					       window, NULL);
1767 
1768 	/* create the columns */
1769 	addr_compl_create_list_view_columns(GTK_WIDGET(list_view));
1770 
1771 	return GTK_WIDGET(list_view);
1772 }
1773 
addr_compl_create_list_view_columns(GtkWidget * list_view)1774 static void addr_compl_create_list_view_columns(GtkWidget *list_view)
1775 {
1776 	GtkTreeViewColumn *column;
1777 	GtkCellRenderer *renderer;
1778 
1779 	renderer = gtk_cell_renderer_pixbuf_new();
1780 	column = gtk_tree_view_column_new_with_attributes
1781 		("", renderer,
1782 	         "pixbuf", ADDR_COMPL_ICON, NULL);
1783 	gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);
1784 	renderer = gtk_cell_renderer_text_new();
1785 	column = gtk_tree_view_column_new_with_attributes
1786 		("", renderer, "text", ADDR_COMPL_ADDRESS, NULL);
1787 	gtk_tree_view_append_column(GTK_TREE_VIEW(list_view), column);
1788 }
1789 
list_view_button_press(GtkWidget * widget,GdkEventButton * event,CompletionWindow * window)1790 static gboolean list_view_button_press(GtkWidget *widget, GdkEventButton *event,
1791 				       CompletionWindow *window)
1792 {
1793 	if (window && event && event->type == GDK_BUTTON_PRESS) {
1794 		window->in_mouse = TRUE;
1795 	}
1796 	return FALSE;
1797 }
1798 
list_view_button_release(GtkWidget * widget,GdkEventButton * event,CompletionWindow * window)1799 static gboolean list_view_button_release(GtkWidget *widget, GdkEventButton *event,
1800 				         CompletionWindow *window)
1801 {
1802 	if (window && event && event->type == GDK_BUTTON_RELEASE) {
1803 		window->in_mouse = FALSE;
1804 	}
1805 	return FALSE;
1806 }
1807 
addr_compl_selected(GtkTreeSelection * selector,GtkTreeModel * model,GtkTreePath * path,gboolean currently_selected,gpointer data)1808 static gboolean addr_compl_selected(GtkTreeSelection *selector,
1809 			            GtkTreeModel *model,
1810 				    GtkTreePath *path,
1811 				    gboolean currently_selected,
1812 				    gpointer data)
1813 {
1814 	CompletionWindow *window = data;
1815 
1816 	if (currently_selected)
1817 		return TRUE;
1818 
1819 	if (!window->in_mouse)
1820 		return TRUE;
1821 
1822 	/* XXX: select the entry and kill window later... select is called before
1823 	 * any other mouse events handlers including the tree view internal one;
1824 	 * not using a time out would result in a crash. if this doesn't work
1825 	 * safely, maybe we should set variables when receiving button presses
1826 	 * in the tree view. */
1827 	if (!window->destroying) {
1828 		window->destroying = TRUE;
1829 		g_idle_add((GSourceFunc) addr_compl_defer_select_destruct, data);
1830 	}
1831 
1832 	return TRUE;
1833 }
1834 
addr_compl_defer_select_destruct(CompletionWindow * window)1835 static gboolean addr_compl_defer_select_destruct(CompletionWindow *window)
1836 {
1837 	GtkEntry *entry = GTK_ENTRY(window->entry);
1838 
1839 	completion_window_apply_selection(GTK_TREE_VIEW(window->list_view),
1840 					  entry, TRUE);
1841 
1842 	clear_completion_cache();
1843 
1844 	addrcompl_destroy_window(window);
1845 	return FALSE;
1846 }
1847 
found_in_addressbook(const gchar * address)1848 gboolean found_in_addressbook(const gchar *address)
1849 {
1850 	gchar *addr = NULL;
1851 	gboolean found = FALSE;
1852 	gint num_addr = 0;
1853 
1854 	if (!address)
1855 		return FALSE;
1856 
1857 	addr = g_strdup(address);
1858 	extract_address(addr);
1859 	num_addr = complete_address(addr);
1860 	if (num_addr > 1) {
1861 		/* skip first item (this is the search string itself) */
1862 		int i = 1;
1863 		for (; i < num_addr && !found; i++) {
1864 			gchar *caddr = get_complete_address(i);
1865 			extract_address(caddr);
1866 			if (strcasecmp(caddr, addr) == 0)
1867 				found = TRUE;
1868 			g_free(caddr);
1869 		}
1870 	}
1871 	g_free(addr);
1872 	return found;
1873 }
1874 
1875 /*
1876  * End of Source.
1877  */
1878