2006-12-01 [wwp] 2.6.0cvs73
[claws.git] / src / gtk / quicksearch.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 2004 Hiroyuki Yamamoto & the Claws Mail team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include <glib.h>
25 #include <glib/gi18n.h>
26 #include <ctype.h>
27
28 #include <gtk/gtk.h>
29 #include <gdk/gdkkeysyms.h>
30
31 #include "utils.h"
32 #include "combobox.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
75 gboolean quicksearch_is_fast(QuickSearch *quicksearch)
76 {
77         return quicksearch->is_fast;
78 }
79
80 static void prepare_matcher(QuickSearch *quicksearch)
81 {
82         const gchar *search_string = gtk_entry_get_text(GTK_ENTRY(GTK_BIN(quicksearch->search_string_entry)->child));
83
84         if (search_string == NULL || search_string[0] == '\0') {
85                 quicksearch_set_active(quicksearch, FALSE);
86         }
87
88         if (quicksearch->matcher_list != NULL) {
89                 if (quicksearch->matching) {
90                         quicksearch->deferred_free = TRUE;
91                         return;
92                 }
93                 quicksearch->deferred_free = FALSE;
94                 matcherlist_free(quicksearch->matcher_list);
95                 quicksearch->matcher_list = NULL;
96         }
97
98         if (search_string == NULL || search_string[0] == '\0') {
99                 return;
100         }
101
102         if (prefs_common.summary_quicksearch_type == QUICK_SEARCH_EXTENDED) {
103                 char *newstr = NULL;
104
105                 newstr = expand_search_string(search_string);
106                 if (newstr && newstr[0] != '\0') {
107                         quicksearch->matcher_list = matcher_parser_get_cond(newstr, &quicksearch->is_fast);
108                         g_free(newstr);
109                 } else {
110                         quicksearch->matcher_list = NULL;
111                         quicksearch_set_active(quicksearch, FALSE);
112
113                         return;
114                 }
115         } else {
116                 quicksearch->is_fast = TRUE;
117                 g_free(quicksearch->search_string);
118                 quicksearch->search_string = g_strdup(search_string);
119         }
120
121         quicksearch_set_active(quicksearch, TRUE);
122 }
123
124 static void update_extended_buttons (QuickSearch *quicksearch)
125 {
126         GtkWidget *expr_btn = quicksearch->search_condition_expression;
127         GtkWidget *ext_btn = quicksearch->search_description;
128
129         g_return_if_fail(expr_btn != NULL);
130         g_return_if_fail(ext_btn != NULL);
131
132         if (prefs_common.summary_quicksearch_type == QUICK_SEARCH_EXTENDED) {
133                 gtk_widget_show(expr_btn);
134                 gtk_widget_show(ext_btn);
135         } else {
136                 gtk_widget_hide(expr_btn);
137                 gtk_widget_hide(ext_btn);
138         }
139 }
140
141 static gboolean searchbar_focus_evt_in(GtkWidget *widget, GdkEventFocus *event,
142                                   QuickSearch *qs)
143 {
144         qs->has_focus = TRUE;
145         return FALSE;
146 }
147
148 static gboolean searchbar_focus_evt_out(GtkWidget *widget, GdkEventFocus *event,
149                                   QuickSearch *qs)
150 {
151         qs->has_focus = FALSE;
152         qs->in_typing = FALSE;
153         return FALSE;
154 }
155
156 gboolean quicksearch_has_focus(QuickSearch *quicksearch)
157 {
158         return quicksearch->has_focus;
159 }
160
161 static void searchbar_run(QuickSearch *quicksearch, gboolean run_only_if_fast)
162 {
163         const gchar *search_string = gtk_entry_get_text(GTK_ENTRY(GTK_BIN(quicksearch->search_string_entry)->child));
164
165         /* add to history */
166         if (!quicksearch->in_typing && search_string && strlen(search_string) != 0) {
167                 combobox_unset_popdown_strings(GTK_COMBO_BOX(quicksearch->search_string_entry));
168                 prefs_common.summary_quicksearch_history =
169                         add_history(prefs_common.summary_quicksearch_history,
170                                         search_string);
171                 combobox_set_popdown_strings(GTK_COMBO_BOX(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         gtk_widget_grab_focus(qs->search_string_entry);
209
210         return FALSE;
211 }
212
213 static gboolean searchbar_pressed(GtkWidget *widget, GdkEventKey *event,
214                                   QuickSearch *quicksearch)
215 {
216         if (event != NULL && event->keyval == GDK_Escape) {
217
218                 const gchar *str;
219
220                 quicksearch->in_typing = FALSE;
221
222                 str = gtk_entry_get_text(GTK_ENTRY(GTK_BIN(quicksearch->search_string_entry)->child));
223                 g_return_val_if_fail(str != NULL, TRUE);
224
225                 /* If the string entry is empty -> hide quicksearch bar. If not -> empty it */
226                 if (!*str) {
227                         quicksearch_hide(quicksearch);
228                 } else {
229                         quicksearch_set(quicksearch, prefs_common.summary_quicksearch_type, "");
230                         gtk_widget_grab_focus(
231                                         GTK_WIDGET(GTK_BIN(quicksearch->search_string_entry)->child));
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_BIN(quicksearch->search_string_entry)->child));
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_BIN(quicksearch->search_string_entry)->child));
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 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_BIN(mainwindow_get_mainwindow()->summaryview->quicksearch->
442                         search_string_entry)->child));
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 *search_cond_expr_tip;
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_box_entry_new_text ();
536         gtk_combo_box_set_active(GTK_COMBO_BOX(search_string_entry), -1);
537         if (prefs_common.summary_quicksearch_history)
538                 combobox_set_popdown_strings(GTK_COMBO_BOX(search_string_entry),
539                                 prefs_common.summary_quicksearch_history);
540         gtk_box_pack_start(GTK_BOX(hbox_search), search_string_entry, FALSE, FALSE, 2);
541         gtk_widget_show(search_string_entry);
542
543         search_hbox = gtk_hbox_new(FALSE, 5);
544
545 #if GTK_CHECK_VERSION(2, 8, 0)
546         clear_search = gtk_button_new_from_stock(GTK_STOCK_CLEAR);
547 #else
548         clear_search = gtk_button_new_with_label(_(" Clear "));
549 #endif
550         gtk_box_pack_start(GTK_BOX(search_hbox), clear_search,
551                            FALSE, FALSE, 0);
552         g_signal_connect(G_OBJECT(clear_search), "clicked",
553                          G_CALLBACK(clear_search_cb), quicksearch);
554         gtk_widget_show(clear_search);
555
556 #if GTK_CHECK_VERSION(2, 8, 0)
557         search_condition_expression = gtk_button_new_from_stock(GTK_STOCK_EDIT);
558 #else
559         search_condition_expression = gtk_button_new_with_label(" ... ");
560 #endif
561         gtk_box_pack_start(GTK_BOX(search_hbox), search_condition_expression,
562                            FALSE, FALSE, 0);
563         g_signal_connect(G_OBJECT (search_condition_expression), "clicked",
564                          G_CALLBACK(search_condition_expr),
565                          quicksearch);
566         search_cond_expr_tip = gtk_tooltips_new();
567         gtk_tooltips_set_tip(GTK_TOOLTIPS(search_cond_expr_tip),
568                              search_condition_expression,
569                              _("Edit search criteria"), NULL);
570         gtk_widget_show(search_condition_expression);
571
572 #if GTK_CHECK_VERSION(2, 8, 0)
573         search_description = gtk_button_new_from_stock(GTK_STOCK_INFO);
574 #else
575         search_description = gtk_button_new_with_label(_(" Extended Symbols... "));
576 #endif
577         gtk_box_pack_start(GTK_BOX(search_hbox), search_description,
578                            FALSE, FALSE, 0);
579         g_signal_connect(G_OBJECT(search_description), "clicked",
580                          G_CALLBACK(search_description_cb), NULL);
581         gtk_widget_show(search_description);
582
583         gtk_box_pack_start(GTK_BOX(hbox_search), search_hbox, FALSE, FALSE, 2);
584         gtk_widget_show(search_hbox);
585
586         g_signal_connect(G_OBJECT(GTK_BIN(search_string_entry)->child),
587                            "key_press_event",
588                            G_CALLBACK(searchbar_pressed),
589                            quicksearch);
590
591         g_signal_connect(G_OBJECT(GTK_BIN(search_string_entry)->child),
592                          "changed",
593                          G_CALLBACK(searchbar_changed_cb),
594                          quicksearch);
595
596         g_signal_connect(G_OBJECT(GTK_BIN(search_string_entry)->child),
597                          "focus_in_event",
598                          G_CALLBACK(searchbar_focus_evt_in),
599                          quicksearch);
600         g_signal_connect(G_OBJECT(GTK_BIN(search_string_entry)->child),
601                          "focus_out_event",
602                          G_CALLBACK(searchbar_focus_evt_out),
603                          quicksearch);
604
605         quicksearch->hbox_search = hbox_search;
606         quicksearch->search_type = search_type;
607         quicksearch->search_type_opt = search_type_opt;
608         quicksearch->search_string_entry = search_string_entry;
609         quicksearch->search_condition_expression = search_condition_expression;
610         quicksearch->search_description = search_description;
611         quicksearch->matcher_list = NULL;
612         quicksearch->active = FALSE;
613         quicksearch->running = FALSE;
614         quicksearch->clear_search = clear_search;
615         quicksearch->in_typing = FALSE;
616         quicksearch->press_timeout_id = -1;
617
618         update_extended_buttons(quicksearch);
619
620         return quicksearch;
621 }
622
623 GtkWidget *quicksearch_get_widget(QuickSearch *quicksearch)
624 {
625         return quicksearch->hbox_search;
626 }
627
628 void quicksearch_show(QuickSearch *quicksearch)
629 {
630         prepare_matcher(quicksearch);
631         gtk_widget_show(quicksearch->hbox_search);
632         update_extended_buttons(quicksearch);
633         gtk_widget_grab_focus(
634                 GTK_WIDGET(GTK_BIN(quicksearch->search_string_entry)->child));
635 }
636
637 void quicksearch_hide(QuickSearch *quicksearch)
638 {
639         quicksearch_set(quicksearch, prefs_common.summary_quicksearch_type, "");
640         quicksearch_set_active(quicksearch, FALSE);
641         gtk_widget_hide(quicksearch->hbox_search);
642 }
643
644 void quicksearch_set(QuickSearch *quicksearch, QuickSearchType type,
645                      const gchar *matchstring)
646 {
647         gtk_option_menu_set_history(GTK_OPTION_MENU(quicksearch->search_type_opt),
648                                     type);
649
650         g_signal_handlers_block_by_func(G_OBJECT(GTK_BIN(quicksearch->search_string_entry)->child),
651                         G_CALLBACK(searchbar_changed_cb), quicksearch);
652         gtk_entry_set_text(GTK_ENTRY(GTK_BIN(quicksearch->search_string_entry)->child),
653                            matchstring);
654         g_signal_handlers_unblock_by_func(G_OBJECT(GTK_BIN(quicksearch->search_string_entry)->child),
655                         G_CALLBACK(searchbar_changed_cb), quicksearch);
656
657         prefs_common.summary_quicksearch_type = type;
658
659         prepare_matcher(quicksearch);
660
661         quicksearch_set_running(quicksearch, TRUE);
662         if (quicksearch->callback != NULL)
663                 quicksearch->callback(quicksearch, quicksearch->callback_data);
664         quicksearch_set_running(quicksearch, FALSE);
665 }
666
667 gboolean quicksearch_is_active(QuickSearch *quicksearch)
668 {
669         return quicksearch->active && 
670                 (prefs_common.summary_quicksearch_type != QUICK_SEARCH_EXTENDED
671                  || quicksearch->matcher_list != NULL);
672 }
673
674 static void quicksearch_set_active(QuickSearch *quicksearch, gboolean active)
675 {
676         static GdkColor yellow;
677         static GdkColor red;
678         static GdkColor black;
679         static gboolean colors_initialised = FALSE;
680         gboolean error = FALSE;
681
682         if (!colors_initialised) {
683                 gdk_color_parse("#f5f6be", &yellow);
684                 gdk_color_parse("#000000", &black);
685                 gdk_color_parse("#ff7070", &red);
686                 colors_initialised = gdk_colormap_alloc_color(
687                         gdk_colormap_get_system(), &yellow, FALSE, TRUE);
688                 colors_initialised &= gdk_colormap_alloc_color(
689                         gdk_colormap_get_system(), &black, FALSE, TRUE);
690                 colors_initialised &= gdk_colormap_alloc_color(
691                         gdk_colormap_get_system(), &red, FALSE, TRUE);
692         }
693
694         quicksearch->active = active;
695
696         if (active && 
697                 (prefs_common.summary_quicksearch_type == QUICK_SEARCH_EXTENDED
698                  && quicksearch->matcher_list == NULL))
699                 error = TRUE;
700
701         if (active) {
702                 gtk_widget_set_sensitive(quicksearch->clear_search, TRUE);
703                 if (colors_initialised) {
704                         gtk_widget_modify_base(
705                                 GTK_BIN(quicksearch->search_string_entry)->child,
706                                 GTK_STATE_NORMAL, error ? &red : &yellow);
707                         gtk_widget_modify_text(
708                                 GTK_BIN(quicksearch->search_string_entry)->child,
709                                 GTK_STATE_NORMAL, &black);
710                 }
711         } else {
712                 gtk_widget_set_sensitive(quicksearch->clear_search, FALSE);
713                 if (colors_initialised) {
714                         gtk_widget_modify_base(
715                                 GTK_BIN(quicksearch->search_string_entry)->child,
716                                 GTK_STATE_NORMAL, NULL);
717                         gtk_widget_modify_text(
718                                 GTK_BIN(quicksearch->search_string_entry)->child,
719                                 GTK_STATE_NORMAL, NULL);
720                 }
721         }
722
723         if (!active) {
724                 quicksearch_reset_cur_folder_item(quicksearch);
725         }
726 }
727
728 void quicksearch_set_execute_callback(QuickSearch *quicksearch,
729                                       QuickSearchExecuteCallback callback,
730                                       gpointer data)
731 {
732         quicksearch->callback = callback;
733         quicksearch->callback_data = data;
734 }
735
736 gboolean quicksearch_match(QuickSearch *quicksearch, MsgInfo *msginfo)
737 {
738         gchar *searched_header = NULL;
739         gboolean result = FALSE;
740
741         if (!quicksearch->active)
742                 return TRUE;
743
744         switch (prefs_common.summary_quicksearch_type) {
745         case QUICK_SEARCH_SUBJECT:
746                 searched_header = msginfo->subject;
747                 break;
748         case QUICK_SEARCH_FROM:
749                 searched_header = msginfo->from;
750                 break;
751         case QUICK_SEARCH_TO:
752                 searched_header = msginfo->to;
753                 break;
754         case QUICK_SEARCH_EXTENDED:
755                 break;
756         default:
757                 debug_print("unknown search type (%d)\n", prefs_common.summary_quicksearch_type);
758                 break;
759         }
760         quicksearch->matching = TRUE;
761         if (prefs_common.summary_quicksearch_type != QUICK_SEARCH_EXTENDED &&
762             quicksearch->search_string &&
763             searched_header && strcasestr(searched_header, quicksearch->search_string) != NULL)
764                 result = TRUE;
765         else if ((quicksearch->matcher_list != NULL) &&
766                  matcherlist_match(quicksearch->matcher_list, msginfo))
767                 result = TRUE;
768
769         quicksearch->matching = FALSE;
770         if (quicksearch->deferred_free) {
771                 prepare_matcher(quicksearch);
772         }
773
774         return result;
775 }
776
777 /* allow Mutt-like patterns in quick search */
778 gchar *expand_search_string(const gchar *search_string)
779 {
780         int i = 0;
781         gchar term_char, save_char;
782         gchar *cmd_start, *cmd_end;
783         GString *matcherstr;
784         gchar *returnstr = NULL;
785         gchar *copy_str;
786         gboolean casesens, dontmatch;
787         /* list of allowed pattern abbreviations */
788         struct {
789                 gchar           *abbreviated;   /* abbreviation */
790                 gchar           *command;       /* actual matcher command */
791                 gint            numparams;      /* number of params for cmd */
792                 gboolean        qualifier;      /* do we append regexpcase */
793                 gboolean        quotes;         /* do we need quotes */
794         }
795         cmds[] = {
796                 { "a",  "all",                          0,      FALSE,  FALSE },
797                 { "ag", "age_greater",                  1,      FALSE,  FALSE },
798                 { "al", "age_lower",                    1,      FALSE,  FALSE },
799                 { "b",  "body_part",                    1,      TRUE,   TRUE  },
800                 { "B",  "message",                      1,      TRUE,   TRUE  },
801                 { "c",  "cc",                           1,      TRUE,   TRUE  },
802                 { "C",  "to_or_cc",                     1,      TRUE,   TRUE  },
803                 { "D",  "deleted",                      0,      FALSE,  FALSE },
804                 { "e",  "header \"Sender\"",            1,      TRUE,   TRUE  },
805                 { "E",  "execute",                      1,      FALSE,  TRUE  },
806                 { "f",  "from",                         1,      TRUE,   TRUE  },
807                 { "F",  "forwarded",                    0,      FALSE,  FALSE },
808                 { "h",  "headers_part",                 1,      TRUE,   TRUE  },
809                 { "i",  "header \"Message-ID\"",        1,      TRUE,   TRUE  },
810                 { "I",  "inreplyto",                    1,      TRUE,   TRUE  },
811                 { "k",  "colorlabel",                   1,      FALSE,  FALSE },
812                 { "L",  "locked",                       0,      FALSE,  FALSE },
813                 { "n",  "newsgroups",                   1,      TRUE,   TRUE  },
814                 { "N",  "new",                          0,      FALSE,  FALSE },
815                 { "O",  "~new",                         0,      FALSE,  FALSE },
816                 { "r",  "replied",                      0,      FALSE,  FALSE },
817                 { "R",  "~unread",                      0,      FALSE,  FALSE },
818                 { "s",  "subject",                      1,      TRUE,   TRUE  },
819                 { "se", "score_equal",                  1,      FALSE,  FALSE },
820                 { "sg", "score_greater",                1,      FALSE,  FALSE },
821                 { "sl", "score_lower",                  1,      FALSE,  FALSE },
822                 { "Se", "size_equal",                   1,      FALSE,  FALSE },
823                 { "Sg", "size_greater",                 1,      FALSE,  FALSE },
824                 { "Ss", "size_smaller",                 1,      FALSE,  FALSE },
825                 { "t",  "to",                           1,      TRUE,   TRUE  },
826                 { "T",  "marked",                       0,      FALSE,  FALSE },
827                 { "U",  "unread",                       0,      FALSE,  FALSE },
828                 { "x",  "header \"References\"",        1,      TRUE,   TRUE  },
829                 { "X",  "test",                         1,      FALSE,  FALSE },
830                 { "y",  "header \"X-Label\"",           1,      TRUE,   TRUE  },
831                 { "&",  "&",                            0,      FALSE,  FALSE },
832                 { "|",  "|",                            0,      FALSE,  FALSE },
833                 { "p",  "partial",                      0,      FALSE,  FALSE },
834                 { NULL, NULL,                           0,      FALSE,  FALSE }
835         };
836
837         if (search_string == NULL)
838                 return NULL;
839
840         copy_str = g_strdup(search_string);
841
842         matcherstr = g_string_sized_new(16);
843         cmd_start = copy_str;
844         while (cmd_start && *cmd_start) {
845                 /* skip all white spaces */
846                 while (*cmd_start && isspace((guchar)*cmd_start))
847                         cmd_start++;
848                 cmd_end = cmd_start;
849
850                 /* extract a command */
851                 while (*cmd_end && !isspace((guchar)*cmd_end))
852                         cmd_end++;
853
854                 /* save character */
855                 save_char = *cmd_end;
856                 *cmd_end = '\0';
857
858                 dontmatch = FALSE;
859                 casesens = FALSE;
860
861                 /* ~ and ! mean logical NOT */
862                 if (*cmd_start == '~' || *cmd_start == '!')
863                 {
864                         dontmatch = TRUE;
865                         cmd_start++;
866                 }
867                 /* % means case sensitive match */
868                 if (*cmd_start == '%')
869                 {
870                         casesens = TRUE;
871                         cmd_start++;
872                 }
873
874                 /* find matching abbreviation */
875                 for (i = 0; cmds[i].command; i++) {
876                         if (!strcmp(cmd_start, cmds[i].abbreviated)) {
877                                 /* restore character */
878                                 *cmd_end = save_char;
879
880                                 /* copy command */
881                                 if (matcherstr->len > 0) {
882                                         g_string_append(matcherstr, " ");
883                                 }
884                                 if (dontmatch)
885                                         g_string_append(matcherstr, "~");
886                                 g_string_append(matcherstr, cmds[i].command);
887                                 g_string_append(matcherstr, " ");
888
889                                 /* stop if no params required */
890                                 if (cmds[i].numparams == 0)
891                                         break;
892
893                                 /* extract a parameter, allow quotes */
894                                 while (*cmd_end && isspace((guchar)*cmd_end))
895                                         cmd_end++;
896
897                                 cmd_start = cmd_end;
898                                 if (*cmd_start == '"') {
899                                         term_char = '"';
900                                         cmd_end++;
901                                 }
902                                 else
903                                         term_char = ' ';
904
905                                 /* extract actual parameter */
906                                 while ((*cmd_end) && (*cmd_end != term_char))
907                                         cmd_end++;
908
909                                 if (*cmd_end == '"')
910                                         cmd_end++;
911
912                                 save_char = *cmd_end;
913                                 *cmd_end = '\0';
914
915                                 if (cmds[i].qualifier) {
916                                         if (casesens)
917                                                 g_string_append(matcherstr, "regexp ");
918                                         else
919                                                 g_string_append(matcherstr, "regexpcase ");
920                                 }
921
922                                 /* do we need to add quotes ? */
923                                 if (cmds[i].quotes && term_char != '"')
924                                         g_string_append(matcherstr, "\"");
925
926                                 /* copy actual parameter */
927                                 g_string_append(matcherstr, cmd_start);
928
929                                 /* do we need to add quotes ? */
930                                 if (cmds[i].quotes && term_char != '"')
931                                         g_string_append(matcherstr, "\"");
932
933                                 /* restore original character */
934                                 *cmd_end = save_char;
935
936                                 break;
937                         }
938                 }
939
940                 if (*cmd_end)
941                         cmd_end++;
942                 cmd_start = cmd_end;
943         }
944
945         g_free(copy_str);
946
947         /* return search string if no match is found to allow
948            all available filtering expressions in quicksearch */
949         if (matcherstr->len > 0) returnstr = matcherstr->str;
950         else returnstr = g_strdup(search_string);
951
952         g_string_free(matcherstr, FALSE);
953         return returnstr;
954 }
955
956 static void quicksearch_set_running(QuickSearch *quicksearch, gboolean run)
957 {
958         quicksearch->running = run;
959 }
960
961 gboolean quicksearch_is_running(QuickSearch *quicksearch)
962 {
963         return quicksearch->running;
964 }
965
966 void quicksearch_pass_key(QuickSearch *quicksearch, guint val, GdkModifierType mod)
967 {
968         GtkEntry *entry = GTK_ENTRY(GTK_BIN(quicksearch->search_string_entry)->child);
969         glong curpos = gtk_editable_get_position(GTK_EDITABLE(entry));
970         guint32 c;
971         char *str = g_strdup(gtk_entry_get_text(entry));
972         char *begin = str;
973         char *end = NULL;
974         char *new = NULL;
975         char key[7] = "";
976         guint char_len = 0;
977
978         if (gtk_editable_get_selection_bounds(GTK_EDITABLE(entry), NULL, NULL)) {
979                 /* remove selection */
980                 gtk_editable_delete_selection(GTK_EDITABLE(entry));
981                 curpos = gtk_editable_get_position(GTK_EDITABLE(entry));
982                 /* refresh string */
983                 g_free(str);
984                 str = g_strdup(gtk_entry_get_text(entry));
985                 begin = str;
986         }
987
988         if (!(c = gdk_keyval_to_unicode(val))) {
989                 g_free(str);
990                 return;
991         }
992         char_len = g_unichar_to_utf8(c, key);
993         if (char_len < 0)
994                 return;
995         key[char_len] = '\0';
996         if (curpos < g_utf8_strlen(str, -1)) {
997                 gchar *stop = g_utf8_offset_to_pointer(begin, curpos);
998                 end = g_strdup(g_utf8_offset_to_pointer(str, curpos));
999                 *stop = '\0';
1000                 new = g_strdup_printf("%s%s%s", begin, key, end);
1001                 gtk_entry_set_text(entry, new);
1002                 g_free(end);
1003         } else {
1004                 new = g_strdup_printf("%s%s", begin, key);
1005                 gtk_entry_set_text(entry, new);
1006         }
1007         g_free(str);
1008         g_free(new);
1009         gtk_editable_set_position(GTK_EDITABLE(entry), curpos+1);
1010
1011 }
1012
1013 static gboolean quicksearch_match_subfolder(QuickSearch *quicksearch,
1014                                  FolderItem *src)
1015 {
1016         GSList *msglist = folder_item_get_msg_list(src);
1017         GSList *cur;
1018         gboolean result = FALSE;
1019         gint num = 0, total = src->total_msgs;
1020         gint interval = quicksearch_is_fast(quicksearch) ? 5000:100;
1021
1022         statusbar_print_all(_("Searching in %s... \n"),
1023                 src->path ? src->path : "(null)");
1024         folder_item_update_freeze();
1025         for (cur = msglist; cur != NULL; cur = cur->next) {
1026                 MsgInfo *msg = (MsgInfo *)cur->data;
1027                 statusbar_progress_all(num++,total, interval);
1028                 if (quicksearch_match(quicksearch, msg)) {
1029                         procmsg_msginfo_free(msg);
1030                         result = TRUE;
1031                         break;
1032                 }
1033                 procmsg_msginfo_free(msg);
1034                 if (num % interval == 0)
1035                         GTK_EVENTS_FLUSH();
1036                 if (!quicksearch_is_active(quicksearch))
1037                         break;
1038         }
1039         folder_item_update_thaw();
1040         statusbar_progress_all(0,0,0);
1041         statusbar_pop_all();
1042
1043         g_slist_free(msglist);
1044         return result;
1045 }
1046
1047 void quicksearch_search_subfolders(QuickSearch *quicksearch,
1048                                    FolderView *folderview,
1049                                    FolderItem *folder_item)
1050 {
1051         FolderItem *cur = NULL;
1052         GNode *node = folder_item->node->children;
1053
1054         if (!prefs_common.summary_quicksearch_recurse
1055         ||  quicksearch->in_typing == TRUE)
1056                 return;
1057
1058         for (; node != NULL; node = node->next) {
1059                 cur = FOLDER_ITEM(node->data);
1060                 if (quicksearch_match_subfolder(quicksearch, cur)) {
1061                         folderview_update_search_icon(cur, TRUE);
1062                 } else {
1063                         folderview_update_search_icon(cur, FALSE);
1064                 }
1065                 if (cur->node->children)
1066                         quicksearch_search_subfolders(quicksearch,
1067                                                       folderview,
1068                                                       cur);
1069         }
1070         quicksearch->root_folder_item = folder_item;
1071         if (!quicksearch_is_active(quicksearch))
1072                 quicksearch_reset_cur_folder_item(quicksearch);
1073 }
1074
1075 static void quicksearch_reset_folder_items(QuickSearch *quicksearch,
1076                                     FolderItem *folder_item)
1077 {
1078         FolderItem *cur = NULL;
1079         GNode *node = (folder_item && folder_item->node) ?
1080                         folder_item->node->children : NULL;
1081
1082         for (; node != NULL; node = node->next) {
1083                 cur = FOLDER_ITEM(node->data);
1084                 folderview_update_search_icon(cur, FALSE);
1085                 if (cur->node->children)
1086                         quicksearch_reset_folder_items(quicksearch,
1087                                                        cur);
1088         }
1089 }
1090
1091 void quicksearch_reset_cur_folder_item(QuickSearch *quicksearch)
1092 {
1093         if (quicksearch->root_folder_item)
1094                 quicksearch_reset_folder_items(quicksearch,
1095                                                quicksearch->root_folder_item);
1096
1097         quicksearch->root_folder_item = NULL;
1098 }
1099
1100 gboolean quicksearch_is_in_typing(QuickSearch *quicksearch)
1101 {
1102         return quicksearch->in_typing;
1103 }