2007-02-21 [colin] 2.7.2cvs60
[claws.git] / src / gtk / quicksearch.c
1 /*
2  * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2007 Colin Leroy <colin@colino.net> 
4  * and 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 2 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, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  */
20
21 #ifdef HAVE_CONFIG_H
22 #  include "config.h"
23 #endif
24
25 #include <glib.h>
26 #include <glib/gi18n.h>
27 #include <ctype.h>
28
29 #include <gtk/gtk.h>
30 #include <gdk/gdkkeysyms.h>
31
32 #include "utils.h"
33 #include "menu.h"
34 #include "prefs_common.h"
35 #include "description_window.h"
36 #include "matcher.h"
37 #include "matcher_parser.h"
38 #include "quicksearch.h"
39 #include "folderview.h"
40 #include "folder.h"
41 #include "prefs_matcher.h"
42 #include "claws.h"
43 #include "statusbar.h"
44
45 struct _QuickSearch
46 {
47         GtkWidget                       *hbox_search;
48         GtkWidget                       *search_type;
49         GtkWidget                       *search_type_opt;
50         GtkWidget                       *search_string_entry;
51         GtkWidget                       *search_condition_expression;
52         GtkWidget                       *search_description;
53         GtkWidget                       *clear_search;
54
55         gboolean                         active;
56         gchar                           *search_string;
57         MatcherList                     *matcher_list;
58
59         QuickSearchExecuteCallback       callback;
60         gpointer                         callback_data;
61         gboolean                         running;
62         gboolean                         has_focus;
63         gboolean                         matching;
64         gboolean                         deferred_free;
65         FolderItem                      *root_folder_item;
66         gboolean                         is_fast;
67         gboolean                         in_typing;
68         guint                            press_timeout_id;
69 };
70
71 static void quicksearch_set_running(QuickSearch *quicksearch, gboolean run);
72 static void quicksearch_set_active(QuickSearch *quicksearch, gboolean active);
73 static void quicksearch_reset_folder_items(QuickSearch *quicksearch, FolderItem *folder_item);
74 static gchar *expand_search_string(const gchar *str);
75
76 gboolean quicksearch_is_fast(QuickSearch *quicksearch)
77 {
78         return quicksearch->is_fast;
79 }
80
81 static void prepare_matcher(QuickSearch *quicksearch)
82 {
83         const gchar *search_string = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(quicksearch->search_string_entry)->entry));
84
85         if (search_string == NULL || search_string[0] == '\0') {
86                 quicksearch_set_active(quicksearch, FALSE);
87         }
88
89         if (quicksearch->matcher_list != NULL) {
90                 if (quicksearch->matching) {
91                         quicksearch->deferred_free = TRUE;
92                         return;
93                 }
94                 quicksearch->deferred_free = FALSE;
95                 matcherlist_free(quicksearch->matcher_list);
96                 quicksearch->matcher_list = NULL;
97         }
98
99         if (search_string == NULL || search_string[0] == '\0') {
100                 return;
101         }
102
103         if (prefs_common.summary_quicksearch_type == QUICK_SEARCH_EXTENDED) {
104                 char *newstr = NULL;
105
106                 newstr = expand_search_string(search_string);
107                 if (newstr && newstr[0] != '\0') {
108                         quicksearch->matcher_list = matcher_parser_get_cond(newstr, &quicksearch->is_fast);
109                         g_free(newstr);
110                 } else {
111                         quicksearch->matcher_list = NULL;
112                         quicksearch_set_active(quicksearch, FALSE);
113
114                         return;
115                 }
116         } else {
117                 quicksearch->is_fast = TRUE;
118                 g_free(quicksearch->search_string);
119                 quicksearch->search_string = g_strdup(search_string);
120         }
121
122         quicksearch_set_active(quicksearch, TRUE);
123 }
124
125 static void update_extended_buttons (QuickSearch *quicksearch)
126 {
127         GtkWidget *expr_btn = quicksearch->search_condition_expression;
128         GtkWidget *ext_btn = quicksearch->search_description;
129
130         g_return_if_fail(expr_btn != NULL);
131         g_return_if_fail(ext_btn != NULL);
132
133         if (prefs_common.summary_quicksearch_type == QUICK_SEARCH_EXTENDED) {
134                 gtk_widget_show(expr_btn);
135                 gtk_widget_show(ext_btn);
136         } else {
137                 gtk_widget_hide(expr_btn);
138                 gtk_widget_hide(ext_btn);
139         }
140 }
141
142 static gboolean searchbar_focus_evt_in(GtkWidget *widget, GdkEventFocus *event,
143                                   QuickSearch *qs)
144 {
145         qs->has_focus = TRUE;
146         return FALSE;
147 }
148
149 static gboolean searchbar_focus_evt_out(GtkWidget *widget, GdkEventFocus *event,
150                                   QuickSearch *qs)
151 {
152         qs->has_focus = FALSE;
153         qs->in_typing = FALSE;
154         return FALSE;
155 }
156
157 gboolean quicksearch_has_focus(QuickSearch *quicksearch)
158 {
159         return quicksearch->has_focus;
160 }
161
162 static void searchbar_run(QuickSearch *quicksearch, gboolean run_only_if_fast)
163 {
164         const gchar *search_string = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(quicksearch->search_string_entry)->entry));
165
166         /* add to history */
167         if (!quicksearch->in_typing && search_string && strlen(search_string) != 0) {
168                 prefs_common.summary_quicksearch_history =
169                         add_history(prefs_common.summary_quicksearch_history,
170                                         search_string);
171                 gtk_combo_set_popdown_strings(GTK_COMBO(quicksearch->search_string_entry),
172                         prefs_common.summary_quicksearch_history);
173         }
174
175         prepare_matcher(quicksearch);
176         if (run_only_if_fast && !quicksearch->is_fast)
177                 return;
178         if (quicksearch->matcher_list == NULL && 
179             prefs_common.summary_quicksearch_type == QUICK_SEARCH_EXTENDED &&
180             search_string && strlen(search_string) != 0)
181                 return;
182         quicksearch_set_running(quicksearch, TRUE);
183         if (quicksearch->callback != NULL)
184                 quicksearch->callback(quicksearch, quicksearch->callback_data);
185         quicksearch_set_running(quicksearch, FALSE);
186 }
187
188 static int searchbar_changed_timeout(void *data)
189 {
190         QuickSearch *qs = (QuickSearch *)data;
191         if (qs && prefs_common.summary_quicksearch_dynamic) {
192                 qs->in_typing = TRUE;
193                 searchbar_run(qs, TRUE);
194         }
195         return FALSE;
196 }
197
198 static gboolean searchbar_changed_cb(GtkWidget *widget, QuickSearch *qs)
199 {
200         if (prefs_common.summary_quicksearch_dynamic) {
201                 if (qs->press_timeout_id != -1) {
202                         g_source_remove(qs->press_timeout_id);
203                 }
204                 qs->press_timeout_id = g_timeout_add(500,
205                                 searchbar_changed_timeout, qs);
206         }
207
208         return FALSE;
209 }
210
211 static gboolean searchbar_pressed(GtkWidget *widget, GdkEventKey *event,
212                                   QuickSearch *quicksearch)
213 {
214         if (event != NULL && event->keyval == GDK_Escape) {
215
216                 const gchar *str;
217
218                 quicksearch->in_typing = FALSE;
219
220                 str = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(quicksearch->search_string_entry)->entry));
221                 g_return_val_if_fail(str != NULL, TRUE);
222
223                 /* If the string entry is empty -> hide quicksearch bar. If not -> empty it */
224                 if (!*str) {
225                         summaryview_activate_quicksearch(
226                                 mainwindow_get_mainwindow()->summaryview, 
227                                 FALSE);
228                 } else {
229                         quicksearch_set(quicksearch, prefs_common.summary_quicksearch_type, "");
230                         gtk_widget_grab_focus(
231                                         GTK_WIDGET(GTK_COMBO(quicksearch->search_string_entry)->entry));
232                 }
233
234                 return TRUE;
235         }
236
237         if (event != NULL && event->keyval == GDK_Return) {
238                 quicksearch->in_typing = FALSE;
239                 /* add expression to history list and exec quicksearch */
240                 searchbar_run(quicksearch, FALSE);
241
242                 g_signal_stop_emission_by_name(G_OBJECT(widget), "key_press_event");
243                 return TRUE;
244         }
245
246         return FALSE;
247 }
248
249 static gboolean searchtype_changed(GtkMenuItem *widget, gpointer data)
250 {
251         QuickSearch *quicksearch = (QuickSearch *)data;
252         const gchar *search_string = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(quicksearch->search_string_entry)->entry));
253
254         prefs_common.summary_quicksearch_type = GPOINTER_TO_INT(g_object_get_data(
255                                    G_OBJECT(GTK_MENU_ITEM(gtk_menu_get_active(
256                                    GTK_MENU(quicksearch->search_type)))), MENU_VAL_ID));
257
258         /* Show extended search description button, only when Extended is selected */
259         update_extended_buttons(quicksearch);
260
261         if (!search_string || strlen(search_string) == 0) {
262                 return TRUE;
263         }
264
265         prepare_matcher(quicksearch);
266
267         quicksearch_set_running(quicksearch, TRUE);
268         if (quicksearch->callback != NULL)
269                 quicksearch->callback(quicksearch, quicksearch->callback_data);
270         quicksearch_set_running(quicksearch, FALSE);
271         return TRUE;
272 }
273
274 static gboolean searchtype_recursive_changed(GtkMenuItem *widget, gpointer data)
275 {
276         QuickSearch *quicksearch = (QuickSearch *)data;
277         gboolean checked = gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(widget));
278         const gchar *search_string = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(quicksearch->search_string_entry)->entry));
279
280         prefs_common.summary_quicksearch_recurse = checked;
281
282         /* reselect the search type */
283         gtk_option_menu_set_history(GTK_OPTION_MENU(quicksearch->search_type_opt),
284                                     prefs_common.summary_quicksearch_type);
285
286         if (!search_string || strlen(search_string) == 0) {
287                 return TRUE;
288         }
289
290         prepare_matcher(quicksearch);
291
292         quicksearch_set_running(quicksearch, TRUE);
293         if (quicksearch->callback != NULL)
294                 quicksearch->callback(quicksearch, quicksearch->callback_data);
295         quicksearch_set_running(quicksearch, FALSE);
296         return TRUE;
297 }
298
299 static gboolean searchtype_sticky_changed(GtkMenuItem *widget, gpointer data)
300 {
301         QuickSearch *quicksearch = (QuickSearch *)data;
302         gboolean checked = gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(widget));
303
304         prefs_common.summary_quicksearch_sticky = checked;
305
306         /* reselect the search type */
307         gtk_option_menu_set_history(GTK_OPTION_MENU(quicksearch->search_type_opt),
308                                     prefs_common.summary_quicksearch_type);
309
310         return TRUE;
311 }
312
313 static gboolean searchtype_dynamic_changed(GtkMenuItem *widget, gpointer data)
314 {
315         QuickSearch *quicksearch = (QuickSearch *)data;
316         gboolean checked = gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(widget));
317
318         prefs_common.summary_quicksearch_dynamic = checked;
319
320         /* reselect the search type */
321         gtk_option_menu_set_history(GTK_OPTION_MENU(quicksearch->search_type_opt),
322                                     prefs_common.summary_quicksearch_type);
323
324         return TRUE;
325 }
326
327 /*
328  * Strings describing how to use Extended Search
329  *
330  * When adding new lines, remember to put 2 strings for each line
331  */
332 static gchar *search_descr_strings[] = {
333         "a",     N_("all messages"),
334         "ag #",  N_("messages whose age is greater than #"),
335         "al #",  N_("messages whose age is less than #"),
336         "b S",   N_("messages which contain S in the message body"),
337         "B S",   N_("messages which contain S in the whole message"),
338         "c S",   N_("messages carbon-copied to S"),
339         "C S",   N_("message is either to: or cc: to S"),
340         "D",     N_("deleted messages"), /** how I can filter deleted messages **/
341         "e S",   N_("messages which contain S in the Sender field"),
342         "E S",   N_("true if execute \"S\" succeeds"),
343         "f S",   N_("messages originating from user S"),
344         "F",     N_("forwarded messages"),
345         "h S",   N_("messages which contain header S"),
346         "i S",   N_("messages which contain S in Message-ID header"),
347         "I S",   N_("messages which contain S in inreplyto header"),
348         "k #",   N_("messages which are marked with color #"),
349         "L",     N_("locked messages"),
350         "n S",   N_("messages which are in newsgroup S"),
351         "N",     N_("new messages"),
352         "O",     N_("old messages"),
353         "p",     N_("incomplete messages (not entirely downloaded)"),
354         "r",     N_("messages which have been replied to"),
355         "R",     N_("read messages"),
356         "s S",   N_("messages which contain S in subject"),
357         "se #",  N_("messages whose score is equal to #"),
358         "sg #",  N_("messages whose score is greater than #"),
359         "sl #",  N_("messages whose score is lower than #"),
360         "Se #",  N_("messages whose size is equal to #"),
361         "Sg #",  N_("messages whose size is greater than #"),
362         "Ss #",  N_("messages whose size is smaller than #"),
363         "t S",   N_("messages which have been sent to S"),
364         "T",     N_("marked messages"),
365         "U",     N_("unread messages"),
366         "x S",   N_("messages which contain S in References header"),
367         "X \"cmd args\"", N_("messages returning 0 when passed to command - %F is message file"),
368         "y S",   N_("messages which contain S in X-Label header"),
369         "",      "" ,
370         "&amp;",         N_("logical AND operator"),
371         "|",     N_("logical OR operator"),
372         "! or ~",       N_("logical NOT operator"),
373         "%",     N_("case sensitive search"),
374         "",      "" ,
375         " ",     N_("all filtering expressions are allowed"),
376         NULL,    NULL
377 };
378
379 static DescriptionWindow search_descr = {
380         NULL,
381         NULL,
382         2,
383         N_("Extended Search"),
384         N_("Extended Search allows the user to define criteria that messages must "
385            "have in order to match and be displayed in the message list.\n\n"
386            "The following symbols can be used:"),
387         search_descr_strings
388 };
389
390 static void search_description_cb(GtkWidget *widget)
391 {
392         description_window_create(&search_descr);
393 };
394
395 static gboolean clear_search_cb(GtkMenuItem *widget, gpointer data)
396 {
397         QuickSearch *quicksearch = (QuickSearch *)data;
398
399         if (!quicksearch->active)
400                 return TRUE;
401
402         quicksearch_set(quicksearch, prefs_common.summary_quicksearch_type, "");
403
404         return TRUE;
405 };
406
407 static void search_condition_expr_done(MatcherList * matchers)
408 {
409         gchar *str;
410
411         g_return_if_fail(
412                         mainwindow_get_mainwindow()->summaryview->quicksearch != NULL);
413
414         if (matchers == NULL)
415                 return;
416
417         str = matcherlist_to_string(matchers);
418
419         if (str != NULL) {
420                 quicksearch_set(mainwindow_get_mainwindow()->summaryview->quicksearch,
421                                 prefs_common.summary_quicksearch_type, str);
422                 g_free(str);
423
424                 /* add expression to history list and exec quicksearch */
425                 searchbar_run(mainwindow_get_mainwindow()->summaryview->quicksearch, FALSE);
426         }
427 }
428
429 static gboolean search_condition_expr(GtkMenuItem *widget, gpointer data)
430 {
431         const gchar * cond_str;
432         MatcherList * matchers = NULL;
433         
434         g_return_val_if_fail(
435                         mainwindow_get_mainwindow()->summaryview->quicksearch != NULL,
436                         FALSE);
437
438         /* re-use it the current quicksearch value if it's a condition expression,
439            otherwise ignore it silently */
440         cond_str = gtk_entry_get_text(
441                         GTK_ENTRY(GTK_COMBO(mainwindow_get_mainwindow()->summaryview->quicksearch->
442                         search_string_entry)->entry));
443         if (*cond_str != '\0') {
444                 matchers = matcher_parser_get_cond((gchar*)cond_str, NULL);
445         }
446
447         prefs_matcher_open(matchers, search_condition_expr_done);
448
449         if (matchers != NULL)
450                 matcherlist_free(matchers);
451
452         return TRUE;
453 };
454
455 QuickSearch *quicksearch_new()
456 {
457         QuickSearch *quicksearch;
458
459         GtkWidget *hbox_search;
460         GtkWidget *search_type_opt;
461         GtkWidget *search_type;
462         GtkWidget *search_string_entry;
463         GtkWidget *search_hbox;
464         GtkWidget *search_description;
465         GtkWidget *clear_search;
466         GtkWidget *search_condition_expression;
467         GtkWidget *menuitem;
468         GtkTooltips *tips = gtk_tooltips_new();
469
470         quicksearch = g_new0(QuickSearch, 1);
471
472         /* quick search */
473         hbox_search = gtk_hbox_new(FALSE, 0);
474
475         search_type_opt = gtk_option_menu_new();
476         gtk_widget_show(search_type_opt);
477         gtk_box_pack_start(GTK_BOX(hbox_search), search_type_opt, FALSE, FALSE, 0);
478
479         search_type = gtk_menu_new();
480         MENUITEM_ADD (search_type, menuitem, _("Subject"), QUICK_SEARCH_SUBJECT);
481         g_signal_connect(G_OBJECT(menuitem), "activate",
482                          G_CALLBACK(searchtype_changed),
483                          quicksearch);
484         MENUITEM_ADD (search_type, menuitem, _("From"), QUICK_SEARCH_FROM);
485         g_signal_connect(G_OBJECT(menuitem), "activate",
486                          G_CALLBACK(searchtype_changed),
487                          quicksearch);
488         MENUITEM_ADD (search_type, menuitem, _("To"), QUICK_SEARCH_TO);
489         g_signal_connect(G_OBJECT(menuitem), "activate",
490                          G_CALLBACK(searchtype_changed),
491                          quicksearch);
492         MENUITEM_ADD (search_type, menuitem, _("Extended"), QUICK_SEARCH_EXTENDED);
493         g_signal_connect(G_OBJECT(menuitem), "activate",
494                          G_CALLBACK(searchtype_changed),
495                          quicksearch);
496
497         gtk_menu_shell_append(GTK_MENU_SHELL(search_type), gtk_separator_menu_item_new());
498
499         menuitem = gtk_check_menu_item_new_with_label(_("Recursive"));
500         gtk_menu_shell_append(GTK_MENU_SHELL(search_type), menuitem);
501
502         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
503                                         prefs_common.summary_quicksearch_recurse);
504
505         g_signal_connect(G_OBJECT(menuitem), "activate",
506                          G_CALLBACK(searchtype_recursive_changed),
507                          quicksearch);
508
509         menuitem = gtk_check_menu_item_new_with_label(_("Sticky"));
510         gtk_menu_shell_append(GTK_MENU_SHELL(search_type), menuitem);
511
512         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
513                                         prefs_common.summary_quicksearch_sticky);
514
515         g_signal_connect(G_OBJECT(menuitem), "activate",
516                          G_CALLBACK(searchtype_sticky_changed),
517                          quicksearch);
518
519         menuitem = gtk_check_menu_item_new_with_label(_("Type-ahead"));
520         gtk_menu_shell_append(GTK_MENU_SHELL(search_type), menuitem);
521
522         gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(menuitem),
523                                         prefs_common.summary_quicksearch_dynamic);
524
525         g_signal_connect(G_OBJECT(menuitem), "activate",
526                          G_CALLBACK(searchtype_dynamic_changed),
527                          quicksearch);
528
529         gtk_option_menu_set_menu(GTK_OPTION_MENU(search_type_opt), search_type);
530
531         gtk_option_menu_set_history(GTK_OPTION_MENU(search_type_opt), prefs_common.summary_quicksearch_type);
532
533         gtk_widget_show(search_type);
534
535         search_string_entry = gtk_combo_new();
536         gtk_box_pack_start(GTK_BOX(hbox_search), search_string_entry, FALSE, FALSE, 2);
537         gtk_combo_set_value_in_list(GTK_COMBO(search_string_entry), FALSE, TRUE);
538         gtk_combo_set_case_sensitive(GTK_COMBO(search_string_entry), TRUE);
539         if (prefs_common.summary_quicksearch_history)
540                 gtk_combo_set_popdown_strings(GTK_COMBO(search_string_entry),
541                         prefs_common.summary_quicksearch_history);
542         gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(search_string_entry)->entry), "");
543         gtk_widget_show(search_string_entry);
544
545         search_hbox = gtk_hbox_new(FALSE, 5);
546
547 #if GTK_CHECK_VERSION(2, 8, 0)
548         clear_search = gtk_button_new_from_stock(GTK_STOCK_CLEAR);
549 #else
550         clear_search = gtk_button_new_with_label(_(" Clear "));
551 #endif
552         gtk_box_pack_start(GTK_BOX(search_hbox), clear_search,
553                            FALSE, FALSE, 0);
554         g_signal_connect(G_OBJECT(clear_search), "clicked",
555                          G_CALLBACK(clear_search_cb), quicksearch);
556         gtk_tooltips_set_tip(GTK_TOOLTIPS(tips),
557                              clear_search,
558                              _("Clear the current search"), NULL);
559         gtk_widget_show(clear_search);
560
561 #if GTK_CHECK_VERSION(2, 8, 0)
562         search_condition_expression = gtk_button_new_from_stock(GTK_STOCK_EDIT);
563 #else
564         search_condition_expression = gtk_button_new_with_label(" ... ");
565 #endif
566         gtk_box_pack_start(GTK_BOX(search_hbox), search_condition_expression,
567                            FALSE, FALSE, 0);
568         g_signal_connect(G_OBJECT (search_condition_expression), "clicked",
569                          G_CALLBACK(search_condition_expr),
570                          quicksearch);
571         gtk_tooltips_set_tip(GTK_TOOLTIPS(tips),
572                              search_condition_expression,
573                              _("Edit search criteria"), NULL);
574         gtk_widget_show(search_condition_expression);
575
576 #if GTK_CHECK_VERSION(2, 8, 0)
577         search_description = gtk_button_new_from_stock(GTK_STOCK_INFO);
578 #else
579         search_description = gtk_button_new_with_label(_(" Extended Symbols... "));
580 #endif
581         gtk_box_pack_start(GTK_BOX(search_hbox), search_description,
582                            FALSE, FALSE, 0);
583         g_signal_connect(G_OBJECT(search_description), "clicked",
584                          G_CALLBACK(search_description_cb), NULL);
585         gtk_tooltips_set_tip(GTK_TOOLTIPS(tips),
586                              search_description,
587                              _("Information about extended symbols"), NULL);
588         gtk_widget_show(search_description);
589
590         gtk_box_pack_start(GTK_BOX(hbox_search), search_hbox, FALSE, FALSE, 2);
591         gtk_widget_show(search_hbox);
592
593         g_signal_connect(G_OBJECT(GTK_COMBO(search_string_entry)->entry),
594                            "key_press_event",
595                            G_CALLBACK(searchbar_pressed),
596                            quicksearch);
597
598         g_signal_connect(G_OBJECT(GTK_COMBO(search_string_entry)->entry),
599                          "changed",
600                          G_CALLBACK(searchbar_changed_cb),
601                          quicksearch);
602
603         g_signal_connect(G_OBJECT(GTK_COMBO(search_string_entry)->entry),
604                          "focus_in_event",
605                          G_CALLBACK(searchbar_focus_evt_in),
606                          quicksearch);
607         g_signal_connect(G_OBJECT(GTK_COMBO(search_string_entry)->entry),
608                          "focus_out_event",
609                          G_CALLBACK(searchbar_focus_evt_out),
610                          quicksearch);
611
612         quicksearch->hbox_search = hbox_search;
613         quicksearch->search_type = search_type;
614         quicksearch->search_type_opt = search_type_opt;
615         quicksearch->search_string_entry = search_string_entry;
616         quicksearch->search_condition_expression = search_condition_expression;
617         quicksearch->search_description = search_description;
618         quicksearch->matcher_list = NULL;
619         quicksearch->active = FALSE;
620         quicksearch->running = FALSE;
621         quicksearch->clear_search = clear_search;
622         quicksearch->in_typing = FALSE;
623         quicksearch->press_timeout_id = -1;
624
625         update_extended_buttons(quicksearch);
626
627         return quicksearch;
628 }
629
630 void quicksearch_relayout(QuickSearch *quicksearch)
631 {
632         switch (prefs_common.layout_mode) {
633         case NORMAL_LAYOUT:
634         case WIDE_LAYOUT:
635         case WIDE_MSGLIST_LAYOUT:
636 #if GTK_CHECK_VERSION(2, 8, 0)
637                 gtk_button_set_label(GTK_BUTTON(quicksearch->search_description), GTK_STOCK_INFO);
638                 gtk_button_set_label(GTK_BUTTON(quicksearch->search_condition_expression), GTK_STOCK_EDIT);
639                 gtk_button_set_label(GTK_BUTTON(quicksearch->clear_search), GTK_STOCK_CLEAR);
640 #else
641                 gtk_button_set_label(GTK_BUTTON(quicksearch->search_description), _(" Extended Symbols... "));
642                 gtk_button_set_label(GTK_BUTTON(quicksearch->search_condition_expression), " ... ");
643                 gtk_button_set_label(GTK_BUTTON(quicksearch->clear_search), _(" Clear "));
644 #endif
645                 break;
646         case VERTICAL_LAYOUT:
647 #if GTK_CHECK_VERSION(2, 8, 0)
648                 gtk_button_set_label(GTK_BUTTON(quicksearch->search_description), "");
649                 gtk_button_set_label(GTK_BUTTON(quicksearch->search_condition_expression), "");
650                 gtk_button_set_label(GTK_BUTTON(quicksearch->clear_search), "");
651
652                 gtk_button_set_image(GTK_BUTTON(quicksearch->search_description),
653                         gtk_image_new_from_stock(GTK_STOCK_INFO, GTK_ICON_SIZE_BUTTON));
654                 gtk_button_set_image(GTK_BUTTON(quicksearch->search_condition_expression),
655                         gtk_image_new_from_stock(GTK_STOCK_EDIT, GTK_ICON_SIZE_BUTTON));
656                 gtk_button_set_image(GTK_BUTTON(quicksearch->clear_search),
657                         gtk_image_new_from_stock(GTK_STOCK_CLEAR, GTK_ICON_SIZE_BUTTON));
658 #else
659                 gtk_button_set_label(GTK_BUTTON(quicksearch->search_description), _("Info"));
660                 gtk_button_set_label(GTK_BUTTON(quicksearch->search_condition_expression), "...");
661                 gtk_button_set_label(GTK_BUTTON(quicksearch->clear_search), _("Clear"));
662 #endif
663                 break;
664         }
665 }
666
667 GtkWidget *quicksearch_get_widget(QuickSearch *quicksearch)
668 {
669         return quicksearch->hbox_search;
670 }
671
672 void quicksearch_show(QuickSearch *quicksearch)
673 {
674         MainWindow *mainwin = mainwindow_get_mainwindow();
675         GtkWidget *ctree = NULL;
676         prepare_matcher(quicksearch);
677         gtk_widget_show(quicksearch->hbox_search);
678         update_extended_buttons(quicksearch);
679         gtk_widget_grab_focus(
680                 GTK_WIDGET(GTK_COMBO(quicksearch->search_string_entry)->entry));
681
682         GTK_EVENTS_FLUSH();
683
684         if (!mainwin || !mainwin->summaryview) {
685                 return;
686         }
687         
688         ctree = summary_get_main_widget(mainwin->summaryview);
689         
690         if (ctree && mainwin->summaryview->selected)
691                 gtk_ctree_node_moveto(GTK_CTREE(ctree), 
692                                 mainwin->summaryview->selected, 
693                                 0, 0.5, 0);
694 }
695
696 void quicksearch_hide(QuickSearch *quicksearch)
697 {
698         if (quicksearch_is_active(quicksearch)) {
699                 quicksearch_set(quicksearch, prefs_common.summary_quicksearch_type, "");
700                 quicksearch_set_active(quicksearch, FALSE);
701         }
702         gtk_widget_hide(quicksearch->hbox_search);
703 }
704
705 void quicksearch_set(QuickSearch *quicksearch, QuickSearchType type,
706                      const gchar *matchstring)
707 {
708         gtk_option_menu_set_history(GTK_OPTION_MENU(quicksearch->search_type_opt),
709                                     type);
710
711         if (!matchstring || !(*matchstring))
712                 quicksearch->in_typing = FALSE;
713
714         g_signal_handlers_block_by_func(G_OBJECT(GTK_COMBO(quicksearch->search_string_entry)->entry),
715                         G_CALLBACK(searchbar_changed_cb), quicksearch);
716         gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(quicksearch->search_string_entry)->entry),
717                            matchstring);
718         g_signal_handlers_unblock_by_func(G_OBJECT(GTK_COMBO(quicksearch->search_string_entry)->entry),
719                         G_CALLBACK(searchbar_changed_cb), quicksearch);
720
721         prefs_common.summary_quicksearch_type = type;
722
723         prepare_matcher(quicksearch);
724
725         quicksearch_set_running(quicksearch, TRUE);
726         if (quicksearch->callback != NULL)
727                 quicksearch->callback(quicksearch, quicksearch->callback_data);
728         quicksearch_set_running(quicksearch, FALSE);
729 }
730
731 gboolean quicksearch_is_active(QuickSearch *quicksearch)
732 {
733         return quicksearch->active && 
734                 (prefs_common.summary_quicksearch_type != QUICK_SEARCH_EXTENDED
735                  || quicksearch->matcher_list != NULL);
736 }
737
738 static void quicksearch_set_active(QuickSearch *quicksearch, gboolean active)
739 {
740         static GdkColor yellow;
741         static GdkColor red;
742         static GdkColor black;
743         static gboolean colors_initialised = FALSE;
744         gboolean error = FALSE;
745
746         if (!colors_initialised) {
747                 gdk_color_parse("#f5f6be", &yellow);
748                 gdk_color_parse("#000000", &black);
749                 gdk_color_parse("#ff7070", &red);
750                 colors_initialised = gdk_colormap_alloc_color(
751                         gdk_colormap_get_system(), &yellow, FALSE, TRUE);
752                 colors_initialised &= gdk_colormap_alloc_color(
753                         gdk_colormap_get_system(), &black, FALSE, TRUE);
754                 colors_initialised &= gdk_colormap_alloc_color(
755                         gdk_colormap_get_system(), &red, FALSE, TRUE);
756         }
757
758         quicksearch->active = active;
759
760         if (active && 
761                 (prefs_common.summary_quicksearch_type == QUICK_SEARCH_EXTENDED
762                  && quicksearch->matcher_list == NULL))
763                 error = TRUE;
764
765         if (active) {
766                 gtk_widget_set_sensitive(quicksearch->clear_search, TRUE);
767                 if (colors_initialised) {
768                         gtk_widget_modify_base(
769                                 GTK_COMBO(quicksearch->search_string_entry)->entry,
770                                 GTK_STATE_NORMAL, error ? &red : &yellow);
771                         gtk_widget_modify_text(
772                                 GTK_COMBO(quicksearch->search_string_entry)->entry,
773                                 GTK_STATE_NORMAL, &black);
774                 }
775         } else {
776                 gtk_widget_set_sensitive(quicksearch->clear_search, FALSE);
777                 if (colors_initialised) {
778                         gtk_widget_modify_base(
779                                 GTK_COMBO(quicksearch->search_string_entry)->entry,
780                                 GTK_STATE_NORMAL, NULL);
781                         gtk_widget_modify_text(
782                                 GTK_COMBO(quicksearch->search_string_entry)->entry,
783                                 GTK_STATE_NORMAL, NULL);
784                 }
785         }
786
787         if (!active) {
788                 quicksearch_reset_cur_folder_item(quicksearch);
789         }
790 }
791
792 void quicksearch_set_execute_callback(QuickSearch *quicksearch,
793                                       QuickSearchExecuteCallback callback,
794                                       gpointer data)
795 {
796         quicksearch->callback = callback;
797         quicksearch->callback_data = data;
798 }
799
800 gboolean quicksearch_match(QuickSearch *quicksearch, MsgInfo *msginfo)
801 {
802         gchar *searched_header = NULL;
803         gboolean result = FALSE;
804
805         if (!quicksearch->active)
806                 return TRUE;
807
808         switch (prefs_common.summary_quicksearch_type) {
809         case QUICK_SEARCH_SUBJECT:
810                 searched_header = msginfo->subject;
811                 break;
812         case QUICK_SEARCH_FROM:
813                 searched_header = msginfo->from;
814                 break;
815         case QUICK_SEARCH_TO:
816                 searched_header = msginfo->to;
817                 break;
818         case QUICK_SEARCH_EXTENDED:
819                 break;
820         default:
821                 debug_print("unknown search type (%d)\n", prefs_common.summary_quicksearch_type);
822                 break;
823         }
824         quicksearch->matching = TRUE;
825         if (prefs_common.summary_quicksearch_type != QUICK_SEARCH_EXTENDED &&
826             quicksearch->search_string &&
827             searched_header && strcasestr(searched_header, quicksearch->search_string) != NULL)
828                 result = TRUE;
829         else if ((quicksearch->matcher_list != NULL) &&
830                  matcherlist_match(quicksearch->matcher_list, msginfo))
831                 result = TRUE;
832
833         quicksearch->matching = FALSE;
834         if (quicksearch->deferred_free) {
835                 prepare_matcher(quicksearch);
836         }
837
838         return result;
839 }
840
841 /* allow Mutt-like patterns in quick search */
842 static gchar *expand_search_string(const gchar *search_string)
843 {
844         int i = 0;
845         gchar term_char, save_char;
846         gchar *cmd_start, *cmd_end;
847         GString *matcherstr;
848         gchar *returnstr = NULL;
849         gchar *copy_str;
850         gboolean casesens, dontmatch;
851         /* list of allowed pattern abbreviations */
852         struct {
853                 gchar           *abbreviated;   /* abbreviation */
854                 gchar           *command;       /* actual matcher command */
855                 gint            numparams;      /* number of params for cmd */
856                 gboolean        qualifier;      /* do we append regexpcase */
857                 gboolean        quotes;         /* do we need quotes */
858         }
859         cmds[] = {
860                 { "a",  "all",                          0,      FALSE,  FALSE },
861                 { "ag", "age_greater",                  1,      FALSE,  FALSE },
862                 { "al", "age_lower",                    1,      FALSE,  FALSE },
863                 { "b",  "body_part",                    1,      TRUE,   TRUE  },
864                 { "B",  "message",                      1,      TRUE,   TRUE  },
865                 { "c",  "cc",                           1,      TRUE,   TRUE  },
866                 { "C",  "to_or_cc",                     1,      TRUE,   TRUE  },
867                 { "D",  "deleted",                      0,      FALSE,  FALSE },
868                 { "e",  "header \"Sender\"",            1,      TRUE,   TRUE  },
869                 { "E",  "execute",                      1,      FALSE,  TRUE  },
870                 { "f",  "from",                         1,      TRUE,   TRUE  },
871                 { "F",  "forwarded",                    0,      FALSE,  FALSE },
872                 { "h",  "headers_part",                 1,      TRUE,   TRUE  },
873                 { "i",  "header \"Message-ID\"",        1,      TRUE,   TRUE  },
874                 { "I",  "inreplyto",                    1,      TRUE,   TRUE  },
875                 { "k",  "colorlabel",                   1,      FALSE,  FALSE },
876                 { "L",  "locked",                       0,      FALSE,  FALSE },
877                 { "n",  "newsgroups",                   1,      TRUE,   TRUE  },
878                 { "N",  "new",                          0,      FALSE,  FALSE },
879                 { "O",  "~new",                         0,      FALSE,  FALSE },
880                 { "r",  "replied",                      0,      FALSE,  FALSE },
881                 { "R",  "~unread",                      0,      FALSE,  FALSE },
882                 { "s",  "subject",                      1,      TRUE,   TRUE  },
883                 { "se", "score_equal",                  1,      FALSE,  FALSE },
884                 { "sg", "score_greater",                1,      FALSE,  FALSE },
885                 { "sl", "score_lower",                  1,      FALSE,  FALSE },
886                 { "Se", "size_equal",                   1,      FALSE,  FALSE },
887                 { "Sg", "size_greater",                 1,      FALSE,  FALSE },
888                 { "Ss", "size_smaller",                 1,      FALSE,  FALSE },
889                 { "t",  "to",                           1,      TRUE,   TRUE  },
890                 { "T",  "marked",                       0,      FALSE,  FALSE },
891                 { "U",  "unread",                       0,      FALSE,  FALSE },
892                 { "x",  "header \"References\"",        1,      TRUE,   TRUE  },
893                 { "X",  "test",                         1,      FALSE,  FALSE },
894                 { "y",  "header \"X-Label\"",           1,      TRUE,   TRUE  },
895                 { "&",  "&",                            0,      FALSE,  FALSE },
896                 { "|",  "|",                            0,      FALSE,  FALSE },
897                 { "p",  "partial",                      0,      FALSE,  FALSE },
898                 { NULL, NULL,                           0,      FALSE,  FALSE }
899         };
900
901         if (search_string == NULL)
902                 return NULL;
903
904         copy_str = g_strdup(search_string);
905
906         matcherstr = g_string_sized_new(16);
907         cmd_start = copy_str;
908         while (cmd_start && *cmd_start) {
909                 /* skip all white spaces */
910                 while (*cmd_start && isspace((guchar)*cmd_start))
911                         cmd_start++;
912                 cmd_end = cmd_start;
913
914                 /* extract a command */
915                 while (*cmd_end && !isspace((guchar)*cmd_end))
916                         cmd_end++;
917
918                 /* save character */
919                 save_char = *cmd_end;
920                 *cmd_end = '\0';
921
922                 dontmatch = FALSE;
923                 casesens = FALSE;
924
925                 /* ~ and ! mean logical NOT */
926                 if (*cmd_start == '~' || *cmd_start == '!')
927                 {
928                         dontmatch = TRUE;
929                         cmd_start++;
930                 }
931                 /* % means case sensitive match */
932                 if (*cmd_start == '%')
933                 {
934                         casesens = TRUE;
935                         cmd_start++;
936                 }
937
938                 /* find matching abbreviation */
939                 for (i = 0; cmds[i].command; i++) {
940                         if (!strcmp(cmd_start, cmds[i].abbreviated)) {
941                                 /* restore character */
942                                 *cmd_end = save_char;
943
944                                 /* copy command */
945                                 if (matcherstr->len > 0) {
946                                         g_string_append(matcherstr, " ");
947                                 }
948                                 if (dontmatch)
949                                         g_string_append(matcherstr, "~");
950                                 g_string_append(matcherstr, cmds[i].command);
951                                 g_string_append(matcherstr, " ");
952
953                                 /* stop if no params required */
954                                 if (cmds[i].numparams == 0)
955                                         break;
956
957                                 /* extract a parameter, allow quotes */
958                                 while (*cmd_end && isspace((guchar)*cmd_end))
959                                         cmd_end++;
960
961                                 cmd_start = cmd_end;
962                                 if (*cmd_start == '"') {
963                                         term_char = '"';
964                                         cmd_end++;
965                                 }
966                                 else
967                                         term_char = ' ';
968
969                                 /* extract actual parameter */
970                                 while ((*cmd_end) && (*cmd_end != term_char))
971                                         cmd_end++;
972
973                                 if (*cmd_end == '"')
974                                         cmd_end++;
975
976                                 save_char = *cmd_end;
977                                 *cmd_end = '\0';
978
979                                 if (cmds[i].qualifier) {
980                                         if (casesens)
981                                                 g_string_append(matcherstr, "regexp ");
982                                         else
983                                                 g_string_append(matcherstr, "regexpcase ");
984                                 }
985
986                                 /* do we need to add quotes ? */
987                                 if (cmds[i].quotes && term_char != '"')
988                                         g_string_append(matcherstr, "\"");
989
990                                 /* copy actual parameter */
991                                 g_string_append(matcherstr, cmd_start);
992
993                                 /* do we need to add quotes ? */
994                                 if (cmds[i].quotes && term_char != '"')
995                                         g_string_append(matcherstr, "\"");
996
997                                 /* restore original character */
998                                 *cmd_end = save_char;
999
1000                                 break;
1001                         }
1002                 }
1003
1004                 if (*cmd_end)
1005                         cmd_end++;
1006                 cmd_start = cmd_end;
1007         }
1008
1009         g_free(copy_str);
1010
1011         /* return search string if no match is found to allow
1012            all available filtering expressions in quicksearch */
1013         if (matcherstr->len > 0) returnstr = matcherstr->str;
1014         else returnstr = g_strdup(search_string);
1015
1016         g_string_free(matcherstr, FALSE);
1017         return returnstr;
1018 }
1019
1020 static void quicksearch_set_running(QuickSearch *quicksearch, gboolean run)
1021 {
1022         quicksearch->running = run;
1023 }
1024
1025 gboolean quicksearch_is_running(QuickSearch *quicksearch)
1026 {
1027         return quicksearch->running;
1028 }
1029
1030 void quicksearch_pass_key(QuickSearch *quicksearch, guint val, GdkModifierType mod)
1031 {
1032         GtkEntry *entry = GTK_ENTRY(GTK_COMBO(quicksearch->search_string_entry)->entry);
1033         glong curpos = gtk_editable_get_position(GTK_EDITABLE(entry));
1034         guint32 c;
1035         char *str = g_strdup(gtk_entry_get_text(entry));
1036         char *begin = str;
1037         char *end = NULL;
1038         char *new = NULL;
1039         char key[7] = "";
1040         guint char_len = 0;
1041
1042         if (gtk_editable_get_selection_bounds(GTK_EDITABLE(entry), NULL, NULL)) {
1043                 /* remove selection */
1044                 gtk_editable_delete_selection(GTK_EDITABLE(entry));
1045                 curpos = gtk_editable_get_position(GTK_EDITABLE(entry));
1046                 /* refresh string */
1047                 g_free(str);
1048                 str = g_strdup(gtk_entry_get_text(entry));
1049                 begin = str;
1050         }
1051
1052         if (!(c = gdk_keyval_to_unicode(val))) {
1053                 g_free(str);
1054                 return;
1055         }
1056         char_len = g_unichar_to_utf8(c, key);
1057         if (char_len < 0)
1058                 return;
1059         key[char_len] = '\0';
1060         if (curpos < g_utf8_strlen(str, -1)) {
1061                 gchar *stop = g_utf8_offset_to_pointer(begin, curpos);
1062                 end = g_strdup(g_utf8_offset_to_pointer(str, curpos));
1063                 *stop = '\0';
1064                 new = g_strdup_printf("%s%s%s", begin, key, end);
1065                 gtk_entry_set_text(entry, new);
1066                 g_free(end);
1067         } else {
1068                 new = g_strdup_printf("%s%s", begin, key);
1069                 gtk_entry_set_text(entry, new);
1070         }
1071         g_free(str);
1072         g_free(new);
1073         gtk_editable_set_position(GTK_EDITABLE(entry), curpos+1);
1074
1075 }
1076
1077 static gboolean quicksearch_match_subfolder(QuickSearch *quicksearch,
1078                                  FolderItem *src)
1079 {
1080         GSList *msglist = folder_item_get_msg_list(src);
1081         GSList *cur;
1082         gboolean result = FALSE;
1083         gint num = 0, total = src->total_msgs;
1084         gint interval = quicksearch_is_fast(quicksearch) ? 5000:100;
1085
1086         statusbar_print_all(_("Searching in %s... \n"),
1087                 src->path ? src->path : "(null)");
1088         folder_item_update_freeze();
1089         for (cur = msglist; cur != NULL; cur = cur->next) {
1090                 MsgInfo *msg = (MsgInfo *)cur->data;
1091                 statusbar_progress_all(num++,total, interval);
1092                 if (quicksearch_match(quicksearch, msg)) {
1093                         result = TRUE;
1094                         break;
1095                 }
1096                 if (num % interval == 0)
1097                         GTK_EVENTS_FLUSH();
1098                 if (!quicksearch_is_active(quicksearch))
1099                         break;
1100         }
1101         folder_item_update_thaw();
1102         statusbar_progress_all(0,0,0);
1103         statusbar_pop_all();
1104
1105         procmsg_msg_list_free(msglist);
1106         return result;
1107 }
1108
1109 void quicksearch_search_subfolders(QuickSearch *quicksearch,
1110                                    FolderView *folderview,
1111                                    FolderItem *folder_item)
1112 {
1113         FolderItem *cur = NULL;
1114         GNode *node = folder_item->node->children;
1115
1116         if (!prefs_common.summary_quicksearch_recurse
1117         ||  quicksearch->in_typing == TRUE)
1118                 return;
1119
1120         for (; node != NULL; node = node->next) {
1121                 cur = FOLDER_ITEM(node->data);
1122                 if (quicksearch_match_subfolder(quicksearch, cur)) {
1123                         folderview_update_search_icon(cur, TRUE);
1124                 } else {
1125                         folderview_update_search_icon(cur, FALSE);
1126                 }
1127                 if (cur->node->children)
1128                         quicksearch_search_subfolders(quicksearch,
1129                                                       folderview,
1130                                                       cur);
1131         }
1132         quicksearch->root_folder_item = folder_item;
1133         if (!quicksearch_is_active(quicksearch))
1134                 quicksearch_reset_cur_folder_item(quicksearch);
1135 }
1136
1137 static void quicksearch_reset_folder_items(QuickSearch *quicksearch,
1138                                     FolderItem *folder_item)
1139 {
1140         FolderItem *cur = NULL;
1141         GNode *node = (folder_item && folder_item->node) ?
1142                         folder_item->node->children : NULL;
1143
1144         for (; node != NULL; node = node->next) {
1145                 cur = FOLDER_ITEM(node->data);
1146                 folderview_update_search_icon(cur, FALSE);
1147                 if (cur->node->children)
1148                         quicksearch_reset_folder_items(quicksearch,
1149                                                        cur);
1150         }
1151 }
1152
1153 void quicksearch_reset_cur_folder_item(QuickSearch *quicksearch)
1154 {
1155         if (quicksearch->root_folder_item)
1156                 quicksearch_reset_folder_items(quicksearch,
1157                                                quicksearch->root_folder_item);
1158
1159         quicksearch->root_folder_item = NULL;
1160 }
1161
1162 gboolean quicksearch_is_in_typing(QuickSearch *quicksearch)
1163 {
1164         return quicksearch->in_typing;
1165 }