Skip to main content

egui_pop_views/library/
filter.rs

1//! A search field with filter chips, giving the application a
2//! structured [`Filter`].
3//!
4//! Words typed search the images' names and tags; typed criteria become
5//! chips when Enter is pressed: `rating>=3` (or `rating:3`), `label:red`,
6//! `flag:pick` (`reject`, `none`), `tag:beach` (or `#beach`),
7//! `date:2024-06-01..2024-06-30`, `from:2024-06-01`, `to:2024-06-30`.
8//! The menu beside the field adds a rating, a label or a flag; each chip
9//! has its remove button, Backspace in the empty field removes the last
10//! one, and the clear button removes everything. Every change of the
11//! filter runs the `library.filter` step: a before-hook may refuse it or
12//! rewrite it; the application filters its images with what the output
13//! gives ([`Filter::matches`] does the usual matching).
14//!
15//! ```
16//! use egui_pop_views::library::filter::{Candidate, SearchField, SearchState};
17//!
18//! fn ui(ui: &mut egui::Ui, state: &mut SearchState, names: &[String], shown: &mut Vec<usize>) {
19//!     if let Some(filter) = SearchField::new("shoot").show(ui, state).changed {
20//!         *shown = (0..names.len())
21//!             .filter(|&i| filter.matches(&Candidate::named(&names[i])))
22//!             .collect();
23//!     }
24//! }
25//! ```
26
27use crate::app_link::AppHandle;
28use egui::{Key as EKey, Modifiers, Response, Role, TextEdit, Ui};
29use egui_pop_core::strings::{tr, tr_args, tr_with};
30use egui_pop_core::theme::Tokens;
31use egui_pop_core::tooltip::TooltipExt as _;
32use serde::{Deserialize, Serialize};
33use serde_json::{Value as Json, json};
34
35use super::marks::{ColorLabel, Flag, MAX_RATING, Marks};
36use super::plugin as lib;
37use super::tags::TagChip;
38use crate::strings as s;
39
40/// What the application filters its images by. Empty criteria filter
41/// nothing; all criteria must hold (labels and flags: any of them; tags:
42/// all of them).
43#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
44#[serde(default)]
45pub struct Filter {
46    /// Words, each found in the name or a tag (ignoring case).
47    #[serde(skip_serializing_if = "String::is_empty")]
48    pub text: String,
49    /// At least this many stars.
50    #[serde(skip_serializing_if = "Option::is_none")]
51    pub min_rating: Option<u8>,
52    /// One of these labels.
53    #[serde(skip_serializing_if = "Vec::is_empty")]
54    pub labels: Vec<ColorLabel>,
55    /// One of these flags.
56    #[serde(skip_serializing_if = "Vec::is_empty")]
57    pub flags: Vec<Flag>,
58    /// All of these tags.
59    #[serde(skip_serializing_if = "Vec::is_empty")]
60    pub tags: Vec<String>,
61    /// From this day (`YYYY-MM-DD`), included.
62    #[serde(skip_serializing_if = "Option::is_none")]
63    pub from: Option<String>,
64    /// Until this day, included.
65    #[serde(skip_serializing_if = "Option::is_none")]
66    pub to: Option<String>,
67}
68
69/// One criterion of a filter, as a chip shows it.
70#[derive(Clone, Debug, PartialEq, Eq)]
71pub enum FilterChip {
72    Rating(u8),
73    Label(ColorLabel),
74    Flag(Flag),
75    Tag(String),
76    /// The date range (either end may be open).
77    Dates {
78        from: Option<String>,
79        to: Option<String>,
80    },
81}
82
83/// An image as [`Filter::matches`] sees it.
84#[derive(Clone, Copy, Debug, Default)]
85pub struct Candidate<'a> {
86    pub name: &'a str,
87    pub marks: Marks,
88    pub tags: &'a [String],
89    /// Its day, `YYYY-MM-DD`.
90    pub date: Option<&'a str>,
91}
92
93impl<'a> Candidate<'a> {
94    /// An image known by its name only.
95    pub fn named(name: &'a str) -> Candidate<'a> {
96        Candidate {
97            name,
98            ..Candidate::default()
99        }
100    }
101}
102
103/// Whether `text` is a day, `YYYY-MM-DD`.
104pub fn is_day(text: &str) -> bool {
105    let b = text.as_bytes();
106    b.len() == 10
107        && b[4] == b'-'
108        && b[7] == b'-'
109        && b.iter()
110            .enumerate()
111            .all(|(i, c)| i == 4 || i == 7 || c.is_ascii_digit())
112}
113
114/// A search text cut at the spaces outside quotes, each term as typed
115/// (`label:red tag:"New York"` is `label:red` and `tag:"New York"`). A
116/// quote escaped inside quotes (`\"`) does not close them; an unclosed
117/// quote runs to the end. Without quotes, the words between spaces.
118pub fn split_terms(text: &str) -> Vec<&str> {
119    let mut out = Vec::new();
120    let mut start = None;
121    let mut open = false;
122    let mut run = 0usize;
123    for (i, c) in text.char_indices() {
124        if c.is_whitespace() && !open {
125            if let Some(s) = start.take() {
126                out.push(&text[s..i]);
127            }
128            continue;
129        }
130        start.get_or_insert(i);
131        match c {
132            '\\' if open => run += 1,
133            '"' => {
134                if !open || run.is_multiple_of(2) {
135                    open = !open;
136                }
137                run = 0;
138            }
139            _ => run = 0,
140        }
141    }
142    if let Some(s) = start {
143        out.push(&text[s..]);
144    }
145    out
146}
147
148/// A term's value with its quotes taken off and their escapes undone,
149/// the inverse of [`value_text`]: `"New York"` is `New York`,
150/// `"say \"hi\""` is `say "hi"`; a bare value is kept.
151///
152/// Inside quotes, backslashes are kept as typed (a Windows path), except
153/// a run of them right before a `"`: halved, and an odd one out makes
154/// that `"` a character rather than the end (the quoting of Windows
155/// command lines, so `"C:\Photos\"` is written `"C:\Photos\\"`). The
156/// same grammar as applications reading their own search terms this way,
157/// so a value one writes the other reads.
158pub fn read_value(raw: &str) -> String {
159    let mut out = String::new();
160    let mut chars = raw.char_indices();
161    let mut end = raw.len();
162    while let Some((i, c)) = chars.next() {
163        if c.is_whitespace() || c == ')' {
164            end = i;
165            break;
166        }
167        if c != '"' {
168            out.push(c);
169            continue;
170        }
171        let mut run = 0usize;
172        for (_, q) in chars.by_ref() {
173            match q {
174                '\\' => run += 1,
175                '"' => {
176                    out.extend(std::iter::repeat_n('\\', run / 2));
177                    if run.is_multiple_of(2) {
178                        run = 0;
179                        break;
180                    }
181                    run = 0;
182                    out.push('"');
183                }
184                q => {
185                    out.extend(std::iter::repeat_n('\\', run));
186                    run = 0;
187                    out.push(q);
188                }
189            }
190        }
191        out.extend(std::iter::repeat_n('\\', run));
192    }
193    out.push_str(&raw[end..]);
194    out
195}
196
197/// A value as written after `key:`, [`read_value`] reading it back
198/// whole: as it is when it can be (`beach`), quoted when it holds a
199/// space, a quote or a parenthesis, is empty, or starts like an operator
200/// (`"New York"`, `"say \"hi\""`).
201pub fn value_text(text: &str) -> String {
202    let bare = !text.is_empty()
203        && !text
204            .chars()
205            .any(|c| c.is_whitespace() || matches!(c, '"' | '(' | ')'))
206        && !text.starts_with(['<', '>', '=', '!', '~', '@']);
207    if bare {
208        return text.to_string();
209    }
210    let mut out = String::from('"');
211    let mut run = 0usize;
212    for ch in text.chars() {
213        match ch {
214            '\\' => run += 1,
215            '"' => {
216                out.extend(std::iter::repeat_n('\\', 2 * run + 1));
217                out.push('"');
218                run = 0;
219            }
220            ch => {
221                out.extend(std::iter::repeat_n('\\', run));
222                out.push(ch);
223                run = 0;
224            }
225        }
226    }
227    out.extend(std::iter::repeat_n('\\', 2 * run));
228    out.push('"');
229    out
230}
231
232impl Filter {
233    pub fn is_empty(&self) -> bool {
234        *self == Filter::default()
235    }
236
237    /// The criteria typed in `text`, the other words kept as the text.
238    ///
239    /// The text is cut at the spaces outside quotes ([`split_terms`]), so
240    /// a value may hold spaces when quoted: `tag:"New York"`, `#"a  b"`
241    /// (the spaces kept as typed). Inside quotes, `\"` is a quote and
242    /// `\\` before a quote is a backslash ([`read_value`]). The words
243    /// that are no criterion stay as typed, quotes included.
244    /// [`Self::to_text`] writes a filter back so that this reads it
245    /// whole.
246    pub fn parse(text: &str) -> Filter {
247        let mut f = Filter::default();
248        let mut words = Vec::new();
249        for w in split_terms(text) {
250            if !f.take(w) {
251                words.push(w);
252            }
253        }
254        f.text = words.join(" ");
255        f
256    }
257
258    /// The filter as text, [`Self::parse`] reading it back as it is: the
259    /// criteria (`rating>=3 label:red flag:pick tag:"New York"
260    /// date:2024-06-01..2024-06-30`), then the words. Tag values are
261    /// quoted when they need it ([`value_text`]); the words are written
262    /// as they are, being already in the grammar.
263    pub fn to_text(&self) -> String {
264        let mut out: Vec<String> = Vec::new();
265        if let Some(r) = self.min_rating {
266            out.push(format!("rating>={r}"));
267        }
268        out.extend(self.labels.iter().map(|l| format!("label:{}", l.name())));
269        out.extend(self.flags.iter().map(|f| format!("flag:{}", f.name())));
270        out.extend(self.tags.iter().map(|t| format!("tag:{}", value_text(t))));
271        match (&self.from, &self.to) {
272            (Some(f), Some(t)) => out.push(format!("date:{f}..{t}")),
273            (Some(f), None) => out.push(format!("from:{f}")),
274            (None, Some(t)) => out.push(format!("to:{t}")),
275            (None, None) => {}
276        }
277        if !self.text.trim().is_empty() {
278            out.push(self.text.trim().to_string());
279        }
280        out.join(" ")
281    }
282
283    /// Reads one typed criterion into the filter; whether it was one.
284    fn take(&mut self, w: &str) -> bool {
285        let lower = w.to_lowercase();
286        let rating = lower
287            .strip_prefix("rating>=")
288            .or_else(|| lower.strip_prefix("rating:"))
289            .or_else(|| lower.strip_prefix("stars:"));
290        if let Some(r) = rating.and_then(|r| r.parse::<u8>().ok()) {
291            self.min_rating = Some(r.min(MAX_RATING));
292            return true;
293        }
294        if let Some(l) = lower.strip_prefix("label:").and_then(ColorLabel::parse) {
295            if !self.labels.contains(&l) {
296                self.labels.push(l);
297            }
298            return true;
299        }
300        if let Some(fl) = lower.strip_prefix("flag:").and_then(Flag::parse) {
301            if !self.flags.contains(&fl) {
302                self.flags.push(fl);
303            }
304            return true;
305        }
306        if let Some(t) = w
307            .strip_prefix("tag:")
308            .or_else(|| w.strip_prefix('#'))
309            .map(read_value)
310            .filter(|t| !t.is_empty())
311        {
312            if !self.tags.contains(&t) {
313                self.tags.push(t);
314            }
315            return true;
316        }
317        if let Some((a, b)) = lower.strip_prefix("date:").and_then(|d| d.split_once(".."))
318            && (a.is_empty() || is_day(a))
319            && (b.is_empty() || is_day(b))
320            && !(a.is_empty() && b.is_empty())
321        {
322            self.from = (!a.is_empty()).then(|| a.to_string());
323            self.to = (!b.is_empty()).then(|| b.to_string());
324            return true;
325        }
326        if let Some(d) = lower.strip_prefix("from:").filter(|d| is_day(d)) {
327            self.from = Some(d.to_string());
328            return true;
329        }
330        if let Some(d) = lower.strip_prefix("to:").filter(|d| is_day(d)) {
331            self.to = Some(d.to_string());
332            return true;
333        }
334        false
335    }
336
337    /// This filter with `other`'s criteria added (its text after this
338    /// one's).
339    #[must_use]
340    pub fn merged(&self, other: &Filter) -> Filter {
341        let mut f = self.clone();
342        if !other.text.is_empty() {
343            f.text = [f.text.as_str(), other.text.as_str()]
344                .iter()
345                .filter(|t| !t.is_empty())
346                .copied()
347                .collect::<Vec<_>>()
348                .join(" ");
349        }
350        if other.min_rating.is_some() {
351            f.min_rating = other.min_rating;
352        }
353        for l in &other.labels {
354            if !f.labels.contains(l) {
355                f.labels.push(*l);
356            }
357        }
358        for fl in &other.flags {
359            if !f.flags.contains(fl) {
360                f.flags.push(*fl);
361            }
362        }
363        for t in &other.tags {
364            if !f.tags.contains(t) {
365                f.tags.push(t.clone());
366            }
367        }
368        if other.from.is_some() {
369            f.from.clone_from(&other.from);
370        }
371        if other.to.is_some() {
372            f.to.clone_from(&other.to);
373        }
374        f
375    }
376
377    /// Its criteria as chips (the text is not one).
378    pub fn chips(&self) -> Vec<FilterChip> {
379        let mut out = Vec::new();
380        if let Some(r) = self.min_rating {
381            out.push(FilterChip::Rating(r));
382        }
383        out.extend(self.labels.iter().map(|l| FilterChip::Label(*l)));
384        out.extend(self.flags.iter().map(|f| FilterChip::Flag(*f)));
385        out.extend(self.tags.iter().map(|t| FilterChip::Tag(t.clone())));
386        if self.from.is_some() || self.to.is_some() {
387            out.push(FilterChip::Dates {
388                from: self.from.clone(),
389                to: self.to.clone(),
390            });
391        }
392        out
393    }
394
395    /// Without that criterion.
396    pub fn remove(&mut self, chip: &FilterChip) {
397        match chip {
398            FilterChip::Rating(_) => self.min_rating = None,
399            FilterChip::Label(l) => self.labels.retain(|x| x != l),
400            FilterChip::Flag(f) => self.flags.retain(|x| x != f),
401            FilterChip::Tag(t) => self.tags.retain(|x| x != t),
402            FilterChip::Dates { .. } => {
403                self.from = None;
404                self.to = None;
405            }
406        }
407    }
408
409    /// Whether an image passes.
410    pub fn matches(&self, c: &Candidate<'_>) -> bool {
411        let words_ok = split_terms(&self.text).into_iter().all(|w| {
412            let w = read_value(w).to_lowercase();
413            c.name.to_lowercase().contains(&w)
414                || c.tags.iter().any(|t| t.to_lowercase().contains(&w))
415        });
416        let rating_ok = self.min_rating.is_none_or(|r| c.marks.rating >= r);
417        let labels_ok =
418            self.labels.is_empty() || self.labels.iter().any(|l| c.marks.labels.has(*l));
419        let flags_ok = self.flags.is_empty() || self.flags.contains(&c.marks.flag);
420        let tags_ok = self
421            .tags
422            .iter()
423            .all(|t| c.tags.iter().any(|x| x.eq_ignore_ascii_case(t)));
424        let from_ok = self
425            .from
426            .as_deref()
427            .is_none_or(|f| c.date.is_some_and(|d| d >= f));
428        let to_ok = self
429            .to
430            .as_deref()
431            .is_none_or(|t| c.date.is_some_and(|d| d <= t));
432        words_ok && rating_ok && labels_ok && flags_ok && tags_ok && from_ok && to_ok
433    }
434}
435
436impl FilterChip {
437    /// What the chip shows (translated).
438    pub fn title(&self, ctx: &egui::Context) -> String {
439        match self {
440            FilterChip::Rating(r) => tr_with(ctx, &s::FILTER_RATING, &[("rating", (*r).into())]),
441            FilterChip::Label(l) => tr_args(ctx, &s::FILTER_LABEL, &[("label", &l.title(ctx))]),
442            FilterChip::Flag(f) => tr_args(ctx, &s::FILTER_FLAG, &[("flag", &f.title(ctx))]),
443            FilterChip::Tag(t) => tr_args(ctx, &s::FILTER_TAG, &[("tag", t)]),
444            FilterChip::Dates { from, to } => match (from, to) {
445                (Some(f), Some(t)) => tr_args(ctx, &s::FILTER_DATES, &[("from", f), ("to", t)]),
446                (Some(f), None) => tr_args(ctx, &s::FILTER_FROM, &[("from", f)]),
447                (None, Some(t)) => tr_args(ctx, &s::FILTER_TO, &[("to", t)]),
448                (None, None) => String::new(),
449            },
450        }
451    }
452}
453
454/// A suggestion the application offers under the field
455/// ([`SearchField::suggestions`]).
456#[derive(Clone, Debug, PartialEq, Eq)]
457#[non_exhaustive]
458pub struct Suggestion {
459    /// What the row shows, and its accessible name.
460    pub label: String,
461    /// What kind of suggestion it is (a key, a value, a recent search),
462    /// shown muted beside the label; empty for none.
463    pub kind: String,
464    /// The field's whole text once the suggestion is taken.
465    pub insert: String,
466}
467
468impl Suggestion {
469    /// A row showing `label` that sets the field's text to `insert`.
470    pub fn new(label: impl Into<String>, insert: impl Into<String>) -> Self {
471        Self {
472            label: label.into(),
473            kind: String::new(),
474            insert: insert.into(),
475        }
476    }
477
478    /// Its kind, shown muted beside the label.
479    pub fn kind(mut self, kind: impl Into<String>) -> Self {
480        self.kind = kind.into();
481        self
482    }
483}
484
485/// A chip the application draws in the field ([`SearchField::chips`]):
486/// a part of its own reading of the text, in words.
487#[derive(Clone, Debug, PartialEq, Eq)]
488#[non_exhaustive]
489pub struct AppChip {
490    /// The application's id for it, given back when it is removed.
491    pub id: String,
492    /// What the chip shows.
493    pub words: String,
494    /// The part of the search text it stands for (`camera:R5`), empty
495    /// for none ([`Self::term`]).
496    pub term: String,
497}
498
499impl AppChip {
500    pub fn new(id: impl Into<String>, words: impl Into<String>) -> Self {
501        Self {
502            id: id.into(),
503            words: words.into(),
504            term: String::new(),
505        }
506    }
507
508    /// The part of the search text the chip stands for, in the
509    /// application's grammar: with [`SearchField::whole_text`], the
510    /// filter's text is the chips' terms, in order, then the text typed.
511    /// So the `library.filter` step, its hooks and the filter a command
512    /// reads see the whole search, not only what is typed.
513    pub fn term(mut self, term: impl Into<String>) -> Self {
514        self.term = term.into();
515        self
516    }
517}
518
519/// What the application hooks did in a pass
520/// ([`SearchState::take_events`]).
521#[derive(Clone, Debug, PartialEq, Eq)]
522#[non_exhaustive]
523pub enum SearchEvent {
524    /// The suggestion at this index was taken: the text is now its
525    /// `insert`.
526    Picked(usize),
527    /// The application chip with this id was asked away (its remove
528    /// button, Backspace twice or Ctrl+Backspace in the empty field): the
529    /// application drops it from its text.
530    ChipRemoved(String),
531    /// Escape closed the suggestion list.
532    ListClosed,
533    /// Escape cleared the text typed (the list already closed).
534    Cleared,
535    /// Escape in the empty field, the list closed: the field let go of the
536    /// keyboard (back to the grid).
537    Left,
538    /// The filter was set whole, by a command (`library.filter`) or by a
539    /// hook redirecting or refusing a change: its text, the chips' terms
540    /// included, is now the text typed. The application's chips no
541    /// longer stand for anything: it drops them (or makes them again from
542    /// the text).
543    FilterSet,
544}
545
546/// A search field's state between passes: the chips, the text typed,
547/// the filter last given.
548#[derive(Clone, Debug, Default)]
549pub struct SearchState {
550    chips: Filter,
551    text: String,
552    last: Filter,
553    /// The suggestion list is open.
554    list_open: bool,
555    /// The suggestion highlighted.
556    highlight: Option<usize>,
557    /// The pointer is over the suggestion list.
558    list_hovered: bool,
559    /// The application chip Backspace selected (a second press removes it).
560    chip_selected: Option<usize>,
561    /// The text had the keyboard at the end of the last pass.
562    had_focus: bool,
563    events: Vec<SearchEvent>,
564}
565
566impl SearchState {
567    pub fn new() -> Self {
568        Self::default()
569    }
570
571    /// The filter in force (the chips and the text typed).
572    pub fn filter(&self) -> &Filter {
573        &self.last
574    }
575
576    /// The text typed.
577    pub fn text(&self) -> &str {
578        &self.text
579    }
580
581    /// Sets the text typed (the application rewriting it, a chip of its
582    /// own removed). The filter follows at the next pass.
583    pub fn set_text(&mut self, text: impl Into<String>) {
584        self.text = text.into();
585    }
586
587    /// The suggestion list is open (shown while the field has the keyboard
588    /// and the application gives suggestions).
589    pub fn list_open(&self) -> bool {
590        self.list_open
591    }
592
593    /// The suggestion highlighted, by index.
594    pub fn highlight(&self) -> Option<usize> {
595        self.highlight
596    }
597
598    /// What the application hooks did since the last call: suggestions
599    /// taken, application chips removed, the Escape sequence.
600    pub fn take_events(&mut self) -> Vec<SearchEvent> {
601        std::mem::take(&mut self.events)
602    }
603
604    /// Sets the filter without running a step (its criteria as chips,
605    /// its text typed).
606    pub fn set_filter(&mut self, filter: Filter) {
607        self.text = filter.text.clone();
608        self.chips = Filter {
609            text: String::new(),
610            ..filter.clone()
611        };
612        self.last = filter;
613    }
614
615    fn effective(&self, whole_text: bool, app_chips: &[AppChip]) -> Filter {
616        if whole_text {
617            let text = app_chips
618                .iter()
619                .map(|c| c.term.trim())
620                .chain(Some(self.text.trim()))
621                .filter(|t| !t.is_empty())
622                .collect::<Vec<_>>()
623                .join(" ");
624            return self.chips.merged(&Filter {
625                text,
626                ..Filter::default()
627            });
628        }
629        self.chips.merged(&Filter::parse(&self.text))
630    }
631}
632
633/// What [`SearchField::show`] returns.
634#[derive(Debug)]
635pub struct SearchOutput {
636    /// The text field.
637    pub response: Response,
638    /// The filter, when it changed this pass.
639    pub changed: Option<Filter>,
640    /// Why a change was refused (a before-hook on `library.filter`).
641    pub vetoed: Option<String>,
642}
643
644/// The search field.
645#[derive(Debug)]
646#[must_use = "show it with `show`"]
647pub struct SearchField<'a> {
648    library: String,
649    app: Option<&'a AppHandle>,
650    width: Option<f32>,
651    label: Option<String>,
652    whole_text: bool,
653    suggestions: Option<&'a [Suggestion]>,
654    app_chips: &'a [AppChip],
655}
656
657impl<'a> SearchField<'a> {
658    /// The search field of library `library` (its name in the
659    /// `library.filter` step and in commands).
660    pub fn new(library: impl Into<String>) -> Self {
661        Self {
662            library: library.into(),
663            app: None,
664            width: None,
665            label: None,
666            whole_text: false,
667            suggestions: None,
668            app_chips: &[],
669        }
670    }
671
672    /// The application's suggestions for the text typed, given each pass
673    /// (meant with [`Self::whole_text`]). They show in a list under the
674    /// field once something is typed, or on Down: Up and Down move the
675    /// highlight, Enter or a click takes the highlighted one (the text
676    /// becomes its [`Suggestion::insert`], [`SearchEvent::Picked`]).
677    /// Escape closes the list, then clears the text, then leaves the
678    /// field, each reported ([`SearchState::take_events`]); the field
679    /// keeps the keyboard until the last step, the focus plugin installed
680    /// (an application's window) or not.
681    pub fn suggestions(mut self, suggestions: &'a [Suggestion]) -> Self {
682        self.suggestions = Some(suggestions);
683        self
684    }
685
686    /// The application's chips, drawn in the field after the field's own
687    /// (meant with [`Self::whole_text`]: the application's reading of the
688    /// text, in words). Each has its remove button; in the empty field,
689    /// Backspace selects the last one and removes it at a second press,
690    /// Ctrl+Backspace removes it at once. A removal is reported
691    /// ([`SearchEvent::ChipRemoved`]): the application drops the chip
692    /// from its text.
693    pub fn chips(mut self, chips: &'a [AppChip]) -> Self {
694        self.app_chips = chips;
695        self
696    }
697
698    /// The application reads the text typed with its own grammar: the
699    /// text is never split into this field's criteria ([`Filter::parse`]),
700    /// Enter makes no chip of it, and the filter's `text` is the text as
701    /// typed (trimmed). The chips are only those picked from the "+" menu
702    /// or set by the application. Off by default.
703    pub fn whole_text(mut self, whole: bool) -> Self {
704        self.whole_text = whole;
705        self
706    }
707
708    /// Runs its changes as steps of this application, and takes the
709    /// `library.filter` command.
710    #[cfg(feature = "api")]
711    pub fn app(mut self, app: &'a AppHandle) -> Self {
712        self.app = Some(app);
713        self
714    }
715
716    /// The text field's width.
717    pub fn width(mut self, width: f32) -> Self {
718        self.width = Some(width);
719        self
720    }
721
722    /// Its accessible name and hint ("Search" by default).
723    pub fn label(mut self, label: impl Into<String>) -> Self {
724        self.label = Some(label.into());
725        self
726    }
727
728    pub fn show(self, ui: &mut Ui, state: &mut SearchState) -> SearchOutput {
729        let t = Tokens::of(ui.ctx());
730        let ctx = ui.ctx().clone();
731        let text_id = egui::Id::unique(("egui_pop_views::search", &self.library));
732        let label = self.label.clone().unwrap_or_else(|| tr(&ctx, &s::SEARCH));
733        let registry = lib::registry(self.app);
734        let mut proposed: Option<Filter> = None;
735        if let Some(reg) = &registry
736            && let Some(f) = reg.take_filter(&self.library)
737            && let Ok(f) = lib::parse::<Filter>(&f, "filter")
738        {
739            state.chips = Filter {
740                text: String::new(),
741                ..f.clone()
742            };
743            state.text = f.text.clone();
744            if !self.app_chips.is_empty() {
745                state.events.push(SearchEvent::FilterSet);
746            }
747            proposed = Some(f);
748        }
749        let focused = ui.memory(|m| m.has_focus(text_id));
750        let rows = self.suggestions.unwrap_or(&[]);
751        if state.highlight.is_some_and(|h| h >= rows.len()) {
752            state.highlight = None;
753        }
754        if state
755            .chip_selected
756            .is_some_and(|c| c >= self.app_chips.len())
757        {
758            state.chip_selected = None;
759        }
760        let mut picked: Option<usize> = None;
761        // egui takes the focus off on Escape before the field is drawn:
762        // the field that had it last pass still answers that Escape.
763        let escaped = self.suggestions.is_some()
764            && !focused
765            && state.had_focus
766            && ui.input(|i| i.key_pressed(EKey::Escape));
767        // The focus plugin took the press that left the field: the last
768        // step of the sequence, done ([`egui_pop_core::focus::escape_left`]).
769        if self.suggestions.is_some()
770            && !focused
771            && state.had_focus
772            && egui_pop_core::focus::escape_left(&ctx, text_id)
773        {
774            state.list_open = false;
775            state.highlight = None;
776            state.events.push(SearchEvent::Left);
777        }
778        if (focused || escaped) && self.suggestions.is_some() {
779            let shown = state.list_open && !rows.is_empty();
780            let (down, up, escape) = ui.input_mut(|i| {
781                (
782                    !rows.is_empty() && i.consume_key(Modifiers::NONE, EKey::ArrowDown),
783                    shown && i.consume_key(Modifiers::NONE, EKey::ArrowUp),
784                    i.consume_key(Modifiers::NONE, EKey::Escape) || escaped,
785                )
786            });
787            let n = rows.len();
788            if down {
789                state.highlight = Some(match (shown, state.highlight) {
790                    (true, Some(h)) => (h + 1) % n,
791                    _ => 0,
792                });
793                state.list_open = true;
794            }
795            if up {
796                state.highlight = Some(match state.highlight {
797                    Some(h) => (h + n - 1) % n,
798                    None => n - 1,
799                });
800            }
801            if escape {
802                // The field keeps the focus until the last step.
803                ui.memory_mut(|m| m.request_focus(text_id));
804                if shown {
805                    state.list_open = false;
806                    state.highlight = None;
807                    state.events.push(SearchEvent::ListClosed);
808                } else if !state.text.is_empty() {
809                    state.text.clear();
810                    state.events.push(SearchEvent::Cleared);
811                } else {
812                    ui.memory_mut(|m| m.surrender_focus(text_id));
813                    state.events.push(SearchEvent::Left);
814                }
815            }
816            if shown
817                && let Some(h) = state.highlight
818                && ui.input_mut(|i| i.consume_key(Modifiers::NONE, EKey::Enter))
819            {
820                picked = Some(h);
821            }
822        }
823        if focused && !self.app_chips.is_empty() && state.text.is_empty() {
824            let (now, back) = ui.input_mut(|i| {
825                (
826                    i.consume_key(Modifiers::COMMAND, EKey::Backspace),
827                    i.consume_key(Modifiers::NONE, EKey::Backspace),
828                )
829            });
830            let last = self.app_chips.len() - 1;
831            if now || (back && state.chip_selected == Some(last)) {
832                state.chip_selected = None;
833                state
834                    .events
835                    .push(SearchEvent::ChipRemoved(self.app_chips[last].id.clone()));
836            } else if back {
837                state.chip_selected = Some(last);
838            }
839        }
840        if let Some(k) = picked {
841            take_suggestion(ui.ctx(), text_id, state, rows, k);
842        }
843        if focused {
844            let (enter, back) = ui.input_mut(|i| {
845                (
846                    i.consume_key(Modifiers::NONE, EKey::Enter),
847                    state.text.is_empty() && i.consume_key(Modifiers::NONE, EKey::Backspace),
848                )
849            });
850            if enter && !self.whole_text {
851                // Typed criteria become chips.
852                let typed = Filter::parse(&state.text);
853                state.text = typed.text.clone();
854                state.chips = state.chips.merged(&Filter {
855                    text: String::new(),
856                    ..typed
857                });
858            }
859            if back && let Some(last) = state.chips.chips().last() {
860                state.chips.remove(last);
861            }
862        }
863        // The field's box, its ring while the text has the keyboard.
864        let kit = egui_pop_core::kit::Kit::of(ui.ctx());
865        let field_state =
866            egui_pop_core::kit::State::REST.with(egui_pop_core::kit::State::FOCUS, focused);
867        let inner = kit
868            .search_field
869            .show(ui, field_state, egui::epaint::Shadow::NONE, |ui| {
870                ui.horizontal_wrapped(|ui| {
871                    let side = t.size.icon_inline;
872                    let (r, _) =
873                        ui.allocate_exact_size(egui::vec2(side, side), egui::Sense::hover());
874                    egui_pop_core::icon::Icon::Search.paint(ui.painter(), r, t.text.muted);
875                    for chip in state.chips.chips() {
876                        let title = chip.title(&ctx);
877                        let name = tr_args(&ctx, &s::REMOVE, &[("item", &title)]);
878                        if TagChip::new(title)
879                            .removable(true)
880                            .remove_label(name)
881                            .show(ui)
882                            .removed
883                        {
884                            state.chips.remove(&chip);
885                        }
886                    }
887                    for (k, chip) in self.app_chips.iter().enumerate() {
888                        let name = tr_args(&ctx, &s::REMOVE, &[("item", &chip.words)]);
889                        if TagChip::new(chip.words.clone())
890                            .removable(true)
891                            .selected(state.chip_selected == Some(k))
892                            .remove_label(name)
893                            .show(ui)
894                            .removed
895                        {
896                            state.chip_selected = None;
897                            state.events.push(SearchEvent::ChipRemoved(chip.id.clone()));
898                        }
899                    }
900                    let before = state.text.clone();
901                    let field = ui.add(
902                        TextEdit::singleline(&mut state.text)
903                            .id(text_id)
904                            .frame(egui::Frame::NONE)
905                            .hint_text(label.clone())
906                            .desired_width(self.width.unwrap_or(180.0)),
907                    );
908                    egui_pop_core::a11y::name(&field, Role::TextInput, &label);
909                    if state.text != before && self.suggestions.is_some() {
910                        // Typing opens the list on what the application
911                        // offers for the new text (at the next pass).
912                        state.list_open = true;
913                        state.highlight = None;
914                        state.chip_selected = None;
915                        ui.ctx().request_repaint();
916                    }
917                    // Each button's name is its tooltip too.
918                    let add = ui.menu_button("+", |ui| add_menu(ui, &mut state.chips));
919                    egui_pop_core::overlay::follow_menu(&add.response, "add filter menu");
920                    let add_name = tr(&ctx, &s::ADD_FILTER);
921                    egui_pop_core::a11y::name(&add.response, Role::Button, &add_name);
922                    let _ = add.response.tip(add_name);
923                    if !state.chips.is_empty() || !state.text.is_empty() {
924                        let clear = ui.button("×");
925                        let clear_name = tr(&ctx, &s::CLEAR_FILTERS);
926                        egui_pop_core::a11y::name(&clear, Role::Button, &clear_name);
927                        let clear = clear.tip(clear_name);
928                        if clear.clicked() {
929                            state.chips = Filter::default();
930                            state.text.clear();
931                        }
932                    }
933                    field
934                })
935                .inner
936            });
937        let response = inner.inner;
938        state.had_focus = ui.memory(|m| m.has_focus(text_id));
939        if self.suggestions.is_some()
940            && state.had_focus
941            && ((state.list_open && !rows.is_empty()) || !state.text.is_empty())
942        {
943            // Escape has a step of the sequence to do: the focus plugin
944            // lets it through to the field instead of making the field let
945            // go of the keyboard, and the key dispatcher leaves it alone.
946            egui_pop_core::focus::escape_passes(&ctx, text_id);
947            egui_pop_core::focus::claim_keyboard(&ctx, text_id);
948        }
949        if self.suggestions.is_some() {
950            let box_rect = inner.response.rect;
951            suggestion_list(ui, text_id, box_rect, state, rows);
952        }
953        let now = proposed.unwrap_or_else(|| state.effective(self.whole_text, self.app_chips));
954        let mut changed = None;
955        let mut vetoed = None;
956        if now != state.last {
957            let args = json!({ "library": self.library, "filter": now });
958            match lib::report(self.app, &lib::LIBRARY_FILTER, args) {
959                Ok(ran) => {
960                    let done: Filter =
961                        lib::parse(&ran["filter"], "filter").unwrap_or_else(|_| now.clone());
962                    if done != now {
963                        // A hook redirected it: its whole text is typed.
964                        state.set_filter(done.clone());
965                        if !self.app_chips.is_empty() {
966                            state.events.push(SearchEvent::FilterSet);
967                        }
968                    }
969                    state.last = done.clone();
970                    changed = Some(done);
971                }
972                Err(reason) => {
973                    // Back to the filter in force.
974                    let last = state.last.clone();
975                    state.set_filter(last);
976                    if !self.app_chips.is_empty() {
977                        state.events.push(SearchEvent::FilterSet);
978                    }
979                    vetoed = Some(reason);
980                }
981            }
982            if let Some(reg) = &registry {
983                reg.publish_filter(
984                    &self.library,
985                    serde_json::to_value(&state.last).unwrap_or(Json::Null),
986                );
987            }
988            ui.ctx().request_repaint();
989        } else if let Some(reg) = &registry {
990            reg.touch(&self.library);
991        }
992        SearchOutput {
993            response,
994            changed,
995            vetoed,
996        }
997    }
998}
999
1000/// Takes suggestion `k`: the text becomes its insert, the cursor at its
1001/// end.
1002fn take_suggestion(
1003    ctx: &egui::Context,
1004    text_id: egui::Id,
1005    state: &mut SearchState,
1006    rows: &[Suggestion],
1007    k: usize,
1008) {
1009    let Some(row) = rows.get(k) else {
1010        return;
1011    };
1012    state.text = row.insert.clone();
1013    state.list_open = false;
1014    state.highlight = None;
1015    state.events.push(SearchEvent::Picked(k));
1016    let mut te = egui::text_edit::TextEditState::load(ctx, text_id).unwrap_or_default();
1017    let end = egui::text::CCursor::new(state.text.chars().count());
1018    te.cursor
1019        .set_char_range(Some(egui::text::CCursorRange::one(end)));
1020    te.store(ctx, text_id);
1021    ctx.request_repaint();
1022}
1023
1024/// The application's suggestions under the field's box: a list box of
1025/// options, the highlighted one selected.
1026fn suggestion_list(
1027    ui: &mut Ui,
1028    text_id: egui::Id,
1029    below: egui::Rect,
1030    state: &mut SearchState,
1031    rows: &[Suggestion],
1032) {
1033    let ctx = ui.ctx().clone();
1034    let focused = ctx.memory(|m| m.has_focus(text_id));
1035    if !focused && !state.list_hovered {
1036        state.list_open = false;
1037        state.highlight = None;
1038    }
1039    let list_id = text_id.with("suggestions");
1040    let visible = state.list_open && !rows.is_empty();
1041    let mut hovered = false;
1042    if visible {
1043        let name = tr(&ctx, &s::SUGGESTIONS);
1044        let mut clicked = None;
1045        let area = egui::Area::new(list_id)
1046            .order(egui::Order::Foreground)
1047            .fixed_pos(below.left_bottom())
1048            .show(&ctx, |ui| {
1049                egui::Frame::popup(ui.style()).show(ui, |ui| {
1050                    ui.scope_builder(
1051                        egui::UiBuilder::new()
1052                            .accessibility_role(egui::accesskit::Role::ListBox)
1053                            .accessibility_label(name.clone()),
1054                        |ui| {
1055                            for (k, row) in rows.iter().enumerate() {
1056                                let on = state.highlight == Some(k);
1057                                ui.horizontal(|ui| {
1058                                    let r = egui_pop_core::widgets::selectable_label(
1059                                        ui,
1060                                        on,
1061                                        row.label.as_str(),
1062                                    );
1063                                    let label = row.label.clone();
1064                                    r.widget_info(|| {
1065                                        egui::WidgetInfo::selected(
1066                                            Role::ListBoxOption,
1067                                            true,
1068                                            on,
1069                                            &label,
1070                                        )
1071                                    });
1072                                    if on {
1073                                        r.scroll_to_me(None);
1074                                    }
1075                                    if !row.kind.is_empty() {
1076                                        ui.weak(row.kind.as_str());
1077                                    }
1078                                    if r.clicked() {
1079                                        clicked = Some(k);
1080                                    }
1081                                });
1082                            }
1083                        },
1084                    );
1085                });
1086            });
1087        hovered = area.response.contains_pointer();
1088        if let Some(k) = clicked {
1089            take_suggestion(&ctx, text_id, state, rows, k);
1090            ctx.memory_mut(|m| m.request_focus(text_id));
1091        }
1092    }
1093    state.list_hovered = hovered;
1094    egui_pop_core::overlay::follow_popup(
1095        &ctx,
1096        list_id,
1097        "search suggestions",
1098        state.list_open && !rows.is_empty(),
1099        None,
1100    );
1101}
1102
1103/// The menu adding a criterion.
1104fn add_menu(ui: &mut Ui, chips: &mut Filter) {
1105    let ctx = ui.ctx().clone();
1106    ui.menu_button(tr(&ctx, &s::RATING), |ui| {
1107        for r in 1..=MAX_RATING {
1108            if ui.button(FilterChip::Rating(r).title(&ctx)).clicked() {
1109                chips.min_rating = Some(r);
1110                ui.close();
1111            }
1112        }
1113    });
1114    ui.menu_button(tr(&ctx, &s::LABEL), |ui| {
1115        for l in ColorLabel::ALL {
1116            if ui.button(l.title(&ctx)).clicked() {
1117                if !chips.labels.contains(&l) {
1118                    chips.labels.push(l);
1119                }
1120                ui.close();
1121            }
1122        }
1123    });
1124    ui.menu_button(tr(&ctx, &s::FLAG), |ui| {
1125        for f in Flag::ALL {
1126            if ui.button(f.title(&ctx)).clicked() {
1127                if !chips.flags.contains(&f) {
1128                    chips.flags.push(f);
1129                }
1130                ui.close();
1131            }
1132        }
1133    });
1134}
1135
1136#[cfg(test)]
1137mod tests {
1138    use super::*;
1139    use crate::library::marks::Labels;
1140
1141    #[test]
1142    fn typed_criteria_become_a_structured_filter() {
1143        let f = Filter::parse(
1144            "beach rating>=3 label:red #sea flag:pick date:2024-06-01..2024-06-30 sunset",
1145        );
1146        assert_eq!(f.text, "beach sunset");
1147        assert_eq!(f.min_rating, Some(3));
1148        assert_eq!(f.labels, [ColorLabel::Red]);
1149        assert_eq!(f.flags, [Flag::Pick]);
1150        assert_eq!(f.tags, ["sea"]);
1151        assert_eq!(f.from.as_deref(), Some("2024-06-01"));
1152        assert_eq!(f.to.as_deref(), Some("2024-06-30"));
1153        assert_eq!(f.chips().len(), 5);
1154        // Not criteria: kept as words.
1155        let g = Filter::parse("label:mauve date:soon");
1156        assert_eq!(g.text, "label:mauve date:soon");
1157        let json = serde_json::to_value(&f).unwrap();
1158        assert_eq!(json["labels"], json!(["red"]));
1159        assert_eq!(serde_json::from_value::<Filter>(json).unwrap(), f);
1160        assert_eq!(serde_json::to_value(Filter::default()).unwrap(), json!({}));
1161    }
1162
1163    #[test]
1164    fn a_quoted_value_keeps_its_spaces_and_escapes() {
1165        let f = Filter::parse(r#"beach tag:"New  York" #"say \"hi\"" label:red "two words""#);
1166        assert_eq!(f.tags, ["New  York", r#"say "hi""#]);
1167        assert_eq!(f.labels, [ColorLabel::Red]);
1168        assert_eq!(f.text, r#"beach "two words""#);
1169        // A run of backslashes before a quote is halved; elsewhere kept.
1170        assert_eq!(read_value(r#""C:\Photos\\""#), r"C:\Photos\");
1171        assert_eq!(read_value(r#""a\b""#), r"a\b");
1172        assert_eq!(read_value("bare"), "bare");
1173        assert_eq!(value_text("bare"), "bare");
1174        assert_eq!(value_text("a b"), r#""a b""#);
1175        assert_eq!(value_text(r#"say "hi""#), r#""say \"hi\"""#);
1176        assert_eq!(value_text(r"C:\My Photos\"), r#""C:\My Photos\\""#);
1177        assert_eq!(value_text(r"C:\Photos\"), r"C:\Photos\");
1178        assert_eq!(value_text(""), r#""""#);
1179        // Unquoted input reads as before.
1180        assert_eq!(
1181            split_terms("  beach   rating>=3 #sea "),
1182            ["beach", "rating>=3", "#sea"]
1183        );
1184        assert_eq!(
1185            split_terms(r#"a tag:"x \" y" b"#),
1186            ["a", r#"tag:"x \" y""#, "b"]
1187        );
1188        // A quoted phrase in the words is searched whole.
1189        let tags = vec!["two words here".to_string()];
1190        let c = Candidate {
1191            tags: &tags,
1192            ..Candidate::named("IMG_1.raw")
1193        };
1194        assert!(Filter::parse(r#""words here""#).matches(&c));
1195        assert!(!Filter::parse(r#""here words""#).matches(&c));
1196    }
1197
1198    /// `parse(to_text(f)) == f` over tags made of the characters the
1199    /// grammar treats specially, in every mix (a fixed pseudo-random
1200    /// sequence, so a failure replays).
1201    #[test]
1202    fn to_text_round_trips_through_parse() {
1203        const PARTS: &[&str] = &[
1204            "a", "Z", " ", "  ", "\t", "\"", "\\", "\\\\", "(", ")", "#", ":", "é", "..", "<", "=",
1205            "tag:", "-",
1206        ];
1207        let mut seed = 0x9E37_79B9_7F4A_7C15_u64;
1208        let mut next = move || {
1209            seed ^= seed << 13;
1210            seed ^= seed >> 7;
1211            seed ^= seed << 17;
1212            seed
1213        };
1214        for _ in 0..2000 {
1215            let mut tags = Vec::new();
1216            for _ in 0..(next() % 3 + 1) {
1217                let len = next() % 6 + 1;
1218                let tag: String = (0..len)
1219                    .map(|_| PARTS[(next() % PARTS.len() as u64) as usize])
1220                    .collect();
1221                if !tag.is_empty() && !tags.contains(&tag) {
1222                    tags.push(tag);
1223                }
1224            }
1225            let f = Filter {
1226                text: r#"beach "two  words""#.into(),
1227                min_rating: Some(3),
1228                labels: vec![ColorLabel::Blue],
1229                flags: vec![Flag::Reject],
1230                tags,
1231                from: Some("2024-06-01".into()),
1232                to: None,
1233            };
1234            let text = f.to_text();
1235            assert_eq!(Filter::parse(&text), f, "{text}");
1236            assert_eq!(Filter::parse(&text).to_text(), text);
1237        }
1238        assert_eq!(Filter::default().to_text(), "");
1239        let f = Filter::parse("date:2024-06-01..2024-06-30 to:2024-07-01");
1240        assert_eq!(Filter::parse(&f.to_text()), f);
1241    }
1242
1243    #[test]
1244    fn a_filter_matches_marks_tags_and_days() {
1245        let tags = vec!["Sea".to_string(), "summer".to_string()];
1246        let c = Candidate {
1247            name: "IMG_0042.raw",
1248            marks: Marks {
1249                rating: 4,
1250                labels: Labels::NONE.with(ColorLabel::Red, true),
1251                flag: Flag::Pick,
1252            },
1253            tags: &tags,
1254            date: Some("2024-06-12"),
1255        };
1256        assert!(
1257            Filter::parse("0042 rating>=4 label:red flag:pick #sea from:2024-06-01").matches(&c)
1258        );
1259        assert!(Filter::parse("summer").matches(&c), "words search tags");
1260        assert!(!Filter::parse("rating:5").matches(&c));
1261        assert!(!Filter::parse("label:blue").matches(&c));
1262        assert!(!Filter::parse("to:2024-06-11").matches(&c));
1263        let mut f = Filter::parse("label:red label:blue");
1264        assert!(f.matches(&c), "any label");
1265        f.remove(&FilterChip::Label(ColorLabel::Red));
1266        assert!(!f.matches(&c));
1267    }
1268}