Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

M3: Advanced Search panel (⇧⌘F): every match with its context, by page; click to go; shares the find bar's search

Brandon Thomas55275cd935ae
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 37f079647..d2ba98890 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -164,6 +164,7 @@ pub const COMMANDS: &[CommandSpec] = &[
ct("edit.undo", "Undo", EDIT, Some(Shortcut::cmd("Z")), Undo, "undo-2"),
ct("edit.redo", "Redo", EDIT, Some(Shortcut::cmd_shift("Z")), Redo, "redo-2"),
c("edit.find", "Find…", EDIT, Some(Shortcut::cmd("F")), Document, "search"),
+ c("edit.advanced_search", "Advanced search…", EDIT, Some(Shortcut::cmd_shift("F")), Document, "search"),
c("view.palette", "Find tools and commands…", VIEW, Some(Shortcut::cmd("K")), Nothing, "search"),
c("view.fit_visible", "Fit visible", VIEW, Some(Shortcut::cmd("3")), Document, "scan"),
c("view.marquee_zoom", "Marquee zoom", VIEW, None, Document, "zoom-in"),
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 167f2ebe2..050d1c383 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -59,6 +59,8 @@ pub struct Find {
/// Find options (Acrobat's: case-sensitive, whole words only).
pub case_sensitive: bool,
pub whole_words: bool,
+ /// Shown in the Search panel (Advanced Search) instead of the find bar.
+ pub in_panel: bool,
}
/// A text selection on one page, in reading-order glyph indices.
@@ -112,8 +114,8 @@ pub struct DocView {
/// Sharp tiles of large pages: (page, tile x, tile y) → (scale tag, texture).
tiles: HashMap<(usize, u32, u32), (u64, TextureHandle)>,
/// Text layers, extracted in the background on demand (selection, find, copy).
- texts: HashMap<usize, Arc<PageText>>,
- text_failed: HashSet<usize>,
+ pub(crate) texts: HashMap<usize, Arc<PageText>>,
+ pub(crate) text_failed: HashSet<usize>,
pub find: Option<Find>,
selection: Option<Selection>,
last_queue: Vec<RenderRequest>,
@@ -408,6 +410,14 @@ impl DocView {
}
}
+ /// 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);
+ self.flash_match(p);
+ }
+
/// Move to the next/previous match.
pub fn find_step(&mut self, forward: bool) {
let Some(f) = self.find.as_mut() else { return };
@@ -852,6 +862,14 @@ pub fn shortcuts(view: &mut DocView, ctx: &egui::Context) {
pub fn document_area(app: &mut PrintCraftApp, index: usize, ui: &mut egui::Ui) {
let t = Tokens::get(ui.ctx());
+ // The Search panel closed: its search moves to the find bar.
+ let search_open = app.right == Some(crate::RightPanel::Search);
+ if let Some(f) = app.views[index].find.as_mut()
+ && f.in_panel
+ && !search_open
+ {
+ f.in_panel = false;
+ }
let Some(doc) = app.session.get(app.views[index].id) else { return };
let info = &doc.info;
if info.pages.is_empty() {
@@ -1637,6 +1655,10 @@ fn run_button(app: &mut PrintCraftApp, index: usize, ctx: &egui::Context, name:
/// Acrobat-style floating find bar at the top-right of the document area.
fn find_bar(view: &mut DocView, pages: usize, area: Rect, ui: &mut egui::Ui, t: &Tokens) {
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<bool> = None;
let searched = view.texts.len() + view.text_failed.len();
diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs
index 40d55818e..645032ce2 100644
--- a/crates/ui-egui/src/chrome.rs
+++ b/crates/ui-egui/src/chrome.rs
@@ -242,6 +242,7 @@ fn main_menu(app: &mut PrintCraftApp, ui: &mut egui::Ui) {
(RightPanel::Attachments, "Attachments"),
(RightPanel::Signatures, "Signatures"),
(RightPanel::Accessibility, "Accessibility Checker"),
+ (RightPanel::Search, "Search"),
] {
if ui.radio(app.right == Some(p), label).clicked() {
app.right = Some(p);
diff --git a/crates/ui-egui/src/commands.rs b/crates/ui-egui/src/commands.rs
index 56f48ac14..18088e9b0 100644
--- a/crates/ui-egui/src/commands.rs
+++ b/crates/ui-egui/src/commands.rs
@@ -223,6 +223,14 @@ impl PrintCraftApp {
"export.image" => self.dialog = Some(Dialog::Export(crate::export_ui::ExportKind::Image)),
"export.text" => self.dialog = Some(Dialog::Export(crate::export_ui::ExportKind::Text)),
"a11y.check" => self.start_accessibility_check(),
+ "edit.advanced_search" => {
+ if let Some(i) = self.active {
+ let f = self.views[i].find.get_or_insert_with(Default::default);
+ f.in_panel = true;
+ f.focus = true;
+ self.right = Some(crate::RightPanel::Search);
+ }
+ }
"a11y.report" => self.show_accessibility_report(),
"a11y.alt_text" => self.start_alt_text(),
"a11y.reading_options" => self.dialog = Some(Dialog::Properties(crate::PropsTab::Advanced)),
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 378eba44b..06b1bd403 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -19,6 +19,7 @@ mod crop;
mod export_ui;
mod marks_ui;
mod optimize_ui;
+mod search_ui;
mod sign_ui;
mod stamps_ui;
mod zoom_snap;
@@ -90,6 +91,8 @@ pub enum RightPanel {
Signatures,
/// Accessibility Checker results.
Accessibility,
+ /// Advanced Search results.
+ Search,
}
/// Quick-action bar tools (the vertical floating strip).
@@ -796,6 +799,7 @@ impl PrintCraftApp {
"attachments" => Some(RightPanel::Attachments),
"signatures" => Some(RightPanel::Signatures),
"accessibility" => Some(RightPanel::Accessibility),
+ "search" => Some(RightPanel::Search),
"none" => None,
other => return Err(format!("unknown panel {other}")),
}
diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs
index 412bae679..427f4451c 100644
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@ -374,6 +374,7 @@ pub fn right_panel(app: &mut PrintCraftApp, ui: &mut egui::Ui) {
RightPanel::Attachments => ("Attachments", Some(info.attachments.len())),
RightPanel::Signatures => ("Signatures", Some(doc.signatures.iter().filter(|s| s.signed).count())),
RightPanel::Accessibility => ("Accessibility Checker", None),
+ RightPanel::Search => ("Search", None),
};
ui.horizontal(|ui| {
ui.label(egui::RichText::new(title).font(theme::semibold(15.5)));
@@ -474,6 +475,7 @@ pub fn right_panel(app: &mut PrintCraftApp, ui: &mut egui::Ui) {
RightPanel::Accessibility => {
a11y_action = crate::a11y_ui::panel(ui, &t, a11y, id);
}
+ RightPanel::Search => crate::search_ui::panel(ui, &t, view, info.pages.len()),
RightPanel::Attachments => {
if info.attachments.is_empty() {
empty(ui, &t, "paperclip", "This document has no attachments.");
diff --git a/crates/ui-egui/src/search_ui.rs b/crates/ui-egui/src/search_ui.rs
new file mode 100644
index 000000000..5822018bf
--- /dev/null
+++ b/crates/ui-egui/src/search_ui.rs
@@ -0,0 +1,91 @@
+//! Edit ▸ Advanced Search (⇧⌘F): the search in a side panel that lists every match with its
+//! context, page by page; click a result to go to it. It shares the find bar's search.
+
+use egui::text::LayoutJob;
+use egui::{Color32, FontId, TextFormat};
+
+use crate::canvas::DocView;
+use crate::theme::{self, Tokens};
+
+/// Glyphs of context shown on each side of a match.
+const CONTEXT: usize = 36;
+
+pub(crate) fn panel(ui: &mut egui::Ui, t: &Tokens, view: &mut DocView, pages: usize) {
+ let searched = view.texts.len() + view.text_failed.len();
+ let Some(find) = view.find.as_mut() else { return };
+ find.in_panel = true;
+ let l = ui.label(egui::RichText::new("What word or phrase would you like to search for?").color(t.text_muted));
+ let r = ui
+ .add(egui::TextEdit::singleline(&mut find.query).id(egui::Id::new("search-panel-input")).hint_text("Search").desired_width(f32::INFINITY))
+ .labelled_by(l.id);
+ if find.focus {
+ r.request_focus();
+ find.focus = false;
+ }
+ ui.horizontal(|ui| {
+ // Outlined boxes (the panel and the check-box fill are alike), as in dialogs.
+ let w = &mut ui.visuals_mut().widgets;
+ w.inactive.bg_stroke = egui::Stroke::new(1.0, t.border);
+ w.inactive.bg_fill = t.hover;
+ let a = ui.checkbox(&mut find.whole_words, "Whole words only").changed();
+ let b = ui.checkbox(&mut find.case_sensitive, "Case-sensitive").changed();
+ if a || b {
+ find.case_query.clear();
+ }
+ });
+ if find.query != find.case_query {
+ view.rerun_find();
+ }
+ let Some(find) = view.find.as_ref() else { return };
+ ui.add_space(6.0);
+ let status = if find.query.trim().is_empty() {
+ String::new()
+ } else if find.matches.is_empty() && searched < pages {
+ format!("Searching… {searched} of {pages} pages")
+ } else {
+ let n = find.matches.len();
+ let more = if searched < pages { format!(" (searching… {searched} of {pages} pages)") } else { String::new() };
+ format!("{n} instance{}{more}", if n == 1 { "" } else { "s" })
+ };
+ ui.label(egui::RichText::new(status).font(theme::semibold(12.5)));
+ ui.add_space(4.0);
+ let mut go = None;
+ let mut last_page = None;
+ for (i, (p, range)) in find.matches.iter().enumerate().take(2000) {
+ if last_page != Some(*p) {
+ ui.add_space(4.0);
+ ui.label(egui::RichText::new(format!("Page {}", p + 1)).small().color(t.text_faint));
+ last_page = Some(*p);
+ }
+ let Some(text) = view.texts.get(p) else { continue };
+ let n = text.glyphs.len();
+ let before = text.text_of(range.start.saturating_sub(CONTEXT)..range.start.min(n));
+ let hit = text.text_of(range.start.min(n)..range.end.min(n));
+ let after = text.text_of(range.end.min(n)..(range.end + CONTEXT).min(n));
+ let flat = |s: String| s.split_whitespace().collect::<Vec<_>>().join(" ");
+ let mut job = LayoutJob::default();
+ let font = FontId::new(12.5, egui::FontFamily::Proportional);
+ let plain = TextFormat { font_id: font.clone(), color: t.text_muted, ..Default::default() };
+ job.append(&format!("…{} ", flat(before)), 0.0, plain.clone());
+ job.append(
+ &flat(hit),
+ 0.0,
+ TextFormat {
+ font_id: theme::semibold(12.5),
+ color: t.text,
+ background: Color32::from_rgba_unmultiplied(255, 214, 0, 90),
+ ..Default::default()
+ },
+ );
+ job.append(&format!(" {}…", flat(after)), 0.0, plain);
+ job.wrap.max_width = ui.available_width();
+ let selected = find.current == Some(i);
+ let resp = ui.add(egui::Button::selectable(selected, job).wrap()).on_hover_text("Go to this result");
+ if resp.clicked() {
+ go = Some(i);
+ }
+ }
+ if let Some(i) = go {
+ view.go_to_match(i);
+ }
+}
diff --git a/crates/ui-egui/tests/viewer.rs b/crates/ui-egui/tests/viewer.rs
index 78e30caf5..aac36aca8 100644
--- a/crates/ui-egui/tests/viewer.rs
+++ b/crates/ui-egui/tests/viewer.rs
@@ -322,3 +322,32 @@ fn an_earlier_revision_opens_from_document_properties() {
assert_eq!(doc.name, "updated (revision 1).pdf");
assert_eq!(doc.info_value("Title"), None, "as it was before the update");
}
+
+#[test]
+fn advanced_search_lists_results_with_context() {
+ let mut h = harness();
+ let i = h.state().active.unwrap();
+ assert!(h.state_mut().execute("edit.advanced_search"));
+ h.run_steps(2);
+ h.get_by_label("What word or phrase would you like to search for?");
+ h.state_mut().views[i].find.as_mut().unwrap().query = "pages".into();
+ for _ in 0..40 {
+ h.run_steps(2);
+ if h.state().views[i].find.as_ref().is_some_and(|f| f.matches.len() == 2) {
+ break;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(5));
+ }
+ h.run_steps(2);
+ h.get_by_label("2 instances");
+ h.get_by_label("Page 2");
+ // A result shows its context; clicking it goes there.
+ h.get_by_label_contains("Page 2 pages PAGE").click();
+ h.run_steps(3);
+ let v = &h.state().views[i];
+ assert_eq!((v.find.as_ref().unwrap().current, v.current), (Some(1), 1));
+ // Closing the panel moves the search to the find bar.
+ h.state_mut().right = None;
+ h.run_steps(2);
+ assert!(!h.state().views[i].find.as_ref().unwrap().in_panel);
+}
diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml
index 759ba1e1b..4fc62c4a0 100644
--- a/parity/acrobat-features.toml
+++ b/parity/acrobat-features.toml
@@ -1391,11 +1391,11 @@ title = "Find results list"
area = "B"
tier = "P1"
milestone = "M3"
-status = "planned"
-commands = []
-tools = []
-evidence = []
-notes = ""
+status = "shipped"
+commands = ["edit.advanced_search"]
+tools = ["text_find"]
+evidence = ["crates/ui-egui/tests/viewer.rs::advanced_search_lists_results_with_context"]
+notes = "Search panel (⇧⌘F): every match grouped by page with its context, whole words / case options, click to go; shares the find bar's search (closing the panel moves it to the bar)"
[[feature]]
id = "view.advanced-search"
@@ -1403,11 +1403,11 @@ title = "Advanced search window"
area = "B"
tier = "P1"
milestone = "M12"
-status = "planned"
-commands = []
-tools = []
-evidence = []
-notes = ""
+status = "partial"
+commands = ["edit.advanced_search"]
+tools = ["text_find"]
+evidence = ["crates/ui-egui/tests/viewer.rs::advanced_search_lists_results_with_context"]
+notes = "in the current document, as a side panel; searching other open documents, folders and indexes is still to come"
[[feature]]
id = "view.search-folder"