1use 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#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
44#[serde(default)]
45pub struct Filter {
46 #[serde(skip_serializing_if = "String::is_empty")]
48 pub text: String,
49 #[serde(skip_serializing_if = "Option::is_none")]
51 pub min_rating: Option<u8>,
52 #[serde(skip_serializing_if = "Vec::is_empty")]
54 pub labels: Vec<ColorLabel>,
55 #[serde(skip_serializing_if = "Vec::is_empty")]
57 pub flags: Vec<Flag>,
58 #[serde(skip_serializing_if = "Vec::is_empty")]
60 pub tags: Vec<String>,
61 #[serde(skip_serializing_if = "Option::is_none")]
63 pub from: Option<String>,
64 #[serde(skip_serializing_if = "Option::is_none")]
66 pub to: Option<String>,
67}
68
69#[derive(Clone, Debug, PartialEq, Eq)]
71pub enum FilterChip {
72 Rating(u8),
73 Label(ColorLabel),
74 Flag(Flag),
75 Tag(String),
76 Dates {
78 from: Option<String>,
79 to: Option<String>,
80 },
81}
82
83#[derive(Clone, Copy, Debug, Default)]
85pub struct Candidate<'a> {
86 pub name: &'a str,
87 pub marks: Marks,
88 pub tags: &'a [String],
89 pub date: Option<&'a str>,
91}
92
93impl<'a> Candidate<'a> {
94 pub fn named(name: &'a str) -> Candidate<'a> {
96 Candidate {
97 name,
98 ..Candidate::default()
99 }
100 }
101}
102
103pub 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
114pub 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
148pub 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
197pub 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 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 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 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 #[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 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 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 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 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#[derive(Clone, Debug, PartialEq, Eq)]
457#[non_exhaustive]
458pub struct Suggestion {
459 pub label: String,
461 pub kind: String,
464 pub insert: String,
466}
467
468impl Suggestion {
469 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 pub fn kind(mut self, kind: impl Into<String>) -> Self {
480 self.kind = kind.into();
481 self
482 }
483}
484
485#[derive(Clone, Debug, PartialEq, Eq)]
488#[non_exhaustive]
489pub struct AppChip {
490 pub id: String,
492 pub words: String,
494 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 pub fn term(mut self, term: impl Into<String>) -> Self {
514 self.term = term.into();
515 self
516 }
517}
518
519#[derive(Clone, Debug, PartialEq, Eq)]
522#[non_exhaustive]
523pub enum SearchEvent {
524 Picked(usize),
527 ChipRemoved(String),
531 ListClosed,
533 Cleared,
535 Left,
538 FilterSet,
544}
545
546#[derive(Clone, Debug, Default)]
549pub struct SearchState {
550 chips: Filter,
551 text: String,
552 last: Filter,
553 list_open: bool,
555 highlight: Option<usize>,
557 list_hovered: bool,
559 chip_selected: Option<usize>,
561 had_focus: bool,
563 events: Vec<SearchEvent>,
564}
565
566impl SearchState {
567 pub fn new() -> Self {
568 Self::default()
569 }
570
571 pub fn filter(&self) -> &Filter {
573 &self.last
574 }
575
576 pub fn text(&self) -> &str {
578 &self.text
579 }
580
581 pub fn set_text(&mut self, text: impl Into<String>) {
584 self.text = text.into();
585 }
586
587 pub fn list_open(&self) -> bool {
590 self.list_open
591 }
592
593 pub fn highlight(&self) -> Option<usize> {
595 self.highlight
596 }
597
598 pub fn take_events(&mut self) -> Vec<SearchEvent> {
601 std::mem::take(&mut self.events)
602 }
603
604 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#[derive(Debug)]
635pub struct SearchOutput {
636 pub response: Response,
638 pub changed: Option<Filter>,
640 pub vetoed: Option<String>,
642}
643
644#[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 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 pub fn suggestions(mut self, suggestions: &'a [Suggestion]) -> Self {
682 self.suggestions = Some(suggestions);
683 self
684 }
685
686 pub fn chips(mut self, chips: &'a [AppChip]) -> Self {
694 self.app_chips = chips;
695 self
696 }
697
698 pub fn whole_text(mut self, whole: bool) -> Self {
704 self.whole_text = whole;
705 self
706 }
707
708 #[cfg(feature = "api")]
711 pub fn app(mut self, app: &'a AppHandle) -> Self {
712 self.app = Some(app);
713 self
714 }
715
716 pub fn width(mut self, width: f32) -> Self {
718 self.width = Some(width);
719 self
720 }
721
722 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) = ®istry
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 let escaped = self.suggestions.is_some()
764 && !focused
765 && state.had_focus
766 && ui.input(|i| i.key_pressed(EKey::Escape));
767 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 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 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 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 state.list_open = true;
913 state.highlight = None;
914 state.chip_selected = None;
915 ui.ctx().request_repaint();
916 }
917 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 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 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 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) = ®istry {
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) = ®istry {
990 reg.touch(&self.library);
991 }
992 SearchOutput {
993 response,
994 changed,
995 vetoed,
996 }
997 }
998}
999
1000fn 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
1024fn 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
1103fn 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 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 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 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 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 #[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}