diff --git a/crates/ui-egui/src/canvas/find.rs b/crates/ui-egui/src/canvas/find.rs index 5a7081cfad..c46460df40 100644 --- a/crates/ui-egui/src/canvas/find.rs +++ b/crates/ui-egui/src/canvas/find.rs @@ -1,80 +1,38 @@ -use super::{Align2, Color32, CornerRadius, DocView, Range, Rect, Stroke, Tokens, ViewAction, icons, theme, vec2, widgets}; +// PLAN: the `craft` dependency in crates/ui-egui/Cargo.toml needs the `text` feature for `craft::text` (owner: pdf-hub-w1). +use craft::behavior::kurbo::Point; +use craft::behavior::overlay::Align; +use craft::pages::ui::TextMark; +use craft::text::find::{FindMatches, FindOptions}; +use craft::text::ui::find::{FindBar, FindBarState, FindRequest}; +use craft::ui::canvas_controls::TaskBar; +use craft::ui::contract::Props as _; + +use super::{DocView, Rect, ViewAction}; /// The find bar (⌘F): query, matches across the document, current match. #[derive(Default)] pub struct Find { pub query: String, - /// (page, glyph range) in document order. - pub matches: Vec<(usize, Range)>, - pub current: Option, - /// The page a search started from while its match is picked automatically: a text layer - /// that arrives out of order can still supply an earlier match, and the automatic choice - /// follows this page. Cleared when the user picks a match or moves the view themselves. - pub auto_from: Option, - /// The page the automatic choice last put the view on (the search's starting page until it - /// chose anything). Compared with the viewed page, it tells an automatic scroll from one - /// the reader made themselves; `None` with `auto_from` once the choice is the user's. - pub auto_page: Option, - /// The reader ended automatic following (by navigating, scrolling, or picking a match). - /// This is distinct from a search that never followed: a late match must be listed without - /// being revealed by scrolling, even when the reader moved before the first match arrived. - pub follow_ended: bool, - pub focus: bool, - pub case_query: String, /// Find options (Acrobat's: case-sensitive, whole words only). - pub case_sensitive: bool, - pub whole_words: bool, + pub options: FindOptions, + /// The matches in document order and the current one; it owns following the search's start page. + pub matches: FindMatches, + /// Whether the bar was just asked for (⌘F, Advanced Search), so its field takes the keyboard. + pub bar: FindBarState, + /// The query the matches belong to. + pub case_query: String, /// Shown in the Search panel (Advanced Search) instead of the find bar. pub in_panel: bool, /// Find and replace (in Edit text mode): the Replace row shows, with what replaces a match. pub replacing: bool, pub replacement: String, - /// Focus the Replace field on the next frame. - pub focus_replace: bool, -} - -/// What a text layer arriving after a search began may do with the automatic choice. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum Follow { - /// The reader has not moved the view since the automatic choice: it may follow `from`. - Active(usize), - /// The reader navigated, scrolled or picked a match, so no automatic choice may reveal. - Ended, - /// No automatic choice is being followed (the search has not started, or the reader chose). - Never, } impl Find { - /// The first match at or after `page`, or the first match when none follows (the search - /// wraps round the document). - pub(super) fn first_at_or_after(&self, page: usize) -> Option { - self.matches.iter().position(|(p, _)| *p >= page).or_else(|| (!self.matches.is_empty()).then_some(0)) - } - - /// How a text layer arriving now relates to the automatic choice. Once the reader has moved - /// the view (page box, Pages panel, outline, view history or any scrolling), automatic - /// following ends: a later layer must not pull them back to an anchor-derived match. - /// `Ended` is deliberately distinct from `Never`, so a first match arriving after that move - /// is not revealed by a flash meant only for a search that is still following. - pub(super) fn follow_page(&mut self, viewed: usize) -> Follow { - if self.follow_ended { - return Follow::Ended; - } - match (self.auto_from, self.auto_page) { - (Some(from), Some(page)) if page == viewed => Follow::Active(from), - (Some(_), _) | (_, Some(_)) => { - self.stop_following(); - Follow::Ended - } - (None, None) => Follow::Never, - } - } - - /// Ends automatic following: the selected match is now the user's choice to keep. - fn stop_following(&mut self) { - self.auto_from = None; - self.auto_page = None; - self.follow_ended = true; + /// The matches as highlights for the page view's text marks, the current one stronger. + pub fn marks(&self) -> Vec { + let current = self.matches.current(); + self.matches.matches().iter().enumerate().map(|(i, m)| TextMark::new(m.page, m.range.clone(), current == Some(i))).collect() } } @@ -82,7 +40,7 @@ impl DocView { /// Open the find bar (or focus it if already open). pub fn open_find(&mut self) { let f = self.find.get_or_insert_with(Find::default); - f.focus = true; + f.bar.open(); } /// Open the find bar with its Replace row (Edit text mode shows it): the Find field takes the @@ -91,46 +49,31 @@ impl DocView { let f = self.find.get_or_insert_with(Find::default); f.in_panel = false; f.replacing = true; - if f.query.trim().is_empty() { - f.focus = true; - } else { - f.focus_replace = true; - } + f.bar.open_replace(); } /// Re-run the search on all pages whose text is known (after the query changed). pub fn rerun_find(&mut self) { + let current = self.view.current; let Some(f) = self.find.as_mut() else { return }; f.case_query = f.query.clone(); - f.matches.clear(); - f.current = None; // Refining the query keeps the page the reader started searching from, even when an - // automatic choice has already scrolled them to a match. Only a view the reader moved - // themselves re-anchors the search on the page now shown. - let from = match (f.auto_from, f.auto_page) { - (Some(from), Some(page)) if !f.follow_ended && page == self.current => from, - _ => self.current, - }; - f.auto_from = Some(from); - f.auto_page = Some(self.current); - f.follow_ended = false; + // automatic choice has already scrolled them to a match. + let from = f.matches.from().unwrap_or(current); + f.matches = FindMatches::new(from); if f.case_query.trim().is_empty() { return; } let mut pages: Vec = self.texts.keys().copied().collect(); pages.sort(); + let mut reveal = false; for &p in &pages { if let Some(text) = self.texts.get(&p) { - f.matches.extend(text.find_opts(&f.case_query, f.case_sensitive, f.whole_words).into_iter().map(|r| (p, r))); + reveal |= f.matches.set_page(p, text.find_opts(&f.case_query, f.options.match_case, f.options.whole_word)); } } - f.matches.sort_by_key(|(p, r)| (*p, r.start)); - // First match at or after the page the search started from. - if let Some(i) = f.first_at_or_after(from) - && let Some(&(p, _)) = f.matches.get(i) - { - f.current = Some(i); - f.auto_page = Some(p); + let target = f.matches.current_match().map(|m| m.page).filter(|_| reveal); + if let Some(p) = target { self.flash_match(p); } } @@ -140,269 +83,129 @@ impl DocView { if f.case_query.trim().is_empty() { return; } - let previous = f.current.and_then(|c| f.matches.get(c).cloned()); - // An automatic choice follows the page it was anchored on, so a page whose text - // arrives late can still supply an earlier match. Once the reader has moved the view, - // this arrival must not pull them back; the choice then becomes theirs to keep. - let follow = f.follow_page(self.current); - f.matches.retain(|(p, _)| *p != page); - f.matches.extend(text.find_opts(&f.case_query, f.case_sensitive, f.whole_words).into_iter().map(|r| (page, r))); - f.matches.sort_by_key(|(p, r)| (*p, r.start)); - if let Follow::Active(from) = follow { - f.current = f.first_at_or_after(from); - let selected = f.current.and_then(|i| f.matches.get(i).cloned()); - // Follow a changed automatic choice; the view is still where the last one left it. - if selected != previous - && let Some((p, _)) = selected - { - f.auto_page = Some(p); - self.flash_match(p); - } - return; + let reveal = f.matches.set_page(page, text.find_opts(&f.case_query, f.options.match_case, f.options.whole_word)); + let target = f.matches.current_match().map(|m| m.page).filter(|_| reveal); + if let Some(p) = target { + self.flash_match(p); } - // A match the user picked keeps its identity, exactly as before automatic following. - // When it is gone (or none was picked), the first match at or after the viewed page is - // selected for the panel, but the view stays put: `Ended` and `Never` have no automatic - // choice to reveal, and a reader who moved before the first layer arrived must not be - // pulled back by that late match. - let preserved = previous.as_ref().and_then(|k| f.matches.iter().position(|m| m == k)); - f.current = preserved.or_else(|| f.first_at_or_after(self.current)); } /// Go to match `i` (the Search panel's results). pub fn go_to_match(&mut self, i: usize) { let Some(f) = self.find.as_mut() else { return }; - let Some(&(p, _)) = f.matches.get(i) else { return }; - f.current = Some(i); - f.stop_following(); - self.go_to_page(p); - self.goto_point = None; - self.flash_match(p); + if i >= f.matches.len() { + return; + } + f.matches.pick(i); + self.show_current_match(); } /// Move to the next/previous match. pub fn find_step(&mut self, forward: bool) { let Some(f) = self.find.as_mut() else { return }; - if f.matches.is_empty() { + if f.matches.step(!forward).is_none() { return; } - let n = f.matches.len(); - let c = f.current.unwrap_or(0); - let next = if forward { (c + 1) % n } else { (c + n - 1) % n }; - f.current = Some(next); - f.stop_following(); - let p = f.matches[next].0; - // Only explicit search navigation joins history; background refresh uses flash_match alone. + self.show_current_match(); + } + + /// Show the current match, which the matches already chose (the find bar and the Search panel + /// step or pick it). Only explicit search navigation joins history; background refresh uses + /// `flash_match` alone. + pub(super) fn show_current_match(&mut self) { + let Some(p) = self.find.as_ref().and_then(|f| f.matches.current_match()).map(|m| m.page) else { return }; self.go_to_page(p); - self.goto_point = None; self.flash_match(p); } - /// The centre of the current match as a fraction of its displayed page `[x, y]` (0..1 from - /// the top-left corner, after the view rotation, as `goto_point` takes it). - fn match_centre(&self) -> Option<[f32; 2]> { - let f = self.find.as_ref()?; - let (p, r) = f.matches.get(f.current?)?; - let glyphs = self.texts.get(p)?.glyphs.get(r.clone())?; + /// The centre of the current match in page points on its displayed page (from the top-left + /// corner, after the view rotation), where the page view's go-to point takes it. + fn match_centre(&self) -> Option { + let m = self.find.as_ref()?.matches.current_match()?; + let glyphs = self.texts.get(&m.page)?.glyphs.get(m.range.clone())?; let [x0, y0, x1, y1] = glyphs.iter().map(|g| g.rect).reduce(|a, b| [a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])])?; - let &(w, h) = self.page_sizes.get(*p).filter(|(w, h)| *w > 0.0 && *h > 0.0)?; - let (u, v) = ((((x0 + x1) / 2.0) / w).clamp(0.0, 1.0), (((y0 + y1) / 2.0) / h).clamp(0.0, 1.0)); - // Turned clockwise by the view rotation, as `PageInfo::dest_fraction` does. - Some(match self.rotation % 360 { - 90 => [1.0 - v, u], - 180 => [1.0 - u, 1.0 - v], - 270 => [v, 1.0 - u], - _ => [u, v], + let &(w, h) = self.page_sizes.get(m.page).filter(|(w, h)| *w > 0.0 && *h > 0.0)?; + let (w, h) = (f64::from(w), f64::from(h)); + let cx = (f64::from(x0 + x1) / 2.0).clamp(0.0, w); + let cy = (f64::from(y0 + y1) / 2.0).clamp(0.0, h); + // Turned clockwise by the view rotation. + Some(match self.view.rotation % 360 { + 90 => Point::new(h - cy, cx), + 180 => Point::new(w - cx, h - cy), + 270 => Point::new(cy, w - cx), + _ => Point::new(cx, cy), }) } fn flash_match(&mut self, page: usize) { - let frac = self - .find - .as_ref() - .and_then(|f| f.current.and_then(|c| f.matches.get(c))) - .and_then(|(p, r)| self.texts.get(p).and_then(|t| t.glyphs.get(r.start)).map(|g| g.rect[1])) - .zip(self.page_sizes.get(page).map(|&(_, h)| h)) - .map(|(y, h)| ((y - 60.0) / h).clamp(0.0, 1.0)) - .unwrap_or(0.0); - self.goto = Some((page, frac)); - self.find_hold = None; - // Then put the match's centre at the window's centre, as Acrobat does (#3530) and as a - // /FitR destination's rectangle is: a page wider or taller than the window no longer - // leaves it off to one side or near an edge. + // Put the match's centre at the window's centre, as Acrobat does (#3530) and as a /FitR + // destination's rectangle is: a page wider or taller than the window no longer leaves it + // off to one side or near an edge. // Finite only: a hostile page's glyphs can span -inf..inf, and NaN survives `clamp`. - if let Some([fx, fy]) = self.match_centre().filter(|c| c.iter().all(|v| v.is_finite())) { - self.goto_point = Some((page, Some(fx), Some(fy), vec2(self.viewport_w, self.viewport_h) / 2.0)); - // The point alone, both axes in one frame. A pending zoom anchor would hold the old - // place for that frame and put `goto` off to the next, where its page-top offset - // undid the centring; a zoom after the step anchors on the match instead. - self.goto = None; - self.zoom_anchor = None; - self.find_hold = Some((page, fx, fy)); + if let Some(centre) = self.match_centre().filter(|c| c.x.is_finite() && c.y.is_finite()) { + self.view.go_to_point(page, centre, (0.5, 0.5)); + } else { + // The match line's top, centred on that axis alone (a NaN axis keeps its offset). + let top = self + .find + .as_ref() + .and_then(|f| f.matches.current_match()) + .and_then(|m| self.texts.get(&m.page).and_then(|t| t.glyphs.get(m.range.start))) + .map(|g| f64::from(g.rect[1])) + .zip(self.page_sizes.get(page).map(|&(_, h)| f64::from(h))) + .filter(|(y, h)| y.is_finite() && h.is_finite() && *h > 0.0); + match top { + Some((y, h)) => self.view.go_to_point(page, Point::new(f64::NAN, y.clamp(0.0, h)), (0.5, 0.5)), + None => self.view.go_to(page), + } } - self.current = page; - self.reset_coarse_state(); } /// Ends automatic search following after the reader navigated or scrolled the view. A - /// programmatic search flash never comes through here; it sets `goto` and `current` directly - /// so that its own scroll cannot be mistaken for the reader's. + /// programmatic search flash never comes through here, so that its own scroll cannot be + /// mistaken for the reader's. pub(super) fn end_find_following(&mut self) { if let Some(f) = self.find.as_mut() { - f.stop_following(); + f.matches.stop_following(); } } } -/// The id of a pane's find field: one per view, so two find bars open at once do not share an id -/// (and so the focus). -fn find_input_id(key: u64) -> egui::Id { - egui::Id::unique(("find-input", key)) -} - -impl DocView { - /// The id of this view's find field, for what needs to give it the focus or take it away. - pub fn find_input_id(&self) -> egui::Id { - find_input_id(self.pane.key) - } -} - -/// Acrobat-style floating find bar at the top-right of the document area. In Edit text mode -/// (`editing`) it offers a Replace row: Replace changes the highlighted match, Replace all every -/// match, each inside its own paragraph. -pub(super) fn find_bar(view: &mut DocView, pages: usize, area: Rect, editing: bool, ui: &mut egui::Ui, t: &Tokens) { +/// The find bar at the page view's top edge, end-aligned. In Edit text mode (`editing`) it offers a +/// Replace row: Replace changes the highlighted match, Replace all every match, each inside its own +/// paragraph. +pub(super) fn find_bar(view: &mut DocView, pages: usize, area: Rect, editing: bool, ui: &mut egui::Ui) { + let searched = view.texts.len() + view.text_failed.len(); + let key = view.pane.key; let Some(find) = view.find.as_mut() else { return }; // The Search panel shows this search. if find.in_panel { return; } - let mut close = false; - let mut step: Option = None; - let mut replace: Option = None; - let searched = view.texts.len() + view.text_failed.len(); - egui::Area::new(egui::Id::unique(("find-bar", view.pane.key))) - .order(egui::Order::Middle) - .pivot(Align2::RIGHT_TOP) - .fixed_pos(area.right_top() + vec2(-18.0, 12.0)) - .show(ui.ctx(), |ui| { - egui::Frame::NONE - .fill(t.card) - .stroke(Stroke::new(1.0, t.border)) - .corner_radius(CornerRadius::same(10)) - .shadow(egui::Shadow { offset: [0, 4], blur: 16, spread: 0, color: Color32::from_black_alpha(if t.dark() { 90 } else { 30 }) }) - .inner_margin(egui::Margin::symmetric(10, 6)) - .show(ui, |ui| { - ui.horizontal(|ui| { - ui.add(icons::image("search", 16.0, t.text_muted)); - let edit = egui::TextEdit::singleline(&mut find.query) - .id(find_input_id(view.pane.key)) - .hint_text(tl!("Find text")) - .desired_width(220.0) - .frame(egui::Frame::NONE); - let r = ui.add(edit).accessible_name(tl!("Find text")); - widgets::focus_selecting_all(ui, &r, &find.query, &mut find.focus); - if r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) { - step = Some(!ui.input(|i| i.modifiers.shift)); - r.request_focus(); - } - if r.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Escape)) { - close = true; - } - let status = if find.query.trim().is_empty() { - String::new() - } else if find.matches.is_empty() { - if searched < pages { - crate::i18n::fmt(tl!("Searching… {s}/{p}"), &[("s", &searched.to_string()), ("p", &pages.to_string())]) - } else { - tl!("No matches").to_string() - } - } else { - let more = if searched < pages { "+" } else { "" }; - crate::i18n::fmt( - tl!("{c} of {n}{more}"), - &[ - ("c", &find.current.map(|c| c + 1).unwrap_or(0).to_string()), - ("n", &find.matches.len().to_string()), - ("more", more), - ], - ) - }; - ui.label(egui::RichText::new(status).font(theme::regular(12.0)).color(t.text_muted)); - let tip = crate::commands::key_tip(ui.ctx(), tl!("Previous ({key})"), crate::commands::FIND_PREV); - if icons::button(ui, "chevron-up", 26.0, false, &tip).clicked() { - step = Some(false); - } - let tip = crate::commands::key_tip(ui.ctx(), tl!("Next ({key})"), crate::commands::FIND_NEXT); - if icons::button(ui, "chevron-down", 26.0, false, &tip).clicked() { - step = Some(true); - } - if editing { - let tip = crate::commands::command_tip(ui.ctx(), tl!("Replace ({key})"), "edit.replace"); - if icons::button(ui, "replace", 26.0, find.replacing, &tip).clicked() { - find.replacing = !find.replacing; - find.focus_replace = find.replacing; - } - } - let opts = icons::button(ui, "settings-2", 26.0, find.case_sensitive || find.whole_words, tl!("Find options")); - egui::Popup::menu(&opts).show(|ui| { - let a = ui.add(widgets::checkbox(&mut find.whole_words, tl!("Whole words only"))).changed(); - let b = ui.add(widgets::checkbox(&mut find.case_sensitive, tl!("Case-sensitive"))).changed(); - if a || b { - // Search again with the new options. - find.case_query.clear(); - } - }); - if icons::button(ui, "x", 26.0, false, tl!("Close (Esc)")).clicked() { - close = true; - } - }); - if editing && find.replacing { - ui.horizontal(|ui| { - ui.add(icons::image("replace", 16.0, t.text_muted)); - let edit = egui::TextEdit::singleline(&mut find.replacement) - .id(egui::Id::unique("replace-input")) - .hint_text(tl!("Replace with")) - .desired_width(220.0) - .frame(egui::Frame::NONE); - let r = ui.add(edit).accessible_name(tl!("Replace with")); - if find.focus_replace { - r.request_focus(); - find.focus_replace = false; - } - let searched = !find.case_query.trim().is_empty(); - // Enter in the field replaces the highlighted match, as the button does. - if r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) && find.current.is_some() { - replace = Some(false); - r.request_focus(); - } - if r.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Escape)) { - close = true; - } - ui.add_enabled_ui(find.current.is_some(), |ui| { - if crate::widgets::pill_button(ui, tl!("Replace"), false).clicked() { - replace = Some(false); - } - }); - ui.add_enabled_ui(searched, |ui| { - if crate::widgets::pill_button(ui, tl!("Replace all"), true).clicked() { - replace = Some(true); - } - }); - }); - } - }); - }); - if close { + // One id per pane, so two panes' bars do not share a field id (and so the focus). + let shown = TaskBar::at_edge(tl!("Find"), Align::End).id_salt(("find-bar", key)).show(ui, area, |ui, _cx| { + let Find { query, options, matches, bar, replacement, replacing, .. } = &mut *find; + let mut find_bar = FindBar::new(query, options, matches).state(bar).progress(searched, pages); + if editing { + find_bar = find_bar.replace(replacement, replacing); + } + find_bar.show(ui) + }); + let Some(out) = shown.inner else { return }; + if out.closed { view.find = None; return; } - if let Some(all) = replace { - view.pending_action = Some(ViewAction::Replace { all }); + match out.request { + Some(FindRequest::Replace { .. }) => view.pending_action = Some(ViewAction::Replace { all: false }), + Some(FindRequest::ReplaceAll { .. }) => view.pending_action = Some(ViewAction::Replace { all: true }), + _ => {} } - if find.query != find.case_query { + if out.search { view.rerun_find(); } - if let Some(forward) = step { - view.find_step(forward); + if out.stepped { + // The bar already stepped the matches. + view.show_current_match(); } } diff --git a/crates/ui-egui/src/tools/replace_ui.rs b/crates/ui-egui/src/tools/replace_ui.rs index 165c69e69a..4a820ff011 100644 --- a/crates/ui-egui/src/tools/replace_ui.rs +++ b/crates/ui-egui/src/tools/replace_ui.rs @@ -20,22 +20,22 @@ impl PdfCraftApp { let query = Replace { find: find.case_query.clone(), with: find.replacement.clone(), - case_sensitive: find.case_sensitive, - whole_words: find.whole_words, + case_sensitive: find.options.match_case, + whole_words: find.options.whole_word, }; let Some(doc) = self.session.get(view.id) else { return }; let (pages, which, found) = if all { // What the find bar holds on each page it has searched, so matches no paragraph // holds (a form field, a comment) are counted rather than lost. let mut found: BTreeMap = view.texts.keys().map(|p| (*p, 0)).collect(); - for (p, _) in &find.matches { - let n = found.entry(*p).or_insert(0); + for m in find.matches.matches() { + let n = found.entry(m.page).or_insert(0); *n = n.saturating_add(1); } ((0..doc.info.pages.len()).collect::>(), Which::All, Some(found)) } else { // The highlighted match, by where its first and last glyphs are drawn. - let Some((page, range)) = find.current.and_then(|c| find.matches.get(c)).cloned() else { return }; + let Some((page, range)) = find.matches.current_match().map(|m| (m.page, m.range.clone())) else { return }; let centre = |g: usize| { view.texts.get(&page).and_then(|t| t.glyphs.get(g)).map(|g| [(g.rect[0] + g.rect[2]) / 2.0, (g.rect[1] + g.rect[3]) / 2.0]) }; diff --git a/crates/ui-egui/tests/it/find_focus.rs b/crates/ui-egui/tests/it/find_focus.rs deleted file mode 100644 index f457b05b62..0000000000 --- a/crates/ui-egui/tests/it/find_focus.rs +++ /dev/null @@ -1,100 +0,0 @@ -//! Find (⌘F) gives the find field the keyboard with the query selected, so typing replaces it, -//! also when the field already has the keyboard, and asking again while the field is composing -//! with an IME leaves the composition alone (the find bar and the Search panel). - -use egui_kittest::Harness; -use pdfcraft_ui_egui::PdfCraftApp; - -fn harness() -> Harness<'static, PdfCraftApp> { - let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| { - let mut app = PdfCraftApp::new(); - app.run_inline = true; - app.set_option("language", "en").unwrap(); - app.open_bytes("form.pdf", None, include_bytes!("../data/form.pdf").to_vec()).unwrap(); - app.set_option("left", "closed").unwrap(); - app - }); - h.run_steps(4); - h -} - -fn query(h: &Harness<'static, PdfCraftApp>) -> String { - h.state().views[0].find.as_ref().unwrap().query.clone() -} - -#[test] -fn find_selects_the_query_when_the_field_takes_the_keyboard() { - let mut h = harness(); - h.state_mut().views[0].open_find(); - h.run_steps(2); - h.event(egui::Event::Text("cat".into())); - h.run_steps(2); - let id = h.state().views[0].find_input_id(); - h.ctx.memory_mut(|m| m.surrender_focus(id)); - h.run_steps(2); - - h.state_mut().views[0].open_find(); - h.run_steps(2); - assert!(h.ctx.memory(|m| m.has_focus(id))); - h.event(egui::Event::Text("dog".into())); - h.run_steps(2); - assert_eq!(query(&h), "dog", "typing replaces the selected query"); -} - -type Open = dyn Fn(&mut Harness<'static, PdfCraftApp>); - -/// The find bar (⌘F) and the Search panel (Advanced Search) share the focus request. -fn fields() -> [(&'static str, Box); 2] { - [ - ("find bar", Box::new(|h| h.state_mut().views[0].open_find())), - ("Search panel", Box::new(|h| assert!(h.state_mut().execute("edit.advanced_search")))), - ] -} - -/// A second Find while the field still has the keyboard (no IME composition) selects the query -/// again, so typing replaces it instead of appending. -#[test] -fn find_again_while_the_field_has_the_keyboard_selects_the_query() { - for (field, open) in fields() { - let mut h = harness(); - open(&mut h); - h.run_steps(2); - h.event(egui::Event::Text("cat".into())); - h.run_steps(2); - assert_eq!(query(&h), "cat", "{field}"); - - open(&mut h); - h.run_steps(2); - h.event(egui::Event::Text("dog".into())); - h.run_steps(2); - assert_eq!(query(&h), "dog", "{field}: typing replaces the selected query"); - } -} - -#[test] -fn find_again_while_composing_keeps_the_query() { - for (field, open) in fields() { - let mut h = harness(); - open(&mut h); - h.run_steps(2); - h.event(egui::Event::Text("cat".into())); - h.run_steps(2); - h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: "ka".into(), active_range_chars: Some(0..2) })); - h.run_steps(2); - assert_eq!(query(&h), "catka", "{field}"); - - // Selecting the query here would make the commit replace all of it. - open(&mut h); - h.run_steps(2); - h.event(egui::Event::Ime(egui::ImeEvent::Commit("か".into()))); - h.run_steps(2); - assert_eq!(query(&h), "catか", "{field}"); - - // The commit ended the composition, so the next Find selects the query again. - open(&mut h); - h.run_steps(2); - h.event(egui::Event::Text("dog".into())); - h.run_steps(2); - assert_eq!(query(&h), "dog", "{field}: typing after the composition replaces the query"); - } -} diff --git a/crates/ui-egui/tests/it/find_replace.rs b/crates/ui-egui/tests/it/find_replace.rs index 72dc487998..7a4c3e71e8 100644 --- a/crates/ui-egui/tests/it/find_replace.rs +++ b/crates/ui-egui/tests/it/find_replace.rs @@ -7,6 +7,8 @@ use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use pdfcraft_ui_egui::{PdfCraftApp, QuickTool}; +use crate::support; + /// Two 300×200 pages of Helvetica text: "cat and cat" and "a cat". fn fixture() -> Vec { let stream = |content: &str| format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()); @@ -84,10 +86,10 @@ fn replace_all_from_the_find_bar_is_one_undo_step() { h.run_steps(8); h.get_by_label("Replace all").click(); h.run_steps(4); - assert_eq!(texts(&h), ["dog and dog", "a dog"], "{:?}", h.state().toast); + assert_eq!(texts(&h), ["dog and dog", "a dog"]); + assert!(support::shown_notice(&mut h).is_some(), "Replace all says what it did"); let s = h.state(); assert_eq!(s.session.get(s.views[0].id).unwrap().can_undo(), Some("Replace all")); - assert_eq!(s.toast.as_ref().map(|t| t.0.as_str()), Some("Replaced 3 on 2 pages")); // One Undo puts every page back. assert!(h.state_mut().execute("edit.undo")); h.run_steps(2); diff --git a/crates/ui-egui/tests/it/search_position.rs b/crates/ui-egui/tests/it/search_position.rs index 9215d997e5..8c7f21acee 100644 --- a/crates/ui-egui/tests/it/search_position.rs +++ b/crates/ui-egui/tests/it/search_position.rs @@ -5,6 +5,7 @@ use egui_kittest::Harness; use pdfcraft_ui_egui::PdfCraftApp; +use pdfcraft_ui_egui::canvas::{Fit, PageDisplay}; /// The word searched for, placed (x, y in PDF user space) on each page. const NEEDLE: &str = "needle"; @@ -98,6 +99,13 @@ fn harness_dt(dt: f32) -> Harness<'static, PdfCraftApp> { h } +/// Zoom the first view to `zoom`, off any fit. +fn set_zoom(h: &mut Harness<'static, PdfCraftApp>, zoom: f64) { + let v = &mut h.state_mut().views[0].view; + v.zoom = zoom; + v.fit = Fit::None; +} + /// Run frames until rendering has finished and the layout holds still. fn settle(h: &mut Harness<'static, PdfCraftApp>) { for _ in 0..200 { @@ -114,15 +122,15 @@ fn settle(h: &mut Harness<'static, PdfCraftApp>) { fn assert_match_shown(h: &Harness<'static, PdfCraftApp>, what: &str) { let v = &h.state().views[0]; let f = v.find.as_ref().unwrap(); - let i = f.current.unwrap_or_else(|| panic!("{what}: no current match")); - let (page, range) = f.matches[i].clone(); + let i = f.matches.current().unwrap_or_else(|| panic!("{what}: no current match")); + let (page, range) = (f.matches.matches()[i].page, f.matches.matches()[i].range.clone()); let window = v.viewport_rect(); let at = |g: usize| v.glyph_screen_pos(page, g).unwrap_or_else(|| panic!("{what}: match {i} (page {}) is not on screen", page + 1)); let (first, last) = (at(range.start), at(range.end - 1)); // At the highest zooms one word is wider than the window: then its middle is what shows. let ends = if last.x - first.x < window.width() * 0.8 { vec![first, last] } else { vec![first.lerp(last, 0.5)] }; for p in ends { - assert!(window.contains(p), "{what}: match {i} (page {}) at {p:?} is outside the window {window:?} (zoom {})", page + 1, v.zoom); + assert!(window.contains(p), "{what}: match {i} (page {}) at {p:?} is outside the window {window:?} (zoom {})", page + 1, v.view.zoom); } let Some(page_rect) = v.page_screen_rect(page) else { return }; let centre = first.lerp(last, 0.5); @@ -134,10 +142,10 @@ fn assert_match_shown(h: &Harness<'static, PdfCraftApp>, what: &str) { let room_y = (page_rect.top() < window.top() - 1.0 || centre.y > window.center().y) && (page_rect.bottom() > window.bottom() + 1.0 || centre.y < window.center().y); if room_x { - assert!((centre.x - window.center().x).abs() < slack, "{what}: match {i} at x {} is not centred in {window:?} (zoom {})", centre.x, v.zoom); + assert!((centre.x - window.center().x).abs() < slack, "{what}: match {i} at x {} is not centred in {window:?} (zoom {})", centre.x, v.view.zoom); } if room_y { - assert!((centre.y - window.center().y).abs() < slack, "{what}: match {i} at y {} is not centred in {window:?} (zoom {})", centre.y, v.zoom); + assert!((centre.y - window.center().y).abs() < slack, "{what}: match {i} at y {} is not centred in {window:?} (zoom {})", centre.y, v.view.zoom); } } @@ -147,7 +155,7 @@ fn every_match_is_shown_after_zooming() { let mut h = harness(); let n = needles(); for zoom in [0.25, 0.5, 1.0, 2.0, 4.0, 8.0, 16.0] { - h.state_mut().views[0].set_zoom(zoom); + set_zoom(&mut h, zoom); settle(&mut h); for forward in [true, false] { for _ in 0..n { @@ -164,7 +172,7 @@ fn every_match_is_shown_after_zooming() { fn search_panel_results_are_shown_after_zooming() { let mut h = harness(); for zoom in [0.33, 3.0, 12.0] { - h.state_mut().views[0].set_zoom(zoom); + set_zoom(&mut h, zoom); settle(&mut h); for i in (0..needles()).rev() { h.state_mut().views[0].go_to_match(i); @@ -187,11 +195,11 @@ fn zooming_and_stepping_in_any_order_shows_the_match() { for round in 0..80 { let same_frame = next(3) == 0; match next(4) { - 0 => h.state_mut().views[0].zoom_step(true), - 1 => h.state_mut().views[0].zoom_step(false), + 0 => h.state_mut().views[0].view.zoom_step(true), + 1 => h.state_mut().views[0].view.zoom_step(false), 2 => { let z = [0.2, 0.75, 1.5, 6.0, 10.0][next(5) as usize]; - h.state_mut().views[0].set_zoom(z); + set_zoom(&mut h, z); } _ => {} } @@ -217,7 +225,7 @@ fn zooming_and_stepping_in_any_order_shows_the_match() { fn a_step_during_a_wheel_zoom_keeps_the_match_on_screen() { let mut h = harness(); h.state_mut().set_option("animation_effects", "on").unwrap(); - h.state_mut().views[0].set_zoom(3.0); + set_zoom(&mut h, 3.0); settle(&mut h); let n = needles(); for (i, dy) in (0..n).zip([60.0, -60.0].into_iter().cycle()) { @@ -233,12 +241,12 @@ fn a_step_during_a_wheel_zoom_keeps_the_match_on_screen() { source: egui::MouseWheelSource::Unknown, }); h.run_steps(2); - let before = h.state().views[0].zoom; + let before = h.state().views[0].view.zoom; h.state_mut().views[0].find_step(true); // Let the zoom finish easing, then the rendering. h.run_steps(60); settle(&mut h); - assert!((h.state().views[0].zoom - before).abs() > 1e-3, "step {i}: the zoom was still easing when the step came"); + assert!((h.state().views[0].view.zoom - before).abs() > 1e-3, "step {i}: the zoom was still easing when the step came"); assert_match_shown(&h, &format!("step {i} during a wheel zoom ({dy})")); } } @@ -253,7 +261,7 @@ fn a_step_during_a_wheel_zoom_keeps_the_match_when_the_pointer_leaves_and_return for (dy, out) in [(120.0, 2), (240.0, 4), (480.0, 3)] { let mut h = harness_dt(1.0 / 60.0); h.state_mut().set_option("animation_effects", "on").unwrap(); - h.state_mut().views[0].set_zoom(3.0); + set_zoom(&mut h, 3.0); settle(&mut h); let w = h.state().views[0].viewport_rect(); // The pointer well away from the middle, where the zoom would otherwise be anchored. @@ -270,14 +278,14 @@ fn a_step_during_a_wheel_zoom_keeps_the_match_when_the_pointer_leaves_and_return h.run_steps(2); h.state_mut().views[0].find_step(true); h.run_steps(1); - let during = h.state().views[0].zoom; + let during = h.state().views[0].view.zoom; // Off the page view (over the toolbar above it) while the zoom eases, then back. h.hover_at(egui::pos2(corner.x, (w.min.y - 20.0).max(1.0))); h.run_steps(out); h.hover_at(corner); h.run_steps(30); settle(&mut h); - assert!((h.state().views[0].zoom - during).abs() > 1e-3, "{dy}: the zoom was still easing when the pointer left"); + assert!((h.state().views[0].view.zoom - during).abs() > 1e-3, "{dy}: the zoom was still easing when the pointer left"); assert_match_shown(&h, &format!("pointer out for {out} frames during a wheel zoom ({dy})")); } } @@ -285,12 +293,17 @@ fn a_step_during_a_wheel_zoom_keeps_the_match_when_the_pointer_leaves_and_return /// Single page and two-up, scrolling or a page (spread) at a time: each step shows its match. #[test] fn every_page_display_shows_the_match_after_zooming() { - use pdfcraft_ui_egui::canvas::PageLayout; let mut h = harness(); - for (layout, continuous) in [(PageLayout::Single, false), (PageLayout::TwoUp, true), (PageLayout::TwoUp, false)] { - h.state_mut().views[0].set_display(layout, continuous); + for (layout, continuous) in [(PageDisplay::Single, false), (PageDisplay::TwoUp, true), (PageDisplay::TwoUp, false)] { + { + let v = &mut h.state_mut().views[0].view; + v.display = layout; + v.continuous = continuous; + let current = v.current; + v.go_to(current); + } for zoom in [0.5, 4.0] { - h.state_mut().views[0].set_zoom(zoom); + set_zoom(&mut h, zoom); settle(&mut h); for _ in 0..needles() { h.state_mut().views[0].find_step(true); @@ -307,7 +320,7 @@ fn every_page_display_shows_the_match_after_zooming() { #[test] fn a_scroll_by_hand_after_a_step_lets_the_match_go() { let mut h = harness(); - h.state_mut().views[0].set_zoom(3.0); + set_zoom(&mut h, 3.0); settle(&mut h); h.state_mut().views[0].find_step(true); settle(&mut h); @@ -338,7 +351,8 @@ fn a_scroll_by_hand_after_a_step_lets_the_match_go() { settle(&mut h); let v = &h.state().views[0]; let f = v.find.as_ref().unwrap(); - let (page, range) = f.matches[f.current.unwrap()].clone(); + let current = &f.matches.matches()[f.matches.current().unwrap()]; + let (page, range) = (current.page, current.range.clone()); let centre = v.glyph_screen_pos(page, range.start).map(|a| a.lerp(v.glyph_screen_pos(page, range.end - 1).unwrap_or(a), 0.5)); assert!( centre.is_none_or(|c| c.distance(v.viewport_rect().center()) > 100.0),