Skip to content

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

M3: Viewer conveniences: Close all (asks only for changed documents), Revert with confirmation, Fit to height, previous/next view (⌘[ ⌘]), page box takes page labels, Select all (⌘A), find options (whole words, case-sensitive), cover page in two-page view, follow the system theme

Brandon Thomas6c921fd8dd12
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 86743f709..ba9bf3c7b 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -153,6 +153,8 @@ pub const COMMANDS: &[CommandSpec] = &[
c("file.save", "Save", FILE, Some(Shortcut::cmd("S")), Document, "save"),
c("file.save_as", "Save as…", FILE, Some(Shortcut::cmd_shift("S")), Document, "save"),
c("file.close", "Close file", FILE, Some(Shortcut::cmd("W")), Document, "x"),
+ c("file.close_all", "Close all", FILE, Some(Shortcut::cmd_shift("W")), Document, "x"),
+ c("file.revert", "Revert", FILE, None, Undo, "rotate-ccw"),
c("print.dialog", "Print…", FILE, Some(Shortcut::cmd("P")), Document, "printer"),
c("file.properties", "Document properties…", FILE, Some(Shortcut::cmd("D")), Document, "info"),
ct("edit.undo", "Undo", EDIT, Some(Shortcut::cmd("Z")), Undo, "undo-2"),
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 729b35856..cd3497061 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -1392,6 +1392,31 @@ impl Session {
Self::refresh(doc)
}
+ /// File ▸ Revert: back to the last saved version (or the file as opened). Undo history is
+ /// cleared, as in Acrobat.
+ pub fn revert(&mut self, id: DocId) -> Result<(), EditError> {
+ let doc = self.doc_mut(id)?;
+ let editor = doc.editor.as_mut().ok_or_else(|| EditError::ReadOnly(doc.read_only_reason.clone().unwrap_or_default()))?;
+ let base = editor.cos.bytes().clone();
+ // The saved file opens with the passwords of the state that was saved: try the current
+ // ones, then each earlier state's.
+ let mut candidates = vec![editor.keys.clone()];
+ candidates.extend(editor.undo.iter().rev().map(|s| s.2.clone()));
+ candidates.push(Keys::default());
+ let (cos, keys) = candidates
+ .into_iter()
+ .find_map(|k| printcraft_cos::Document::open_with_password(base.clone(), k.reopen.as_deref()).ok().map(|c| (c, k)))
+ .ok_or_else(|| EditError::Reopen("the saved file can't be opened".into()))?;
+ editor.cos = cos;
+ editor.keys = keys;
+ editor.undo.clear();
+ editor.redo.clear();
+ Self::adopt_keys(doc);
+ doc.dirty = false;
+ doc.generation += 1;
+ Self::refresh(doc)
+ }
+
/// The page count of another PDF (Replace Pages, Insert Pages dialogs).
pub fn page_count_of(&self, name: &str, bytes: &Arc<Vec<u8>>) -> Result<usize, EditError> {
Ok(printcraft_organize::page_count(&open_source(name, bytes)?)?)
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index a59808e30..7ec18c19d 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -924,3 +924,19 @@ fn added_images_rotate_flip_and_crop_as_drawn() {
s.apply(id, Edit::UpdateContent { page: 0, index: 0, content: AddedContent::Image(img) }).unwrap();
assert!(red(colour_at(&s, 130, 150)), "the right half cropped away: red fills the box");
}
+
+#[test]
+fn revert_goes_back_to_the_saved_version() {
+ let (mut s, id) = session_with(2);
+ s.apply(id, Edit::DeletePages { pages: vec![0] }).unwrap();
+ let saved = s.save_bytes(id).unwrap();
+ s.mark_saved(id, saved, None).unwrap();
+ s.apply(id, Edit::RotatePages { pages: vec![0], degrees: 90 }).unwrap();
+ s.apply(id, Edit::InsertBlankPage { at: 0, width: 200.0, height: 300.0 }).unwrap();
+ assert!(s.get(id).unwrap().dirty);
+ s.revert(id).unwrap();
+ let d = s.get(id).unwrap();
+ assert!(!d.dirty && d.can_undo().is_none() && d.can_redo().is_none());
+ assert_eq!(page_texts(&s, id), ["Page 2"], "the saved state, not the opened one");
+ assert_eq!(d.info.pages[0].rotation, 0);
+}
diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs
index ced39153c..1f7dd7255 100644
--- a/crates/render/src/text.rs
+++ b/crates/render/src/text.rs
@@ -64,7 +64,13 @@ impl PageText {
/// Case-insensitive search. Returns glyph ranges of every match (words may span line breaks,
/// which count as a single space).
pub fn find(&self, needle: &str) -> Vec<std::ops::Range<usize>> {
- let needle: Vec<char> = needle.to_lowercase().split_whitespace().collect::<Vec<_>>().join(" ").chars().collect();
+ self.find_opts(needle, false, false)
+ }
+
+ /// Search with Acrobat's find options: case-sensitive, whole words only.
+ pub fn find_opts(&self, needle: &str, case_sensitive: bool, whole_words: bool) -> Vec<std::ops::Range<usize>> {
+ let fold = |s: &str| if case_sensitive { s.to_string() } else { s.to_lowercase() };
+ let needle: Vec<char> = fold(needle).split_whitespace().collect::<Vec<_>>().join(" ").chars().collect();
if needle.is_empty() {
return Vec::new();
}
@@ -74,14 +80,16 @@ impl PageText {
if i > 0 && (self.space_before[i] || self.line_of[i] != self.line_of[i - 1]) && chars.last().is_some_and(|c| c.0 != ' ') {
chars.push((' ', i));
}
- for c in g.text.chars().flat_map(char::to_lowercase) {
+ for c in fold(&g.text).chars() {
chars.push((if c.is_whitespace() { ' ' } else { c }, i));
}
}
+ let word = |k: Option<&(char, usize)>| k.is_some_and(|c| c.0.is_alphanumeric());
let mut out = Vec::new();
let mut i = 0;
while i + needle.len() <= chars.len() {
- if chars[i..i + needle.len()].iter().map(|c| c.0).eq(needle.iter().copied()) {
+ let bounded = !whole_words || (!word(i.checked_sub(1).and_then(|p| chars.get(p))) && !word(chars.get(i + needle.len())));
+ if bounded && chars[i..i + needle.len()].iter().map(|c| c.0).eq(needle.iter().copied()) {
let start = chars[i].1;
let end = chars[i + needle.len() - 1].1 + 1;
out.push(start..end);
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index a695b849c..8140467f4 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -36,6 +36,7 @@ const THUMB_W: f32 = 132.0;
pub enum Fit {
Width,
Page,
+ Height,
None,
}
@@ -55,6 +56,9 @@ pub struct Find {
pub current: Option<usize>,
pub focus: bool,
pub case_query: String,
+ /// Find options (Acrobat's: case-sensitive, whole words only).
+ pub case_sensitive: bool,
+ pub whole_words: bool,
}
/// A text selection on one page, in reading-order glyph indices.
@@ -88,6 +92,11 @@ pub struct DocView {
pub highlight_fields: bool,
pub page_input: String,
pub notice_dismissed: bool,
+ /// Two-page view: show the first page alone, as a cover (View ▸ Page display).
+ pub cover: bool,
+ /// Previous view / Next view: pages visited before (and after, once going back).
+ pub back: Vec<usize>,
+ pub forward: Vec<usize>,
/// Pending navigation: page and fraction down the page to align with the viewport top.
pub goto: Option<(usize, f32)>,
/// Briefly outline an annotation after navigating to it from a panel.
@@ -183,6 +192,9 @@ impl DocView {
highlight_fields: false,
page_input: "1".into(),
notice_dismissed: false,
+ cover: false,
+ back: Vec::new(),
+ forward: Vec::new(),
goto: None,
flash: None,
pages: HashMap::new(),
@@ -360,7 +372,7 @@ impl DocView {
}
let current_key = f.current.and_then(|c| f.matches.get(c).cloned());
f.matches.retain(|(p, _)| *p != page);
- f.matches.extend(text.find(&f.case_query).into_iter().map(|r| (page, r)));
+ 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));
f.current = match current_key {
Some(k) => f.matches.iter().position(|m| *m == k),
@@ -423,10 +435,60 @@ impl DocView {
}
pub fn go_to_page(&mut self, page: usize) {
+ let page = page.min(self.page_count.saturating_sub(1));
+ if page != self.current {
+ // The view history (Previous view / Next view).
+ if self.back.last() != Some(&self.current) {
+ self.back.push(self.current);
+ if self.back.len() > 200 {
+ self.back.remove(0);
+ }
+ }
+ self.forward.clear();
+ }
+ self.goto = Some((page, 0.0));
+ self.current = page;
+ self.page_input = (page + 1).to_string();
+ }
+
+ /// Go to the page typed in the page box: a page label (logical page numbers, as Acrobat
+ /// does), else a page number. `false` when it names no page.
+ pub fn go_to_typed(&mut self, typed: &str, labels: &[String]) -> bool {
+ let t = typed.trim();
+ let page = labels
+ .iter()
+ .position(|l| !l.is_empty() && l.eq_ignore_ascii_case(t))
+ .or_else(|| t.parse::<usize>().ok().filter(|n| *n >= 1).map(|n| n - 1));
+ match page {
+ Some(p) if p < self.page_count => {
+ self.go_to_page(p);
+ true
+ }
+ _ => false,
+ }
+ }
+
+ /// View ▸ Page navigation ▸ Previous view (`false`) / Next view (`true`).
+ pub fn view_history(&mut self, forward: bool) -> bool {
+ let (from, to) = if forward { (&mut self.forward, &mut self.back) } else { (&mut self.back, &mut self.forward) };
+ let Some(page) = from.pop() else { return false };
+ to.push(self.current);
let page = page.min(self.page_count.saturating_sub(1));
self.goto = Some((page, 0.0));
self.current = page;
self.page_input = (page + 1).to_string();
+ true
+ }
+
+ /// Edit ▸ Select all: every word on the current page.
+ pub fn select_all(&mut self) -> bool {
+ let page = self.current;
+ let Some(t) = self.texts.get(&page) else { return false };
+ if t.glyphs.is_empty() {
+ return false;
+ }
+ self.selection = Some(Selection { page, anchor: 0, head: t.glyphs.len() - 1 });
+ true
}
/// Rotate the view 90° clockwise or counter-clockwise (View ▸ Rotate View, ⇧⌘+ / ⇧⌘−).
@@ -534,6 +596,10 @@ impl DocView {
let zh = (self.viewport_h - 2.0 * MARGIN) / (h * PT);
self.zoom = zw.min(zh);
}
+ Fit::Height => {
+ let (_, h) = self.display_size(&info.pages[self.current.min(info.pages.len() - 1)]);
+ self.zoom = (self.viewport_h - 2.0 * MARGIN) / (h * PT);
+ }
Fit::None => {}
}
self.zoom = self.zoom.clamp(0.08, 64.0);
@@ -554,11 +620,17 @@ impl DocView {
}
}
PageLayout::TwoUp => {
- for pair in info.pages.chunks(2) {
+ // With a cover page, the first page sits alone on the right.
+ let rows: Vec<&[printcraft_render::PageInfo]> = if self.cover && !info.pages.is_empty() {
+ std::iter::once(&info.pages[..1]).chain(info.pages[1..].chunks(2)).collect()
+ } else {
+ info.pages.chunks(2).collect()
+ };
+ for (ri, pair) in rows.into_iter().enumerate() {
let sizes: Vec<Vec2> = pair.iter().map(|p| self.display_size(p)).map(|(w, h)| vec2(w * s, h * s)).collect();
let row_w: f32 = sizes.iter().map(|v| v.x).sum::<f32>() + GAP * (sizes.len() as f32 - 1.0);
let row_h = sizes.iter().map(|v| v.y).fold(0.0, f32::max);
- let mut x = ((content_w - row_w) / 2.0).max(SIDE);
+ let mut x = if self.cover && ri == 0 { (content_w / 2.0 + GAP / 2.0).max(SIDE) } else { ((content_w - row_w) / 2.0).max(SIDE) };
for size in sizes {
rects.push(Rect::from_min_size(pos2(x, y + (row_h - size.y) / 2.0), size));
x += size.x + GAP;
@@ -693,6 +765,15 @@ pub fn shortcuts(view: &mut DocView, ctx: &egui::Context) {
if pressed(cmd(Key::G)) {
view.find_step(true);
}
+ if pressed(cmd(Key::A)) {
+ view.select_all();
+ }
+ if pressed(cmd(Key::OpenBracket)) {
+ view.view_history(false);
+ }
+ if pressed(cmd(Key::CloseBracket)) {
+ view.view_history(true);
+ }
if pressed(KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, Key::G)) {
view.find_step(false);
}
@@ -1369,6 +1450,15 @@ fn find_bar(view: &mut DocView, pages: usize, area: Rect, ui: &mut egui::Ui, t:
if icons::button(ui, "chevron-down", 26.0, false, "Next (⌘G)").clicked() {
step = Some(true);
}
+ let opts = icons::button(ui, "settings-2", 26.0, find.case_sensitive || find.whole_words, "Find options");
+ egui::Popup::menu(&opts).show(|ui| {
+ 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 {
+ // Search again with the new options.
+ find.case_query.clear();
+ }
+ });
if icons::button(ui, "x", 26.0, false, "Close (Esc)").clicked() {
close = true;
}
diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs
index acb0db68e..0e212fa32 100644
--- a/crates/ui-egui/src/chrome.rs
+++ b/crates/ui-egui/src/chrome.rs
@@ -173,6 +173,10 @@ fn main_menu(app: &mut PrintCraftApp, ui: &mut egui::Ui) {
if widgets::menu_item(ui, "Fit to width", "⌘2").clicked() {
v.fit = Fit::Width;
}
+ if widgets::menu_item(ui, "Fit to height", "").clicked() {
+ v.fit = Fit::Height;
+ v.goto = Some((v.current, 0.0));
+ }
if widgets::menu_item(ui, "Zoom in", "⌘+").clicked() {
v.zoom_step(true);
}
@@ -186,6 +190,14 @@ fn main_menu(app: &mut PrintCraftApp, ui: &mut egui::Ui) {
v.rotate_view(false);
}
ui.separator();
+ ui.label(egui::RichText::new("Page navigation").color(t.text_faint).small());
+ if ui.add_enabled(!v.back.is_empty(), egui::Button::new("Previous view").shortcut_text("⌘[")).clicked() {
+ v.view_history(false);
+ }
+ if ui.add_enabled(!v.forward.is_empty(), egui::Button::new("Next view").shortcut_text("⌘]")).clicked() {
+ v.view_history(true);
+ }
+ ui.separator();
ui.label(egui::RichText::new("Page display").color(t.text_faint).small());
for (l, label) in
[(PageLayout::Continuous, "Continuous scrolling"), (PageLayout::TwoUp, "Two-page view"), (PageLayout::Single, "Single page")]
@@ -195,15 +207,23 @@ fn main_menu(app: &mut PrintCraftApp, ui: &mut egui::Ui) {
v.goto = Some((v.current, 0.0));
}
}
+ if ui.add_enabled(v.layout == PageLayout::TwoUp, egui::Checkbox::new(&mut v.cover, "Show cover page in two-page view")).changed() {
+ v.goto = Some((v.current, 0.0));
+ }
ui.separator();
}
crate::commands::registry_menu(app, ui, "View");
ui.menu_button("Display theme", |ui| {
let ctx = ui.ctx().clone();
- if ui.radio(app.theme == ThemeKind::Light, "Light gray").clicked() {
+ if ui.radio(app.follow_system_theme, "Use system setting").clicked() {
+ app.follow_system_theme = true;
+ }
+ if ui.radio(!app.follow_system_theme && app.theme == ThemeKind::Light, "Light gray").clicked() {
+ app.follow_system_theme = false;
app.set_theme(&ctx, ThemeKind::Light);
}
- if ui.radio(app.theme == ThemeKind::Dark, "Dark gray").clicked() {
+ if ui.radio(!app.follow_system_theme && app.theme == ThemeKind::Dark, "Dark gray").clicked() {
+ app.follow_system_theme = false;
app.set_theme(&ctx, ThemeKind::Dark);
}
});
@@ -238,6 +258,7 @@ pub fn right_rail(app: &mut PrintCraftApp, ui: &mut egui::Ui) {
!doc.info.attachments.is_empty(),
);
let page_count = doc.info.pages.len();
+ let labels: Vec<String> = doc.info.pages.iter().map(|p| p.label.clone()).collect();
egui::Panel::right("rail")
.resizable(false)
.exact_size(48.0)
@@ -301,12 +322,13 @@ pub fn right_rail(app: &mut PrintCraftApp, ui: &mut egui::Ui) {
.corner_radius(CornerRadius::same(5))
.show(ui, |ui| ui.add(edit))
.inner
- .on_hover_text("Current page — type a number and press Enter");
- if r.lost_focus()
- && ui.input(|i| i.key_pressed(egui::Key::Enter))
- && let Ok(n) = view.page_input.trim().parse::<usize>()
- {
- view.go_to_page(n.saturating_sub(1));
+ .on_hover_text("Current page — type a page number or label (such as iv) and press Enter");
+ if r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
+ // A page label first (logical page numbers, as Acrobat), then a number.
+ let typed = view.page_input.clone();
+ if !view.go_to_typed(&typed, &labels) {
+ view.page_input = (view.current + 1).to_string();
+ }
}
});
});
diff --git a/crates/ui-egui/src/commands.rs b/crates/ui-egui/src/commands.rs
index f241a6d9e..ed8340808 100644
--- a/crates/ui-egui/src/commands.rs
+++ b/crates/ui-egui/src/commands.rs
@@ -67,6 +67,8 @@ impl PrintCraftApp {
self.request_close_tab(i);
}
}
+ "file.close_all" => self.close_all(),
+ "file.revert" => self.dialog = Some(Dialog::Revert),
"file.properties" => self.dialog = Some(Dialog::Properties(PropsTab::Description)),
"protect.properties" => self.dialog = Some(Dialog::Properties(PropsTab::Security)),
"protect.password" => {
diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs
index 206cb9a01..c4ca6a3d0 100644
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@ -38,6 +38,7 @@ pub fn show(app: &mut PrintCraftApp, ctx: &egui::Context) {
let mut field_props_now = false;
let mut redact_now: Option<Dialog> = None;
let mut print_go = false;
+ let mut revert_now = false;
let mut replace_now = false;
let t = Tokens::get(ctx);
let mut close = false;
@@ -317,6 +318,23 @@ pub fn show(app: &mut PrintCraftApp, ctx: &egui::Context) {
close = ok || cancel;
return;
}
+ Dialog::Revert => {
+ let name = app.active_ids().and_then(|(_, id)| app.session.get(id)).map(|d| d.name.clone()).unwrap_or_default();
+ ui.label(egui::RichText::new("Revert").font(theme::semibold(18.0)));
+ ui.add_space(8.0);
+ ui.label(format!("Revert to the previously saved version of \"{name}\"? Changes since then can't be undone afterwards."));
+ ui.add_space(12.0);
+ ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
+ if widgets::pill_button(ui, "Revert", true).clicked() {
+ revert_now = true;
+ close = true;
+ }
+ if widgets::pill_button(ui, "Cancel", false).clicked() {
+ close = true;
+ }
+ });
+ return;
+ }
Dialog::Print => {
let Some((i, id)) = app.active_ids() else {
close = true;
@@ -609,6 +627,9 @@ pub fn show(app: &mut PrintCraftApp, ctx: &egui::Context) {
if print_go {
app.print_now();
}
+ if revert_now {
+ app.revert_active();
+ }
match redact_now {
Some(Dialog::RedactPages) => app.redact_pages(),
Some(Dialog::RedactSearch) => {
@@ -716,7 +737,7 @@ fn save_prompt(app: &mut PrintCraftApp, ctx: &egui::Context) {
let Some(req) = app.close_request else { return };
let index = match req {
CloseRequest::Tab(i) => Some(i),
- CloseRequest::Quit => app.first_dirty(),
+ CloseRequest::Quit | CloseRequest::All => app.first_dirty(),
};
let Some(name) = index.and_then(|i| app.views.get(i)).and_then(|v| app.session.get(v.id)).map(|d| d.name.clone()) else {
// Nothing left to ask about (tab already gone or no dirty documents).
diff --git a/crates/ui-egui/src/editing.rs b/crates/ui-egui/src/editing.rs
index 5290154bc..fa760de9f 100644
--- a/crates/ui-egui/src/editing.rs
+++ b/crates/ui-egui/src/editing.rs
@@ -12,6 +12,8 @@ pub enum CloseRequest {
Tab(usize),
/// Quit the application once every dirty document is resolved.
Quit,
+ /// File ▸ Close all: like Quit, but the application stays open.
+ All,
}
/// Where Save writes.
@@ -189,6 +191,34 @@ impl PrintCraftApp {
}
}
+ /// File ▸ Close all: clean documents close at once; each one with unsaved changes asks.
+ pub fn close_all(&mut self) {
+ for i in (0..self.views.len()).rev() {
+ if !self.session.get(self.views[i].id).is_some_and(|d| d.dirty) {
+ self.close_tab(i);
+ }
+ }
+ if self.first_dirty().is_some() {
+ self.close_request = Some(CloseRequest::All);
+ }
+ }
+
+ /// File ▸ Revert (after the confirmation).
+ pub fn revert_active(&mut self) {
+ let Some((_, id)) = self.active_ids() else { return };
+ match self.session.revert(id) {
+ Ok(()) => {
+ if let Some(i) = self.active
+ && let Some(d) = self.session.get(id)
+ {
+ self.views[i].document_changed(&d.info);
+ }
+ self.notify("Reverted to the last saved version");
+ }
+ Err(e) => self.notify(e.to_string()),
+ }
+ }
+
/// The first tab with unsaved changes.
pub fn first_dirty(&self) -> Option<usize> {
self.views.iter().position(|v| self.session.get(v.id).is_some_and(|d| d.dirty))
@@ -199,10 +229,12 @@ impl PrintCraftApp {
let Some(req) = self.close_request.take() else { return };
let index = match req {
CloseRequest::Tab(i) => i,
- CloseRequest::Quit => match self.first_dirty() {
+ CloseRequest::Quit | CloseRequest::All => match self.first_dirty() {
Some(i) => i,
None => {
- self.quit(ctx);
+ if req == CloseRequest::Quit {
+ self.quit(ctx);
+ }
return;
}
},
@@ -214,11 +246,12 @@ impl PrintCraftApp {
return; // save failed or was cancelled: keep the document open
}
self.close_tab(index);
- if req == CloseRequest::Quit {
+ if req == CloseRequest::Quit || req == CloseRequest::All {
// Ask about the next dirty document, or quit.
match self.first_dirty() {
- Some(_) => self.close_request = Some(CloseRequest::Quit),
- None => self.quit(ctx),
+ Some(_) => self.close_request = Some(req),
+ None if req == CloseRequest::Quit => self.quit(ctx),
+ None => {}
}
}
}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 94a094790..8c8e391c5 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -5,7 +5,7 @@
//! Everything here is presentation: documents, rendering and the tool catalogue live in
//! `printcraft-engine`.
-mod canvas;
+pub mod canvas;
mod chrome;
mod commands;
mod comment_props;
@@ -128,6 +128,8 @@ pub enum Dialog {
RedactApply,
/// File ▸ Print.
Print,
+ /// File ▸ Revert confirmation.
+ Revert,
/// Remove Hidden Information and Sanitize Document.
RemoveHidden,
Sanitize,
@@ -175,6 +177,8 @@ pub struct PrintCraftApp {
/// Comment author, per-tool colours and widths, pin.
pub comment_prefs: comments::CommentPrefs,
pub theme: ThemeKind,
+ /// Follow the operating system's light/dark setting.
+ pub follow_system_theme: bool,
pub dialog: Option<Dialog>,
pub palette_open: bool,
pub palette_query: String,
@@ -277,6 +281,7 @@ impl PrintCraftApp {
quick_tool: QuickTool::Select,
comment_prefs: Default::default(),
theme: ThemeKind::Light,
+ follow_system_theme: false,
dialog: None,
palette_open: false,
palette_query: String::new(),
@@ -587,7 +592,10 @@ impl PrintCraftApp {
pub fn set_option(&mut self, key: &str, value: &str) -> Result<(), String> {
let view = self.active.and_then(|i| self.views.get_mut(i));
match (key, view) {
- ("theme", _) => self.pending_theme = Some(if value == "dark" { ThemeKind::Dark } else { ThemeKind::Light }),
+ ("theme", _) => {
+ self.follow_system_theme = value == "system";
+ self.pending_theme = Some(if value == "dark" { ThemeKind::Dark } else { ThemeKind::Light });
+ }
("panel", _) => {
self.right = match value {
"comments" => Some(RightPanel::Comments),
@@ -758,6 +766,14 @@ impl eframe::App for PrintCraftApp {
if let Some(k) = self.pending_theme.take() {
self.set_theme(ctx, k);
}
+ if self.follow_system_theme
+ && let Some(sys) = ctx.system_theme()
+ {
+ let want = if sys == egui::Theme::Dark { ThemeKind::Dark } else { ThemeKind::Light };
+ if want != self.theme {
+ self.set_theme(ctx, want);
+ }
+ }
let dropped = ctx.input(|i| i.raw.dropped_files.clone());
for f in dropped {
self.open_dropped(f, ctx);
diff --git a/crates/ui-egui/tests/viewer.rs b/crates/ui-egui/tests/viewer.rs
new file mode 100644
index 000000000..f6c8f8b47
--- /dev/null
+++ b/crates/ui-egui/tests/viewer.rs
@@ -0,0 +1,173 @@
+//! Viewer conveniences: close all, revert, fit height, view history, select all, find options,
+//! cover page.
+
+use egui_kittest::Harness;
+use egui_kittest::kittest::Queryable;
+use printcraft_ui_egui::{Dialog, PrintCraftApp};
+
+/// `n` pages of 200×300; page i says "Page i+1" plus "page" and "Pages" for find tests.
+fn fixture(n: usize) -> Vec<u8> {
+ let mut objs: Vec<String> = vec!["<< /Type /Catalog /Pages 2 0 R >>".into()];
+ let kids: Vec<String> = (0..n).map(|i| format!("{} 0 R", 4 + 2 * i)).collect();
+ objs.push(format!("<< /Type /Pages /Kids [{}] /Count {n} /MediaBox [0 0 200 300] >>", kids.join(" ")));
+ objs.push("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".into());
+ for i in 0..n {
+ objs.push(format!("<< /Type /Page /Parent 2 0 R /Contents {} 0 R /Resources << /Font << /F1 3 0 R >> >> >>", 5 + 2 * i));
+ let body = format!("BT /F1 18 Tf 20 150 Td (Page {} pages PAGE) Tj ET", i + 1);
+ objs.push(format!("<< /Length {} >>\nstream\n{body}\nendstream", body.len()));
+ }
+ let mut out = b"%PDF-1.7\n".to_vec();
+ let mut offs = Vec::new();
+ for (i, o) in objs.iter().enumerate() {
+ offs.push(out.len());
+ out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
+ }
+ let x = out.len();
+ out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
+ for o in offs {
+ out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
+ }
+ out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{x}\n%%EOF\n", objs.len() + 1).as_bytes());
+ out
+}
+
+fn harness() -> Harness<'static, PrintCraftApp> {
+ let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| {
+ let mut app = PrintCraftApp::new();
+ app.open_bytes("a.pdf", None, fixture(5)).unwrap();
+ app.open_bytes("b.pdf", None, fixture(2)).unwrap();
+ app
+ });
+ for _ in 0..40 {
+ h.run_steps(2);
+ if !h.state().render_pending() {
+ break;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(5));
+ }
+ h
+}
+
+#[test]
+fn close_all_asks_only_for_changed_documents() {
+ let mut h = harness();
+ // Change the active document (b.pdf).
+ h.state_mut().apply_edit(printcraft_engine::Edit::RotatePages { pages: vec![0], degrees: 90 });
+ h.state_mut().execute("file.close_all");
+ h.run_steps(2);
+ assert_eq!(h.state().views.len(), 1, "the clean document closed at once");
+ assert_eq!(h.state().close_request, Some(printcraft_ui_egui::CloseRequest::All), "b.pdf asks to be saved");
+ h.get_by_label_contains("Save changes");
+}
+
+#[test]
+fn revert_after_confirming() {
+ let mut h = harness();
+ h.state_mut().apply_edit(printcraft_engine::Edit::DeletePages { pages: vec![0] });
+ assert!(h.state_mut().execute("file.revert"));
+ h.run_steps(2);
+ assert_eq!(h.state().dialog, Some(Dialog::Revert));
+ h.get_all_by_label("Revert").last().expect("the button").click();
+ h.run_steps(3);
+ let s = h.state();
+ let d = s.session.get(s.views[1].id).unwrap();
+ assert_eq!((d.info.pages.len(), d.dirty), (2, false));
+}
+
+#[test]
+fn view_history_select_all_and_find_options() {
+ let mut h = harness();
+ h.state_mut().active = Some(0);
+ h.run_steps(2);
+ h.state_mut().views[0].go_to_page(3);
+ h.run_steps(2);
+ h.state_mut().views[0].go_to_page(1);
+ h.run_steps(2);
+ assert!(h.state_mut().views[0].view_history(false));
+ assert_eq!(h.state().views[0].current, 3, "previous view");
+ assert!(h.state_mut().views[0].view_history(false));
+ assert_eq!(h.state().views[0].current, 0);
+ assert!(h.state_mut().views[0].view_history(true));
+ assert_eq!(h.state().views[0].current, 3, "next view");
+ // Select all on the current page (once its text is known).
+ for _ in 0..40 {
+ h.run_steps(2);
+ if h.state_mut().views[0].select_all() {
+ break;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(5));
+ }
+ assert_eq!(h.state().views[0].selected_text().as_deref(), Some("Page 4 pages PAGE"));
+ // Find: "page" matches three times a page; whole words, case-sensitive narrows it.
+ h.state_mut().views[0].open_find();
+ h.state_mut().views[0].find.as_mut().unwrap().query = "page".into();
+ h.state_mut().views[0].rerun_find();
+ for _ in 0..60 {
+ h.run_steps(2);
+ std::thread::sleep(std::time::Duration::from_millis(5));
+ if h.state().views[0].find.as_ref().unwrap().matches.len() >= 15 {
+ break;
+ }
+ }
+ assert_eq!(h.state().views[0].find.as_ref().unwrap().matches.len(), 15);
+ {
+ let f = h.state_mut().views[0].find.as_mut().unwrap();
+ f.whole_words = true;
+ f.case_sensitive = true;
+ }
+ h.state_mut().views[0].rerun_find();
+ h.run_steps(2);
+ assert_eq!(h.state().views[0].find.as_ref().unwrap().matches.len(), 0, "\"page\" alone, lower case, appears nowhere");
+ h.state_mut().views[0].find.as_mut().unwrap().query = "PAGE".into();
+ h.state_mut().views[0].rerun_find();
+ h.run_steps(2);
+ assert_eq!(h.state().views[0].find.as_ref().unwrap().matches.len(), 5);
+}
+
+#[test]
+fn layouts_fit_height_labels_and_system_theme() {
+ use printcraft_ui_egui::canvas::{Fit, PageLayout};
+ let mut h = harness();
+ h.state_mut().active = Some(0);
+ // Fit height: the page's height fills the view (less the margins).
+ h.state_mut().views[0].fit = Fit::Height;
+ h.run_steps(4);
+ let r = h.state().views[0].page_screen_rect(0).expect("on screen");
+ let vp = h.state().views[0].viewport_rect();
+ assert!(r.height() > vp.height() * 0.85 && r.top() >= vp.top() && r.bottom() <= vp.bottom() + 1.0, "page {r:?} in {vp:?}");
+ // Two-page view scrolls continuously; a cover puts page 1 alone on the right.
+ h.state_mut().views[0].fit = Fit::Width;
+ h.state_mut().views[0].layout = PageLayout::TwoUp;
+ h.run_steps(4);
+ let (a, b) = (h.state().views[0].page_screen_rect(0).unwrap(), h.state().views[0].page_screen_rect(1).unwrap());
+ assert!((a.top() - b.top()).abs() < 1.0 && b.left() > a.right(), "side by side");
+ h.state_mut().views[0].cover = true;
+ h.run_steps(4);
+ let (a, b, c) = (
+ h.state().views[0].page_screen_rect(0).unwrap(),
+ h.state().views[0].page_screen_rect(1).unwrap(),
+ h.state().views[0].page_screen_rect(2).unwrap(),
+ );
+ assert!(a.left() > vp.center().x - 1.0, "the cover sits on the right");
+ assert!(b.top() > a.bottom() && (b.top() - c.top()).abs() < 1.0, "then pairs 2–3");
+ // Page labels in the page box.
+ h.state_mut().apply_edit(printcraft_engine::Edit::NumberPages {
+ from: 0,
+ to: 1,
+ style: printcraft_engine::LabelStyle::LowerRoman,
+ prefix: String::new(),
+ first: 1,
+ });
+ h.run_steps(2);
+ let labels: Vec<String> = {
+ let s = h.state();
+ s.session.get(s.views[0].id).unwrap().info.pages.iter().map(|p| p.label.clone()).collect()
+ };
+ assert_eq!(labels[1], "ii");
+ assert!(h.state_mut().views[0].go_to_typed("ii", &labels));
+ assert_eq!(h.state().views[0].current, 1);
+ assert!(!h.state_mut().views[0].go_to_typed("xx", &labels));
+ // Follow the system theme.
+ h.state_mut().set_option("theme", "system").unwrap();
+ assert!(h.state().follow_system_theme);
+}
diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml
index 188099f39..91154b020 100644
--- a/parity/acrobat-features.toml
+++ b/parity/acrobat-features.toml
@@ -607,11 +607,11 @@ title = "Close all documents"
area = "A"
tier = "P1"
milestone = "M3"
-status = "planned"
-commands = []
+status = "shipped"
+commands = ["file.close_all"]
tools = []
-evidence = []
-notes = ""
+evidence = ["crates/ui-egui/tests/viewer.rs::close_all_asks_only_for_changed_documents"]
+notes = "clean documents close; each changed one asks"
[[feature]]
id = "core.revert"
@@ -619,11 +619,11 @@ title = "Revert to the last saved version"
area = "A"
tier = "P1"
milestone = "M4"
-status = "planned"
-commands = []
+status = "shipped"
+commands = ["file.revert"]
tools = []
-evidence = []
-notes = ""
+evidence = ["crates/ui-egui/tests/viewer.rs::revert_after_confirming", "crates/engine/src/tests.rs::revert_goes_back_to_the_saved_version"]
+notes = "with confirmation; clears undo, as Acrobat"
[[feature]]
id = "core.signed-save-policy"
@@ -851,11 +851,11 @@ title = "Two-page scrolling"
area = "B"
tier = "P1"
milestone = "M3"
-status = "planned"
+status = "shipped"
commands = []
tools = []
-evidence = []
-notes = ""
+evidence = ["crates/ui-egui/tests/viewer.rs::layouts_fit_height_labels_and_system_theme"]
+notes = "the two-page view scrolls continuously"
[[feature]]
id = "view.cover-page"
@@ -863,11 +863,11 @@ title = "Show cover page in two-page view"
area = "B"
tier = "P1"
milestone = "M3"
-status = "planned"
+status = "shipped"
commands = []
tools = []
-evidence = []
-notes = ""
+evidence = ["crates/ui-egui/tests/viewer.rs::layouts_fit_height_labels_and_system_theme"]
+notes = "View ▸ Show cover page in two-page view"
[[feature]]
id = "view.page-gaps"
@@ -959,11 +959,11 @@ title = "Fit height"
area = "B"
tier = "P1"
milestone = "M3"
-status = "planned"
+status = "shipped"
commands = []
tools = []
-evidence = []
-notes = ""
+evidence = ["crates/ui-egui/tests/viewer.rs::layouts_fit_height_labels_and_system_theme"]
+notes = "View ▸ Fit to height"
[[feature]]
id = "view.zoom-fit-visible"
@@ -1115,11 +1115,11 @@ title = "Go to a page by its label (logical page numbers)"
area = "B"
tier = "P1"
milestone = "M3"
-status = "planned"
+status = "shipped"
commands = []
tools = []
-evidence = []
-notes = ""
+evidence = ["crates/ui-egui/tests/viewer.rs::layouts_fit_height_labels_and_system_theme"]
+notes = "the page box takes labels (iv, A-1) before numbers"
[[feature]]
id = "view.view-history"
@@ -1127,11 +1127,11 @@ title = "Previous view / next view"
area = "B"
tier = "P1"
milestone = "M3"
-status = "planned"
+status = "shipped"
commands = []
tools = []
-evidence = []
-notes = ""
+evidence = ["crates/ui-egui/tests/viewer.rs::view_history_select_all_and_find_options"]
+notes = "⌘[ / ⌘] and View ▸ Page navigation"
[[feature]]
id = "view.follow-links"
@@ -1367,11 +1367,11 @@ title = "Find options: whole words, case-sensitive"
area = "B"
tier = "P1"
milestone = "M3"
-status = "planned"
-commands = []
+status = "shipped"
+commands = ["edit.find"]
tools = []
-evidence = []
-notes = ""
+evidence = ["crates/ui-egui/tests/viewer.rs::view_history_select_all_and_find_options"]
+notes = "whole words only, case-sensitive"
[[feature]]
id = "view.find-in-comments-bookmarks"
@@ -1487,11 +1487,11 @@ title = "Select all text on a page"
area = "B"
tier = "P1"
milestone = "M3"
-status = "planned"
+status = "shipped"
commands = []
tools = []
-evidence = []
-notes = ""
+evidence = ["crates/ui-egui/tests/viewer.rs::view_history_select_all_and_find_options"]
+notes = "⌘A on the current page"
[[feature]]
id = "view.copy-with-layout"
@@ -1595,11 +1595,11 @@ title = "Follow the system theme"
area = "B"
tier = "P1"
milestone = "M3"
-status = "planned"
-commands = []
+status = "shipped"
+commands = ["view.theme"]
tools = []
-evidence = []
-notes = ""
+evidence = ["crates/ui-egui/tests/viewer.rs::layouts_fit_height_labels_and_system_theme"]
+notes = "Display theme ▸ Use system setting (and --theme system)"
[[feature]]
id = "view.home-view"