Skip to content

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

Refactor ui support for strict Clippy checks

Dylan M. Taylor2d27306a8d3a
diff --git a/crates/ui-egui/src/app/input.rs b/crates/ui-egui/src/app/input.rs
index ad554c1df..953eb4a6e 100644
--- a/crates/ui-egui/src/app/input.rs
+++ b/crates/ui-egui/src/app/input.rs
@@ -1,4 +1,4 @@
-use super::*;
+use super::{GridDrop, GridFile, OpenRequest, PdfCraftApp, open_worker};
/// Read a file dropped on a page grid (see [`GridFile`]).
fn read_grid_file((name, source): GridFile) -> Result<(String, Vec<u8>), (String, String)> {
diff --git a/crates/ui-egui/src/app/prefs.rs b/crates/ui-egui/src/app/prefs.rs
index ac8ac644e..f64ba6d89 100644
--- a/crates/ui-egui/src/app/prefs.rs
+++ b/crates/ui-egui/src/app/prefs.rs
@@ -178,6 +178,15 @@ impl PdfCraftApp {
let r: Vec<RecentFile> = r.into_iter().filter(|f| std::path::Path::new(&f.path).exists()).collect();
self.recent = r;
}
+ self.restore_layout_prefs(&v);
+ self.restore_behavior_prefs(&v);
+ self.restore_view_prefs(&v);
+ self.restore_comment_prefs(&v);
+ self.restore_signature_prefs(&v);
+ }
+
+ /// The panels, combine view, zoom and recent files.
+ fn restore_layout_prefs(&mut self, v: &serde_json::Value) {
if let Some(on) = v["reopen_last_session"].as_bool() {
self.reopen_last_session = on;
}
@@ -211,6 +220,10 @@ impl PdfCraftApp {
if let Some((layout, continuous)) = v["default_layout"].as_str().and_then(canvas::parse_display_token) {
(self.view_defaults.layout, self.view_defaults.continuous) = (layout, continuous);
}
+ }
+
+ /// Switches for reopening, window chrome and file watching.
+ fn restore_behavior_prefs(&mut self, v: &serde_json::Value) {
if let Some(show) = v["default_page_gaps"].as_bool() {
self.view_defaults.show_page_gaps = show;
}
@@ -252,6 +265,10 @@ impl PdfCraftApp {
self.redact_prefs = prefs.clone();
self.redact_defaults = prefs;
}
+ }
+
+ /// Display defaults, units, language and sign-in details.
+ fn restore_view_prefs(&mut self, v: &serde_json::Value) {
// Settings are untrusted: an unreadable value (a colour that isn't three bytes, say)
// fails to deserialize and keeps Off.
if let Ok(colors) = serde_json::from_value::<pdfcraft_render::ReadingColors>(v["reading_colors"].clone()) {
@@ -277,6 +294,10 @@ impl PdfCraftApp {
if let Some(pinned) = v["comment_tool_pinned"].as_bool() {
self.comment_prefs.pinned = pinned;
}
+ }
+
+ /// The author and per-tool comment styles.
+ fn restore_comment_prefs(&mut self, v: &serde_json::Value) {
// Per-tool comment styles (#340): each field goes through its clamping setter, so a
// malformed or hostile entry is clamped or ignored rather than trusted.
if let Some(styles) = v["comment_styles"].as_array() {
@@ -305,6 +326,10 @@ impl PdfCraftApp {
}
}
}
+ }
+
+ /// Saved signatures, stamps, actions and trusted certificates.
+ fn restore_signature_prefs(&mut self, v: &serde_json::Value) {
if let Ok(s) = serde_json::from_value::<Vec<Vec<[f32; 2]>>>(v["signature"].clone())
&& s.iter().all(|st| st.iter().all(|p| p.iter().all(|x| x.is_finite())))
{
diff --git a/crates/ui-egui/src/app/window.rs b/crates/ui-egui/src/app/window.rs
index c950b54a5..e7035b500 100644
--- a/crates/ui-egui/src/app/window.rs
+++ b/crates/ui-egui/src/app/window.rs
@@ -1,4 +1,4 @@
-use super::*;
+use super::{PdfCraftApp, QuickTool};
impl PdfCraftApp {
/// Whether the app draws the window's title bar, buttons and resize edges: the desktop leaves
diff --git a/crates/ui-egui/src/control/host.rs b/crates/ui-egui/src/control/host.rs
index 62693cda2..1166c0e7e 100644
--- a/crates/ui-egui/src/control/host.rs
+++ b/crates/ui-egui/src/control/host.rs
@@ -1,4 +1,4 @@
-use super::*;
+use super::{Host, Reply, Value, json};
impl Host for crate::PdfCraftApp {
/// Cancel any in-progress pointer gesture in every open view.
diff --git a/crates/ui-egui/src/control/pending.rs b/crates/ui-egui/src/control/pending.rs
index 9e63849cf..d87ae037a 100644
--- a/crates/ui-egui/src/control/pending.rs
+++ b/crates/ui-egui/src/control/pending.rs
@@ -1,5 +1,5 @@
use super::screenshot::{Geometry, MAX_IMAGE_BYTES, retried_reservation, screenshot_png};
-use super::*;
+use super::{Arc, Control, Host, Pending, Reply, Sender, Value, not_drawn, timeout};
/// A screenshot pending in the `finish_pending` pass, with ownership of its reply.
struct PendingCapture {
diff --git a/crates/ui-egui/src/control/plugin.rs b/crates/ui-egui/src/control/plugin.rs
index be0dff826..a6def94c4 100644
--- a/crates/ui-egui/src/control/plugin.rs
+++ b/crates/ui-egui/src/control/plugin.rs
@@ -1,5 +1,5 @@
use super::requests::Handled;
-use super::*;
+use super::{Arc, Control, Mutex, RequestBatches, Shared, Value, timeout};
/// Track only presses that reached egui and have not yet been released. A pointer release is
/// retained as an ownership marker, never as a timeout event.
diff --git a/crates/ui-egui/src/control/requests.rs b/crates/ui-egui/src/control/requests.rs
index 1e2a24b97..0c926ab2a 100644
--- a/crates/ui-egui/src/control/requests.rs
+++ b/crates/ui-egui/src/control/requests.rs
@@ -1,5 +1,5 @@
use super::screenshot::Geometry;
-use super::*;
+use super::{Action, Control, Host, NodeId, Reply, Value, accesskit, json};
impl Control {
/// Validate and dispatch one control method, rejecting unknown methods and malformed parameters with
diff --git a/crates/ui-egui/src/control/screenshot.rs b/crates/ui-egui/src/control/screenshot.rs
index 9eb3e50bb..c6fbb0ed8 100644
--- a/crates/ui-egui/src/control/screenshot.rs
+++ b/crates/ui-egui/src/control/screenshot.rs
@@ -1,4 +1,4 @@
-use super::*;
+use super::{Control, Host, Pending, Reply, Sender, json};
/// Screenshot admission limits: bounded requests, per-image bytes and aggregate retained bytes.
const MAX_PENDING_SCREENSHOTS: usize = 4;
diff --git a/crates/ui-egui/src/control/transport.rs b/crates/ui-egui/src/control/transport.rs
index 81e30ff10..23a5181de 100644
--- a/crates/ui-egui/src/control/transport.rs
+++ b/crates/ui-egui/src/control/transport.rs
@@ -1,4 +1,4 @@
-use super::*;
+use super::{ControlClient, Value, json};
// ---- transport (native only) -----------------------------------------------------------------
@@ -331,7 +331,7 @@ mod transport_tests {
#[test]
fn malformed_input_before_auth_closes_the_connection() {
use std::io::{BufRead, BufReader, ErrorKind, Write};
- let (_control, client) = super::attach(&egui::Context::default());
+ let (_control, client) = crate::control::attach(&egui::Context::default());
let ep = super::serve(client).unwrap();
let s = std::net::TcpStream::connect(("127.0.0.1", ep.port)).unwrap();
s.set_read_timeout(Some(std::time::Duration::from_secs(5))).unwrap();
@@ -375,7 +375,7 @@ mod transport_tests {
#[test]
fn an_overlong_line_before_auth_is_refused() {
use std::io::{BufRead, BufReader, ErrorKind, Write};
- let (_control, client) = super::attach(&egui::Context::default());
+ let (_control, client) = crate::control::attach(&egui::Context::default());
let ep = super::serve(client).unwrap();
let s = std::net::TcpStream::connect(("127.0.0.1", ep.port)).unwrap();
s.set_read_timeout(Some(std::time::Duration::from_secs(5))).unwrap();
@@ -429,7 +429,7 @@ mod transport_tests {
#[test]
fn an_unauthenticated_connection_is_closed_at_the_deadline() {
use std::io::{BufReader, Write};
- let (_control, client) = super::attach(&egui::Context::default());
+ let (_control, client) = crate::control::attach(&egui::Context::default());
let ep = super::serve_with(client, TEST_LIMITS).unwrap();
// Idle.
let started = std::time::Instant::now();
@@ -468,7 +468,7 @@ mod transport_tests {
#[test]
fn a_client_refused_with_input_unread_gets_the_reason() {
use std::io::{BufReader, Write};
- let (_control, client) = super::attach(&egui::Context::default());
+ let (_control, client) = crate::control::attach(&egui::Context::default());
let ep = super::serve_with(client, TEST_LIMITS).unwrap();
let s = connect(ep.port);
let mut w = s.try_clone().unwrap();
@@ -488,7 +488,7 @@ mod transport_tests {
use std::io::{BufReader, Write};
// A linger far longer than the checks below take, even on a loaded machine.
let limits = super::Limits { linger: std::time::Duration::from_secs(5), ..TEST_LIMITS };
- let (_control, client) = super::attach(&egui::Context::default());
+ let (_control, client) = crate::control::attach(&egui::Context::default());
let ep = super::serve_with(client, limits).unwrap();
let auth = serde_json::json!({ "jsonrpc": "2.0", "id": 1, "method": "auth", "params": { "token": ep.token } });
// Refused with most of its line unread, and left open: it lingers for `linger`.
@@ -517,7 +517,7 @@ mod transport_tests {
use std::io::{BufReader, Write};
// A linger far longer than the checks below take, even on a loaded machine.
let limits = super::Limits { linger: std::time::Duration::from_secs(5), max_lingering: 1, ..TEST_LIMITS };
- let (_control, client) = super::attach(&egui::Context::default());
+ let (_control, client) = crate::control::attach(&egui::Context::default());
let ep = super::serve_with(client, limits).unwrap();
let bad = r#"{"jsonrpc": "2.0", "id": 1, "method": "page_count"}"#;
// The first refused connection takes the only lingering place and keeps it.
@@ -553,7 +553,7 @@ mod transport_tests {
#[test]
fn only_so_many_connections_may_wait_to_authenticate() {
use std::io::{BufReader, Write};
- let (_control, client) = super::attach(&egui::Context::default());
+ let (_control, client) = crate::control::attach(&egui::Context::default());
let ep = super::serve_with(client, TEST_LIMITS).unwrap();
let auth = serde_json::json!({ "jsonrpc": "2.0", "id": 1, "method": "auth", "params": { "token": ep.token } });
let first = connect(ep.port);
@@ -593,7 +593,7 @@ mod transport_tests {
#[test]
fn long_lines_after_auth_are_still_read() {
use std::io::{BufRead, BufReader, Write};
- let (_control, client) = super::attach(&egui::Context::default());
+ let (_control, client) = crate::control::attach(&egui::Context::default());
let ep = super::serve(client).unwrap();
let s = std::net::TcpStream::connect(("127.0.0.1", ep.port)).unwrap();
s.set_read_timeout(Some(std::time::Duration::from_secs(5))).unwrap();
diff --git a/crates/ui-egui/src/editing.rs b/crates/ui-egui/src/editing.rs
index ba2d3cbf9..4d09b5cf4 100644
--- a/crates/ui-egui/src/editing.rs
+++ b/crates/ui-egui/src/editing.rs
@@ -27,6 +27,79 @@ fn new_text_typed(v: &crate::DocView) -> bool {
v.content.draft.as_ref().is_some_and(|d| d.index.is_none() && !d.text.trim().is_empty())
}
+/// Keeps the pages (or comment) the user acted on selected, where they now are.
+fn select_after_edit(view: &mut crate::DocView, edit: Edit, info: &pdfcraft_render::DocInfo, quick_tool: crate::QuickTool) {
+ match edit {
+ Edit::MovePages { pages, to } => {
+ let n = pages.iter().collect::<std::collections::BTreeSet<_>>().len();
+ let to = to.min(info.pages.len() - n);
+ view.select_pages(&(to..to + n).collect::<Vec<_>>());
+ }
+ Edit::DuplicatePages { pages, at: Some(at) } => {
+ let n = pages.iter().collect::<std::collections::BTreeSet<_>>().len();
+ let at = at.min(info.pages.len().saturating_sub(n));
+ view.select_pages(&(at..at + n).collect::<Vec<_>>());
+ }
+ Edit::InsertBlankPage { at, .. } => view.select_pages(&[at.min(info.pages.len() - 1)]),
+ Edit::DeletePages { .. } => view.select_pages(&[]),
+ // A stroke drawn with the pen stays unselected, so the selection box and
+ // author popup don't sit over the next stroke (#429).
+ Edit::AddAnnotation(a)
+ if matches!(a.shape, pdfcraft_engine::Shape::Ink { .. })
+ && quick_tool == crate::QuickTool::Comment(crate::comments::CommentTool::Ink) =>
+ {
+ view.comments.selected = None;
+ }
+ Edit::AddAnnotation(a) => {
+ // Select the new comment (appended last among the page's comments).
+ let newest = info.annotations.iter().filter(|x| x.page == a.page && !x.is_reply()).map(|x| x.index).max();
+ view.comments.selected = newest.map(|n| (a.page, n));
+ view.comments.reveal = true;
+ // A new highlight opens its note for typing straight away, as in Acrobat,
+ // unless a note typed into another card is still unsaved.
+ if let (pdfcraft_engine::Shape::TextMarkup { kind: pdfcraft_engine::Markup::Highlight, .. }, Some(n)) = (&a.shape, newest)
+ && a.contents.is_empty()
+ && view.comments.editing.is_none()
+ {
+ view.comments.open_editor(a.page, n, String::new());
+ }
+ }
+ Edit::DeleteAnnotation { .. } => view.comments.selected = None,
+ _ => {}
+ }
+}
+
+/// The pages whose widgets differ between two form states, and the (field, page) pairs whose
+/// value changed and so must not be drawn from the baked page.
+fn form_edit_pages(
+ before: &[pdfcraft_engine::FormField],
+ after: &[pdfcraft_engine::FormField],
+) -> (std::collections::BTreeSet<usize>, Vec<(String, usize)>) {
+ let mut changed_pages = std::collections::BTreeSet::new();
+ let mut unbaked = Vec::new();
+ for f in after {
+ let pages = |field: &pdfcraft_engine::FormField| field.widgets.iter().filter_map(|w| w.page).collect::<Vec<_>>();
+ match before.iter().find(|old| old.name == f.name) {
+ Some(old) if old == f => {}
+ Some(old) => {
+ changed_pages.extend(pages(f));
+ changed_pages.extend(pages(old));
+ if old.value != f.value {
+ unbaked.extend(pages(f).into_iter().map(|p| (f.name.clone(), p)));
+ }
+ }
+ None => {
+ changed_pages.extend(pages(f));
+ unbaked.extend(pages(f).into_iter().map(|p| (f.name.clone(), p)));
+ }
+ }
+ }
+ for old in before.iter().filter(|old| !after.iter().any(|f| f.name == old.name)) {
+ changed_pages.extend(old.widgets.iter().filter_map(|w| w.page));
+ }
+ (changed_pages, unbaked)
+}
+
impl PdfCraftApp {
/// Apply an edit to the active document. Returns `true` on success; failures are shown.
pub fn apply_edit(&mut self, edit: Edit) -> bool {
@@ -68,49 +141,8 @@ impl PdfCraftApp {
&& doc.xfa.is_none()
&& is_form_edit(&edit)
{
- let mut changed_pages = std::collections::BTreeSet::new();
- for f in doc.form.iter() {
- match form_before.iter().find(|old| old.name == f.name) {
- Some(old) => {
- if old != f {
- for w in &f.widgets {
- if let Some(p) = w.page {
- changed_pages.insert(p);
- }
- }
- for w in &old.widgets {
- if let Some(p) = w.page {
- changed_pages.insert(p);
- }
- }
- if old.value != f.value {
- for w in &f.widgets {
- if let Some(p) = w.page {
- view.forms.unbaked.insert((f.name.clone(), p));
- }
- }
- }
- }
- }
- None => {
- for w in &f.widgets {
- if let Some(p) = w.page {
- changed_pages.insert(p);
- view.forms.unbaked.insert((f.name.clone(), p));
- }
- }
- }
- }
- }
- for old in form_before.iter() {
- if !doc.form.iter().any(|f| f.name == old.name) {
- for w in &old.widgets {
- if let Some(p) = w.page {
- changed_pages.insert(p);
- }
- }
- }
- }
+ let (changed_pages, unbaked) = form_edit_pages(&form_before, &doc.form);
+ view.forms.unbaked.extend(unbaked);
for page in changed_pages {
view.page_changed(page);
}
@@ -121,44 +153,7 @@ impl PdfCraftApp {
view.comments.comment_added();
}
// Keep the pages the user acted on selected, where they now are.
- match edit {
- Edit::MovePages { pages, to } => {
- let n = pages.iter().collect::<std::collections::BTreeSet<_>>().len();
- let to = to.min(info.pages.len() - n);
- view.select_pages(&(to..to + n).collect::<Vec<_>>());
- }
- Edit::DuplicatePages { pages, at: Some(at) } => {
- let n = pages.iter().collect::<std::collections::BTreeSet<_>>().len();
- let at = at.min(info.pages.len().saturating_sub(n));
- view.select_pages(&(at..at + n).collect::<Vec<_>>());
- }
- Edit::InsertBlankPage { at, .. } => view.select_pages(&[at.min(info.pages.len() - 1)]),
- Edit::DeletePages { .. } => view.select_pages(&[]),
- // A stroke drawn with the pen stays unselected, so the selection box and
- // author popup don't sit over the next stroke (#429).
- Edit::AddAnnotation(a)
- if matches!(a.shape, pdfcraft_engine::Shape::Ink { .. })
- && self.quick_tool == crate::QuickTool::Comment(crate::comments::CommentTool::Ink) =>
- {
- view.comments.selected = None;
- }
- Edit::AddAnnotation(a) => {
- // Select the new comment (appended last among the page's comments).
- let newest = info.annotations.iter().filter(|x| x.page == a.page && !x.is_reply()).map(|x| x.index).max();
- view.comments.selected = newest.map(|n| (a.page, n));
- view.comments.reveal = true;
- // A new highlight opens its note for typing straight away, as in Acrobat,
- // unless a note typed into another card is still unsaved.
- if let (pdfcraft_engine::Shape::TextMarkup { kind: pdfcraft_engine::Markup::Highlight, .. }, Some(n)) = (&a.shape, newest)
- && a.contents.is_empty()
- && view.comments.editing.is_none()
- {
- view.comments.open_editor(a.page, n, String::new());
- }
- }
- Edit::DeleteAnnotation { .. } => view.comments.selected = None,
- _ => {}
- }
+ select_after_edit(view, edit, info, self.quick_tool);
if std::mem::take(&mut view.comments.tool_done) && !self.comment_prefs.pinned {
self.quick_tool = crate::QuickTool::Select;
}
diff --git a/crates/ui-egui/src/editing/close.rs b/crates/ui-egui/src/editing/close.rs
index 5317c0ccd..55d884cd9 100644
--- a/crates/ui-egui/src/editing/close.rs
+++ b/crates/ui-egui/src/editing/close.rs
@@ -1,5 +1,5 @@
+use super::PdfCraftApp;
use super::save::SaveTarget;
-use super::*;
/// What the user was doing when we asked whether to save.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
diff --git a/crates/ui-egui/src/editing/save.rs b/crates/ui-egui/src/editing/save.rs
index 59eba1fbc..f685247c9 100644
--- a/crates/ui-egui/src/editing/save.rs
+++ b/crates/ui-egui/src/editing/save.rs
@@ -1,4 +1,4 @@
-use super::*;
+use super::{PdfCraftApp, StagingName, staging_suffixes};
/// A save held back by [`Dialog::OverwriteChanged`](crate::Dialog::OverwriteChanged): the file
/// on disk is another version than the document came from (#2166).
diff --git a/crates/ui-egui/src/panels/bookmarks.rs b/crates/ui-egui/src/panels/bookmarks.rs
index 3753c8494..ec61bf2fe 100644
--- a/crates/ui-egui/src/panels/bookmarks.rs
+++ b/crates/ui-egui/src/panels/bookmarks.rs
@@ -1,4 +1,4 @@
-use super::*;
+use super::{DocInfo, Nav, OutlineItem, Rect, Sense, Tokens, icons, pos2, theme, vec2};
/// What the user asked to do with a bookmark (applied after the panel is drawn).
#[derive(Clone, Debug, PartialEq)]
diff --git a/crates/ui-egui/src/panels/edit.rs b/crates/ui-egui/src/panels/edit.rs
index e10d0d01e..fa4cc2536 100644
--- a/crates/ui-egui/src/panels/edit.rs
+++ b/crates/ui-egui/src/panels/edit.rs
@@ -1,5 +1,8 @@
use super::tools::row_label;
-use super::*;
+use super::{
+ Align2, Availability, Color32, CornerRadius, LeftPanel, PdfCraftApp, Rect, Sense, Stroke, Tokens, ToolGroup, ToolItem, catalog, icons, theme,
+ vec2, widgets,
+};
/// The page operations Edit shows as a row of icon buttons, as Acrobat's Edit panel does.
const EDIT_PAGE_BUTTONS: [&str; 4] = ["page.rotate", "page.insert", "page.delete", "page.extract"];
diff --git a/crates/ui-egui/src/panels/pages.rs b/crates/ui-egui/src/panels/pages.rs
index e7afe45e8..1157b64a4 100644
--- a/crates/ui-egui/src/panels/pages.rs
+++ b/crates/ui-egui/src/panels/pages.rs
@@ -1,4 +1,4 @@
-use super::*;
+use super::{Align, Align2, Color32, CornerRadius, DocInfo, Layout, Nav, Rect, Sense, Stroke, Tokens, icons, pos2, theme, vec2};
/// Page tools in the Pages panel's header (#4415): a menu, as Bookmark options is in its panel,
/// to insert a blank page or pages from a file, rotate, extract and delete. Each runs its
diff --git a/crates/ui-egui/src/panels/right.rs b/crates/ui-egui/src/panels/right.rs
index 4f6c150c4..7b6502b9c 100644
--- a/crates/ui-egui/src/panels/right.rs
+++ b/crates/ui-egui/src/panels/right.rs
@@ -1,6 +1,8 @@
use super::bookmarks::{BmAction, OutlineCtx, outline_item, outline_matches};
use super::pages::{page_tools, pages, thumbnail_size};
-use super::*;
+use super::{
+ Align, Align2, Color32, DocInfo, FieldKind, Layout, Nav, PdfCraftApp, Rect, RightPanel, Sense, Stroke, Tokens, human_size, icons, theme, vec2,
+};
/// Draw the selected right-hand panel and apply its navigation, layer, bookmark or edit actions.
pub fn right_panel(app: &mut PdfCraftApp, ui: &mut egui::Ui) {
diff --git a/crates/ui-egui/src/panels/tools.rs b/crates/ui-egui/src/panels/tools.rs
index 3a1cccd71..4ff76a7c4 100644
--- a/crates/ui-egui/src/panels/tools.rs
+++ b/crates/ui-egui/src/panels/tools.rs
@@ -1,5 +1,8 @@
use super::edit::{actions_menu, edit_panel, stamp_palette};
-use super::*;
+use super::{
+ Align2, Availability, Color32, CornerRadius, LeftPanel, PdfCraftApp, Rect, Sense, Stroke, TOOL_GROUPS, Tokens, ToolGroup, catalog, icons, theme,
+ vec2, widgets,
+};
const COLLAPSED_TOOLS: usize = 14;
diff --git a/crates/ui-egui/src/platform/open_worker/tests.rs b/crates/ui-egui/src/platform/open_worker/tests.rs
index af847b9a2..fe2a0ae41 100644
--- a/crates/ui-egui/src/platform/open_worker/tests.rs
+++ b/crates/ui-egui/src/platform/open_worker/tests.rs
@@ -556,55 +556,117 @@ fn tool_picker_keeps_picked_recipient_when_other_open_is_ready() {
held.release.send(()).expect("release ordinary B");
held.finished.recv_timeout(Duration::from_secs(5)).expect("ordinary B reply is also ready");
assert_eq!(harness.state().pending_opens.len(), 2);
+ let files = PickerFiles {
+ picked: &picked,
+ other: &other,
+ insert: &insert,
+ original_a: &original_a,
+ original_b: &original_b,
+ original_c: &original_c,
+ };
+ let a_id = assert_picker_keeps_a_visible(&mut harness, &files);
+ assert_picker_completion_releases_b(&mut harness, a_id, cancel, &files);
+ }
+}
- // Poll admission separately from consuming the picker callback: this reproduces
- // the same ordering as a UI frame, with both worker replies already available.
- harness.state_mut().poll_pending_opens();
- assert_eq!(harness.state().views.len(), 1, "ready B must wait for A's Insert pages picker");
- assert_eq!(harness.state().active, Some(0));
- assert!(harness.state().dialog.is_none() && harness.state().password_prompt.is_none());
- let a_id = harness.state().views[0].id;
- let doc = harness.state().session.get(a_id).expect("picked A before picker completion");
- assert_eq!(doc.path.as_deref(), Some(picked.0.to_string_lossy().as_ref()));
+struct PickerFiles<'a> {
+ picked: &'a ToolOpenFile,
+ other: &'a ToolOpenFile,
+ insert: &'a ToolOpenFile,
+ original_a: &'a [u8],
+ original_b: &'a [u8],
+ original_c: &'a [u8],
+}
+
+fn assert_picker_keeps_a_visible(harness: &mut Harness<'static, PdfCraftApp>, files: &PickerFiles<'_>) -> pdfcraft_engine::DocId {
+ // Poll admission separately from consuming the picker callback: this reproduces
+ // the same ordering as a UI frame, with both worker replies already available.
+ harness.state_mut().poll_pending_opens();
+ assert_eq!(harness.state().views.len(), 1, "ready B must wait for A's Insert pages picker");
+ assert_eq!(harness.state().active, Some(0));
+ assert!(harness.state().dialog.is_none() && harness.state().password_prompt.is_none());
+ let a_id = harness.state().views[0].id;
+ let doc = harness.state().session.get(a_id);
+ assert!(doc.is_some(), "picked A before picker completion");
+ if let Some(doc) = doc {
+ assert_eq!(doc.path.as_deref(), Some(files.picked.0.to_string_lossy().as_ref()));
assert_eq!(doc.info.pages.len(), 2);
assert!(!doc.dirty && doc.can_undo().is_none() && doc.can_redo().is_none());
- assert_eq!(harness.state().pending_opens.len(), 1);
- assert_eq!(harness.state().pending_opens[0].path.as_deref(), Some(other.0.to_string_lossy().as_ref()));
- harness.state_mut().poll_pending_opens();
- assert_eq!(harness.state().views.len(), 1, "B remains held until the queued picker result is consumed");
- assert_eq!(harness.state().active, Some(0));
-
- // Consume the actual native-picker callback (or its empty-path cancellation).
- harness.state_mut().process_picked();
- let doc = harness.state().session.get(a_id).expect("A after picker completion");
- assert_eq!(doc.info.pages.len(), if cancel { 2 } else { 3 });
+ }
+ assert_eq!(harness.state().pending_opens.len(), 1);
+ assert_eq!(harness.state().pending_opens[0].path.as_deref(), Some(files.other.0.to_string_lossy().as_ref()));
+ harness.state_mut().poll_pending_opens();
+ assert_eq!(harness.state().views.len(), 1, "B remains held until the queued picker result is consumed");
+ assert_eq!(harness.state().active, Some(0));
+ a_id
+}
+
+fn assert_picker_completion_releases_b(
+ harness: &mut Harness<'static, PdfCraftApp>,
+ a_id: pdfcraft_engine::DocId,
+ cancel: bool,
+ files: &PickerFiles<'_>,
+) {
+ // Consume the actual native-picker callback (or its empty-path cancellation).
+ harness.state_mut().process_picked();
+ assert_document_a_after_picker(harness, a_id, cancel);
+ assert_eq!(harness.state().views.len(), 1);
+ assert_eq!(harness.state().pending_opens.len(), 1);
+ assert_eq!(harness.state().active, Some(0));
+
+ harness.step();
+ assert!(harness.state().pending_opens.is_empty());
+ assert_eq!(harness.state().views.len(), 2, "picker completion releases B exactly once");
+ let active = harness.state().active;
+ assert!(active.is_some(), "B activates after picker completion");
+ if let Some(active) = active {
+ assert_document_b_after_picker(harness, active, files);
+ }
+ harness.run_steps(2);
+ assert!(harness.state().pending_opens.is_empty() && harness.state().dialog.is_none());
+ assert_eq!(harness.state().views.len(), 2);
+ assert_eq!(harness.state().active, active);
+ assert_document_a_after_picker(harness, a_id, cancel);
+ assert_a_saved_source(harness, a_id, files.original_a);
+ assert_picker_files_unchanged(files);
+}
+
+fn assert_document_a_after_picker(harness: &Harness<'static, PdfCraftApp>, a_id: pdfcraft_engine::DocId, cancel: bool) {
+ let expected_pages = if cancel { 2 } else { 3 };
+ let doc = harness.state().session.get(a_id);
+ assert!(doc.is_some(), "A after picker completion");
+ if let Some(doc) = doc {
+ assert_eq!(doc.info.pages.len(), expected_pages);
assert_eq!(doc.dirty, !cancel);
assert_eq!(doc.can_undo().is_some(), !cancel);
assert!(doc.can_redo().is_none());
- assert_eq!(harness.state().views.len(), 1);
- assert_eq!(harness.state().pending_opens.len(), 1);
- assert_eq!(harness.state().active, Some(0));
+ }
+}
- harness.step();
- assert!(harness.state().pending_opens.is_empty());
- assert_eq!(harness.state().views.len(), 2, "picker completion releases B exactly once");
- let active = harness.state().active.expect("B activates after picker completion");
- let doc = harness.state().session.get(harness.state().views[active].id).expect("ordinary B document");
- assert_eq!(doc.path.as_deref(), Some(other.0.to_string_lossy().as_ref()));
+fn assert_document_b_after_picker(harness: &Harness<'static, PdfCraftApp>, active: usize, files: &PickerFiles<'_>) {
+ let doc = harness.state().session.get(harness.state().views[active].id);
+ assert!(doc.is_some(), "ordinary B document");
+ if let Some(doc) = doc {
+ assert_eq!(doc.path.as_deref(), Some(files.other.0.to_string_lossy().as_ref()));
assert_eq!(doc.info.pages.len(), 1);
assert!(!doc.dirty && doc.can_undo().is_none() && doc.can_redo().is_none());
- harness.run_steps(2);
- assert!(harness.state().pending_opens.is_empty() && harness.state().dialog.is_none());
- assert_eq!(harness.state().views.len(), 2);
- assert_eq!(harness.state().active, Some(active));
- let doc = harness.state().session.get(a_id).expect("A retains exactly one insertion or cancellation");
- assert_eq!(doc.info.pages.len(), if cancel { 2 } else { 3 });
- assert_eq!(doc.dirty, !cancel);
- assert_eq!(doc.can_undo().is_some(), !cancel);
- assert!(doc.can_redo().is_none());
- assert_eq!(doc.saved_bytes().as_slice(), original_a.as_slice(), "insertion preserves A's saved source");
- for (file, original) in [(&picked, &original_a), (&other, &original_b), (&insert, &original_c)] {
- assert_eq!(std::fs::read(&file.0).expect("read unchanged original picker fixture"), *original);
+ }
+}
+
+fn assert_a_saved_source(harness: &Harness<'static, PdfCraftApp>, a_id: pdfcraft_engine::DocId, original: &[u8]) {
+ let doc = harness.state().session.get(a_id);
+ assert!(doc.is_some(), "A retains exactly one insertion or cancellation");
+ if let Some(doc) = doc {
+ assert_eq!(doc.saved_bytes().as_slice(), original, "insertion preserves A's saved source");
+ }
+}
+
+fn assert_picker_files_unchanged(files: &PickerFiles<'_>) {
+ for (file, original) in [(files.picked, files.original_a), (files.other, files.original_b), (files.insert, files.original_c)] {
+ let bytes = std::fs::read(&file.0);
+ assert!(bytes.is_ok(), "read unchanged original picker fixture: {bytes:?}");
+ if let Ok(bytes) = bytes {
+ assert_eq!(bytes, original);
}
}
}
diff --git a/crates/ui-egui/tests/it/signing.rs b/crates/ui-egui/tests/it/signing.rs
index 62d97d4e5..0d8bc72de 100644
--- a/crates/ui-egui/tests/it/signing.rs
+++ b/crates/ui-egui/tests/it/signing.rs
@@ -97,23 +97,32 @@ fn ctrl_alt_q_types_an_email_without_quitting() {
fn drawing_a_signature_creating_an_id_signing_and_trusting() {
let dir = dir();
let mut h = harness(dir.clone());
+ create_signing_id(&mut h);
+ sign_with_created_id(&mut h, &dir);
+ trust_signer_and_inspect_certificate(&mut h);
+ verify_signed_snapshot_reuse(&mut h);
+ verify_dirty_snapshot_close(&mut h);
+ assert_trust_and_id_persist(&h);
+}
+
+fn create_signing_id(h: &mut Harness<'static, PdfCraftApp>) {
assert!(h.state_mut().execute("sign.digital"));
assert_eq!(h.state().quick_tool, QuickTool::SignArea { certify: false });
- let (a, b) = (at(&h, 40.0, 90.0), at(&h, 220.0, 40.0));
- drag(&mut h, a, b);
+ let (a, b) = (at(h, 40.0, 90.0), at(h, 220.0, 40.0));
+ drag(h, a, b);
assert_eq!(h.state().dialog, Some(Dialog::Sign));
assert_eq!(h.state().sign_draft.as_ref().map(|d| d.step), Some(SignStep::Configure), "no IDs yet: configure one");
// Create a new digital ID (P-256 keeps the test fast).
h.get_by_label("Configure a Digital ID for Signing");
- field(&h, "Name").click();
+ field(h, "Name").click();
h.run_steps(1);
- field(&h, "Name").type_text("Grace Hopper");
+ field(h, "Name").type_text("Grace Hopper");
h.state_mut().sign_draft.as_mut().unwrap().new_id.key = 3;
for (label, text) in [("Password", "secret12"), ("Confirm Password", "secret12")] {
- field(&h, label).click();
+ field(h, label).click();
h.run_steps(1);
- field(&h, label).type_text(text);
+ field(h, label).type_text(text);
h.run_steps(1);
}
h.get_by_label("Save").click();
@@ -124,31 +133,41 @@ fn drawing_a_signature_creating_an_id_signing_and_trusting() {
h.get_by_label("Continue").click();
h.run_steps(2);
h.get_by_label("Sign as \"Grace Hopper\"");
+}
+fn sign_with_created_id(h: &mut Harness<'static, PdfCraftApp>, dir: &std::path::Path) {
// A wrong password says so.
- field(&h, "Digital ID password").click();
+ field(h, "Digital ID password").click();
h.run_steps(1);
- field(&h, "Digital ID password").type_text("nope");
- support::outside_menus(&h, "Sign").click();
+ field(h, "Digital ID password").type_text("nope");
+ support::outside_menus(h, "Sign").click();
h.run_steps(3);
h.get_by_label("The password is incorrect.");
h.state_mut().sign_draft.as_mut().unwrap().password = "secret12".into();
- field(&h, "Reason").click();
+ field(h, "Reason").click();
h.run_steps(1);
- field(&h, "Reason").type_text("I approve");
- support::outside_menus(&h, "Sign").click();
+ field(h, "Reason").type_text("I approve");
+ support::outside_menus(h, "Sign").click();
h.run_steps(6);
let s = h.state();
assert_eq!(s.dialog, None);
assert!(dir.join("contract_signed.pdf").exists());
- let doc = s.session.get(s.views[0].id).unwrap();
- assert_eq!(doc.name, "contract_signed.pdf");
- let sig = doc.signatures.iter().find(|x| x.signed).expect("signed");
- assert_eq!((sig.status, sig.reason.as_deref(), sig.page), (SignatureStatus::Unknown, Some("I approve"), Some(0)));
+ let doc = s.session.get(s.views[0].id);
+ assert!(doc.is_some(), "signed document remains open");
+ if let Some(doc) = doc {
+ assert_eq!(doc.name, "contract_signed.pdf");
+ let signature = doc.signatures.iter().find(|signature| signature.signed);
+ assert!(signature.is_some(), "the saved document contains a signature");
+ if let Some(signature) = signature {
+ assert_eq!((signature.status, signature.reason.as_deref(), signature.page), (SignatureStatus::Unknown, Some("I approve"), Some(0)));
+ }
+ }
assert_eq!(s.right, Some(RightPanel::Signatures));
h.get_by_label("At least one signature has problems.");
+}
+fn trust_signer_and_inspect_certificate(h: &mut Harness<'static, PdfCraftApp>) {
// Signatures panel: expand, trust the signer → valid.
h.get_by_label_contains("Signed by Grace Hopper").click();
h.run_steps(2);
@@ -160,9 +179,13 @@ fn drawing_a_signature_creating_an_id_signing_and_trusting() {
h.run_steps(3);
h.get_by_label("Signed and all signatures are valid.");
let s = h.state();
- assert_eq!(s.session.get(s.views[0].id).unwrap().signatures[0].status, SignatureStatus::Valid);
+ let doc = s.session.get(s.views[0].id);
+ assert!(doc.is_some(), "the original signed document remains open");
+ if let Some(doc) = doc {
+ assert_eq!(doc.signatures[0].status, SignatureStatus::Valid);
+ assert!(!doc.dirty, "trust alone is not an edit");
+ }
assert!(s.views[0].find.as_ref().is_some_and(|f| f.matches.is_empty()), "trust invalidates the view without zooming");
- assert!(!s.session.get(s.views[0].id).unwrap().dirty, "trust alone is not an edit");
// Show certificate: the Certificate Viewer.
h.get_by_label("Show certificate…").click();
h.run_steps(3);
@@ -181,13 +204,19 @@ fn drawing_a_signature_creating_an_id_signing_and_trusting() {
h.get_by_label("OK").click();
h.run_steps(2);
assert_eq!(h.state().dialog, None);
+}
+
+fn verify_signed_snapshot_reuse(h: &mut Harness<'static, PdfCraftApp>) {
// View signed version opens the bytes the signature covers as a new document.
h.get_by_label("View signed version").click();
h.run_steps(3);
let s = h.state();
assert_eq!(s.views.len(), 2);
- let v = s.session.get(s.views[1].id).unwrap();
- assert!(v.name.contains("signed version") && v.signatures.iter().any(|x| x.signed));
+ let signed_version = s.session.get(s.views[1].id);
+ assert!(signed_version.is_some(), "the signed version opens in its own tab");
+ if let Some(version) = signed_version {
+ assert!(version.name.contains("signed version") && version.signatures.iter().any(|signature| signature.signed));
+ }
assert!(s.views[0].snapshot.is_none());
assert!(s.views[1].snapshot.as_ref().is_some_and(|snap| snap.kind == pdfcraft_ui_egui::canvas::SnapshotKind::SignedVersion));
// A repeat click reuses the snapshot tab instead of opening another identical one.
@@ -219,15 +248,20 @@ fn drawing_a_signature_creating_an_id_signing_and_trusting() {
let Some(up) = node.parent() else { break };
node = up;
}
- let close = close.expect("the notice bar holds its own Close");
+ assert!(close.is_some(), "the notice bar holds its own Close");
// The bar's Close sits in the bar's row and the tab chrome's sits above it. Without
// this the walk could reach the chrome's button, which closes the same tab, and the
// test would pass with the bar's own button never pressed.
- assert!(label_row.contains(close.rect().center().y), "the Close found is the bar's own");
- close.click();
- h.run_steps(2);
- assert_eq!(h.state().views.len(), 1);
- assert!(h.state().close_request.is_none());
+ if let Some(close) = close {
+ assert!(label_row.contains(close.rect().center().y), "the Close found is the bar's own");
+ close.click();
+ h.run_steps(2);
+ assert_eq!(h.state().views.len(), 1);
+ assert!(h.state().close_request.is_none());
+ }
+}
+
+fn verify_dirty_snapshot_close(h: &mut Harness<'static, PdfCraftApp>) {
// Closing a dirty snapshot asks about saving instead of closing at once.
h.get_by_label("View signed version").click();
h.run_steps(3);
@@ -240,6 +274,9 @@ fn drawing_a_signature_creating_an_id_signing_and_trusting() {
h.get_by_label("Don't save").click();
h.run_steps(2);
assert_eq!(h.state().views.len(), 1);
+}
+
+fn assert_trust_and_id_persist(h: &Harness<'static, PdfCraftApp>) {
// Trusted certificates and the ID list persist.
let saved = h.state().persist();
let mut fresh = PdfCraftApp::new();