Merge storytold/pdfcraft main into feat/lock-signatures-prompt

Conflicts:
- crates/ui-egui/src/workflows/js_ui.rs: main moved the Preferences dialog to
  crates/ui-egui/src/dialogs/preferences.rs (cards with search). Took main's re-export and
  carried this branch's "Otherwise, ask on the first save after a signature is placed"
  checkbox into card_fill_and_sign, disabled while flattening is on as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Pq7HyCfwzyRXj4VfQAVVdv
This commit is contained in:
mtlcl410andClaude Opus 5.5 committed 2026-11-02 21:36:45 +08:00
commit 39d760d686
28 files changed
+1980 -510

No files matched your search

+3
View File
@@ -219,6 +219,8 @@ Ranked; detail and the full milestone table in [docs/roadmap.md](docs/roadmap.md
## Progress log
- **2026-11-01 (M7, #5657):** Header/footer, watermark and background additions and replacements stage the complete call before committing. Synthetic later-page failures preserve exact incremental bytes, object count, dirty state and allocation cursor; success controls retain other marks and shared/inherited resources. Estimates unchanged.
- **2026-11-01 (M14, #5572):** Preferences ▸ Documents and view sets how many recent files to keep, from 0 to 50 with 12 by default. At 0 Home has no Recent section and File ▸ Open Recent is disabled. The list is cut when Preferences closes, so the number can pass through 0 on its way to another.
- **2026-11-01 (M5/M14, customizable hotbar, freehand highlight, and moveable navigation rail):** Added Freehand-Highlight (`/Subtype /Ink`, `/IT /FreehandHighlight`, Multiply blending, 100 pt max line width) inside the standard Highlight flyout and headless `comment_add`; added a customizable floating or side-docked hotbar with a full-side chrome strip mode, settings gear icon anchored at the bar end, and 24–64 px sizing; and added Left/Right docking for the navigation rail (`rail_side`). Focused unit and integration tests pass across `annot`, `automation`, and `ui-egui`. Estimates unchanged.
@@ -743,6 +745,7 @@ Newest first: the date, what moved, and the new overall estimate.
| Date | Change | Summary |
|---|---|---|
| 2026-11-01 | patch | M7 #5657: header/footer, watermark and background operations commit all selected pages together; later-page errors preserve marks, content, shared/inherited resources and pending edits; estimates unchanged. |
| 2026-10-28 | patch | M2, PR #4172: integrate main 5af10276 and retain both roadmap histories; viewer-only CJK and print/output font policies and estimates unchanged. |
| 2026-10-27 | minor | M10: OCR stages SHA-256-verified ONNX models after the upstream RTEN URL brownout; discovery prefers a complete ONNX pair per directory, falls back to a complete RTEN pair, and never mixes formats or directories; language/web limits and estimates unchanged. |
| 2026-10-23 | minor | M8, #3205 follow-up: phone-pattern redaction includes the +39 country code on labelled Italian geographic numbers with a slash; dates, protocol identifiers and whole-run guards remain. Estimates unchanged. |
+3
View File
@@ -180,3 +180,6 @@ sync_github_name = true
[people.dylanmtaylor]
sync_github_name = true
[people.Combiler01]
sync_github_name = true
+5 -2
View File
@@ -730,11 +730,14 @@ impl Matrix {
pub fn invert(&self) -> Option<Matrix> {
let [a, b, c, d, e, f] = self.0;
let det = a * d - b * c;
if det.abs() < 1e-12 || !det.is_finite() {
if det == 0.0 || !det.is_finite() || det.abs() <= 1e-12 * ((a * d).abs() + (b * c).abs()) {
return None;
}
let (ia, ib, ic, id) = (d / det, -b / det, -c / det, a / det);
Some(Matrix([ia, ib, ic, id, -(e * ia + f * ic), -(e * ib + f * id)]))
let inverse = [ia, ib, ic, id, -(e * ia + f * ic), -(e * ib + f * id)];
// A determinant that underflows toward zero can still pass the relative check above,
// and dividing by it overflows: such a matrix has no usable inverse.
inverse.iter().all(|v| v.is_finite()).then_some(Matrix(inverse))
}
/// The bounding box of a rectangle `[x0 y0 x1 y1]` after this transform.
+14
View File
@@ -552,3 +552,17 @@ fn inline_images_end_where_the_renderer_ends_them() {
assert_eq!((parsed.skipped, parsed.ambiguous_images), (0, 0), "{}", String::from_utf8_lossy(data));
}
}
#[test]
fn invert_accepts_small_scale_and_rejects_singular() {
let m = Matrix([1e-7, 0., 0., 1e-7, 0., 0.]);
let inv = m.invert().expect("a uniform 1e-7 scale is invertible");
let id = m.then(&inv).0;
for (got, want) in id.iter().zip(Matrix::IDENTITY.0) {
assert!((got - want).abs() < 1e-9, "{id:?}");
}
assert!(Matrix([1., 2., 2., 4., 0., 0.]).invert().is_none());
assert!(Matrix([f64::NAN, 0., 0., 1., 0., 0.]).invert().is_none());
// A subnormal scale passes the relative check but its inverse overflows (CodeRabbit on #5703).
assert!(Matrix([1e-310, 0., 0., 1., 0., 0.]).invert().is_none());
}
+29 -3
View File
@@ -7,9 +7,25 @@ use super::place::{
};
use super::{Document, EditError, Object, added, backdrop, helvetica_width};
/// Commit one complete mark operation only after every selected page succeeds. The snapshot
/// shares original bytes, cross-references, caches and unchanged objects; only the overlay table
/// and document metadata are copied. Dropping a failed stage also drops removed marks, changed
/// page/resources/backdrop dictionaries and new objects, including the allocation cursor.
fn apply_mark_transaction(doc: &mut Document, apply: impl FnOnce(&mut Document) -> Result<(), EditError>) -> Result<(), EditError> {
let mut staged = doc.clone();
apply(&mut staged)?;
*doc = staged;
Ok(())
}
/// Add a header and footer to `pages` (0-based). With `replace`, existing headers and footers on
/// those pages are removed first (Acrobat's Replace Existing).
/// those pages are removed first (Acrobat's Replace Existing). The whole call is atomic:
/// on error, the document (including earlier selected pages) is unchanged.
pub fn add_header_footer(doc: &mut Document, pages: &[usize], hf: &HeaderFooter, replace: bool, cx: &Context) -> Result<(), EditError> {
apply_mark_transaction(doc, |staged| add_header_footer_in_place(staged, pages, hf, replace, cx))
}
fn add_header_footer_in_place(doc: &mut Document, pages: &[usize], hf: &HeaderFooter, replace: bool, cx: &Context) -> Result<(), EditError> {
let all = page_list(doc);
check(pages, all.len())?;
if hf.text.iter().all(|t| t.trim().is_empty()) {
@@ -121,8 +137,13 @@ pub fn add_header_footer(doc: &mut Document, pages: &[usize], hf: &HeaderFooter,
Ok(())
}
/// Add a text watermark to `pages`.
/// Add a text or picture watermark to `pages`. All selected pages, including mark replacement,
/// form one transaction; on error, the document is unchanged.
pub fn add_watermark(doc: &mut Document, pages: &[usize], wm: &Watermark, replace: bool) -> Result<(), EditError> {
apply_mark_transaction(doc, |staged| add_watermark_in_place(staged, pages, wm, replace))
}
fn add_watermark_in_place(doc: &mut Document, pages: &[usize], wm: &Watermark, replace: bool) -> Result<(), EditError> {
let all = page_list(doc);
check(pages, all.len())?;
let text = wm.text.trim();
@@ -201,8 +222,13 @@ pub fn add_watermark(doc: &mut Document, pages: &[usize], wm: &Watermark, replac
/// Add a solid-colour background behind the content of `pages`. With `bg.replace_backdrop`, a
/// white backdrop a page paints itself is replaced first, so the background shows (see
/// [`backdrop`]); a picture backdrop (a scan) still hides it.
/// [`backdrop`]); a picture backdrop (a scan) still hides it. All selected pages, including
/// replacement and backdrop edits, form one transaction; on error, the document is unchanged.
pub fn add_background(doc: &mut Document, pages: &[usize], bg: &Background, replace: bool) -> Result<(), EditError> {
apply_mark_transaction(doc, |staged| add_background_in_place(staged, pages, bg, replace))
}
fn add_background_in_place(doc: &mut Document, pages: &[usize], bg: &Background, replace: bool) -> Result<(), EditError> {
let all = page_list(doc);
check(pages, all.len())?;
if replace {
+5
View File
@@ -1,6 +1,11 @@
//! pdfcraft-edit — page content editing (L4). Today: page marks, Acrobat's Header & footer,
//! Watermark, Background and Bates numbering (execution plan M7.6).
//!
//! **Atomic page-mark operations.** Adding or replacing headers/footers, watermarks and backgrounds
//! stages the whole call on a document snapshot and commits only after every selected page succeeds.
//! An error preserves existing marks, content, resources, pending edits and allocated objects. The
//! snapshot shares original PDF bytes and unchanged objects; it copies the overlay table and metadata.
//!
//! **How marks are stored.** Each mark is one content stream appended to (or, for content behind
//! the page, inserted after the backgrounds at the start of) the page's `/Contents`, drawn in
//! display space (after `/Rotate`) and wrapped in a marked-content artifact (§14.8.2.2) so
+211
View File
@@ -0,0 +1,211 @@
//! The public mark APIs either commit the complete operation or leave the document untouched.
use super::{cx, fixture, reopen, streams};
use crate::place::MARK_PLACEMENT_FAILURE;
use crate::*;
use pdfcraft_cos::{ObjRef, SaveOptions, write_incremental};
const SELECTED: &[usize] = &[0, 1, 2];
struct PlacementFailure;
impl PlacementFailure {
fn after_two_pages(kind: MarkKind) -> Self {
MARK_PLACEMENT_FAILURE.with(|failure| {
assert!(failure.get().is_none());
failure.set(Some((kind, 2, 0)));
});
Self
}
fn completed(&self) -> usize {
MARK_PLACEMENT_FAILURE.with(|failure| failure.get().unwrap().2)
}
}
impl Drop for PlacementFailure {
fn drop(&mut self) {
MARK_PLACEMENT_FAILURE.with(|failure| failure.set(None));
}
}
/// Four pages share an original stream and resources, both inherited and directly referenced.
/// All have all three existing marks, including a picture background with a replaced white fill.
fn marked_document() -> (Document, MarkSource) {
let mut doc = fixture();
let parent = ObjRef::new(2, 0);
let extra = doc.add(Object::Dict(Dict::from_iter([
(b"Type".to_vec(), Object::name("Page")),
(b"Parent".to_vec(), Object::Ref(parent)),
(b"Contents".to_vec(), Object::Ref(ObjRef::new(7, 0))),
])));
doc.update_dict(parent, |d| {
d.set(b"Kids".to_vec(), Object::Array([3, 4, 5].map(|n| Object::Ref(ObjRef::new(n, 0))).into_iter().chain([Object::Ref(extra)]).collect()));
d.set(b"Count".to_vec(), Object::Int(4));
})
.unwrap();
doc.set(ObjRef::new(7, 0), Object::Stream(Stream::from_raw(Dict::new(), b"1 g 0 0 600 800 re f 0 g BT /F1 9 Tf (Original page) Tj ET".to_vec())));
let picture = |doc: &mut Document, gray| {
let image = doc.add(Object::Stream(Stream::from_raw(
Dict::from_iter([
(b"Type".to_vec(), Object::name("XObject")),
(b"Subtype".to_vec(), Object::name("Image")),
(b"Width".to_vec(), Object::Int(1)),
(b"Height".to_vec(), Object::Int(1)),
(b"ColorSpace".to_vec(), Object::name("DeviceGray")),
(b"BitsPerComponent".to_vec(), Object::Int(8)),
]),
vec![gray],
)));
MarkSource { xobject: image, size: (1.0, 1.0), image: true }
};
let old_picture = picture(&mut doc, 170);
let replacement_picture = picture(&mut doc, 80);
let all = [0, 1, 2, 3];
let hf = HeaderFooter {
text: ["Old header".into(), String::new(), String::new(), String::new(), String::new(), String::new()],
font: added::Family::Times,
..Default::default()
};
add_header_footer(&mut doc, &all, &hf, false, &cx()).unwrap();
add_watermark(&mut doc, &all, &Watermark { text: "Old watermark".into(), opacity: 0.45, ..Default::default() }, false).unwrap();
add_background(&mut doc, &all, &Background { source: Some(old_picture), opacity: 0.6, replace_backdrop: true, ..Default::default() }, false)
.unwrap();
let pages = page_list(&doc);
let shared = ObjRef::new(6, 0);
let resources = (*doc.resolve(pages[0].dict.get(b"Resources").unwrap())).clone();
doc.set(shared, resources);
for (i, page) in pages.iter().enumerate() {
doc.update_dict(page.obj, |d| {
if i % 2 == 0 {
d.set(b"Resources".to_vec(), Object::Ref(shared));
} else {
d.remove(b"Resources");
}
})
.unwrap();
}
let doc = reopen(&doc);
assert!(!doc.is_modified());
let pages = page_list(&doc);
assert_eq!(pages.len(), 4);
assert!(doc.get(pages[1].obj).as_dict().unwrap().get(b"Resources").is_none(), "a selected page inherits its resources");
assert_eq!(pages[0].dict.get(b"Resources").and_then(Object::as_ref), Some(shared));
assert_eq!(pages[2].dict.get(b"Resources").and_then(Object::as_ref), Some(shared));
for i in 0..4 {
for kind in [MarkKind::HeaderFooter, MarkKind::Watermark, MarkKind::Background] {
assert_eq!(mark_streams(&doc, i, kind).len(), 1, "page {i} has existing {kind:?}");
}
}
(doc, replacement_picture)
}
fn mark_streams(doc: &Document, page: usize, kind: MarkKind) -> Vec<String> {
streams(doc, page).into_iter().filter(|s| s.contains(&format!("/PCMark /{}", kind.tag()))).collect()
}
fn apply_replacement(doc: &mut Document, kind: MarkKind, source: MarkSource, replace: bool) -> Result<(), EditError> {
match kind {
MarkKind::HeaderFooter => add_header_footer(
doc,
SELECTED,
&HeaderFooter {
text: ["New header".into(), String::new(), String::new(), String::new(), String::new(), String::new()],
font: added::Family::Courier,
shrink: true,
..Default::default()
},
replace,
&cx(),
),
MarkKind::Watermark => add_watermark(doc, SELECTED, &Watermark { source: Some(source), opacity: 0.25, ..Default::default() }, replace),
MarkKind::Background => {
add_background(doc, SELECTED, &Background { color: [0.1, 0.3, 0.7], replace_backdrop: true, ..Default::default() }, replace)
}
}
}
fn unchanged_after_later_page_failure(kind: MarkKind) {
// Replacement and addition share the same operation boundary; exercise replacement first.
for (replace, pending_edit) in [(true, false), (true, true), (false, false), (false, true)] {
let (mut doc, source) = marked_document();
if pending_edit {
let pending = doc.add(Object::String(pdfcraft_cos::PdfString::literal(b"unsaved caller edit".to_vec())));
doc.update_dict(page_list(&doc)[0].obj, |d| d.set(b"CallerEdit".to_vec(), Object::Ref(pending))).unwrap();
}
let modified = doc.is_modified();
let before = write_incremental(&doc, &SaveOptions::default()).unwrap();
let objects = doc.object_numbers().len();
let mut allocation_probe = doc.clone();
let next_object = allocation_probe.add(Object::Null);
let failure = PlacementFailure::after_two_pages(kind);
let result = apply_replacement(&mut doc, kind, source, replace);
assert_eq!(result, Err(EditError::Invalid("injected mark placement failure".into())));
assert_eq!(failure.completed(), 2, "the error followed two real page placements");
assert_eq!(doc.object_numbers().len(), objects, "{kind:?}, replace={replace}: no allocated objects remain");
assert_eq!(doc.is_modified(), modified, "{kind:?}, replace={replace}: the dirty state is preserved");
assert!(write_incremental(&doc, &SaveOptions::default()).unwrap() == before, "{kind:?}, replace={replace}: every byte stays unchanged");
assert_eq!(doc.add(Object::Null), next_object, "the allocation cursor is unchanged too");
}
}
#[test]
fn header_footer_changes_are_atomic_after_a_later_page_failure() {
unchanged_after_later_page_failure(MarkKind::HeaderFooter);
}
#[test]
fn watermark_changes_are_atomic_after_a_later_page_failure() {
unchanged_after_later_page_failure(MarkKind::Watermark);
}
#[test]
fn background_changes_are_atomic_after_a_later_page_failure() {
unchanged_after_later_page_failure(MarkKind::Background);
}
#[test]
fn replacements_commit_all_selected_pages_and_preserve_other_marks_and_shared_resources() {
for kind in [MarkKind::HeaderFooter, MarkKind::Watermark, MarkKind::Background] {
let (mut doc, source) = marked_document();
let before = doc.clone();
let expected = match kind {
MarkKind::HeaderFooter => "(New header)".to_string(),
MarkKind::Watermark => format!("/PCPic{} Do", source.xobject.num),
MarkKind::Background => "0.1 0.3 0.7 rg".to_string(),
};
apply_replacement(&mut doc, kind, source, true).unwrap();
let doc = reopen(&doc);
assert_eq!(streams(&doc, 3), streams(&before, 3), "the unselected page keeps its content");
let unselected = page_list(&before)[3].obj;
assert_eq!(doc.get(unselected), before.get(unselected), "the unselected page keeps its resources and entries");
for reference in [ObjRef::new(6, 0), ObjRef::new(7, 0)] {
assert_eq!(
format!("{:?}", doc.get(reference)),
format!("{:?}", before.get(reference)),
"shared resources and original content stay unchanged"
);
}
for page in SELECTED {
let marks = mark_streams(&doc, *page, kind);
assert_eq!(marks.len(), 1, "one replacement on selected page {page}");
assert!(marks[0].contains(&expected), "the new mark is present: {}", marks[0]);
let old_page = &page_list(&before)[*page];
let new_page = &page_list(&doc)[*page];
let old_resources = before.resolve(old_page.dict.get(b"Resources").unwrap());
let new_resources = doc.resolve(new_page.dict.get(b"Resources").unwrap());
for category in [&b"Font"[..], &b"ExtGState"[..], &b"XObject"[..]] {
let old = before.resolve(old_resources.as_dict().unwrap().get(category).unwrap());
let new = doc.resolve(new_resources.as_dict().unwrap().get(category).unwrap());
for (name, value) in old.as_dict().unwrap().iter() {
assert_eq!(new.as_dict().unwrap().get(name), Some(value), "old resources remain usable on page {page}");
assert_eq!(doc.resolve(value), before.resolve(value), "referenced resource contents are unchanged on page {page}");
}
}
for other in [MarkKind::HeaderFooter, MarkKind::Watermark, MarkKind::Background] {
if other != kind {
assert_eq!(mark_streams(&doc, *page, other), mark_streams(&before, *page, other), "unrelated {other:?} on page {page}");
}
}
}
}
}
+26 -1
View File
@@ -294,7 +294,32 @@ pub(crate) fn isolation(doc: &Document, list: &[Object]) -> Isolation {
/// Put a mark's content on a page: behind (with the behind-marks at the start) or on top
/// (appended, after wrapping the original content in q/Q).
pub(crate) fn place(doc: &mut Document, page: &pdfcraft_model::Page, kind: MarkKind, content: Vec<u8>, behind: bool) -> Result<(), EditError> {
place_tagged(doc, page, kind.tag(), content, behind).map(drop)
place_tagged(doc, page, kind.tag(), content, behind)?;
#[cfg(test)]
fail_after_mark_placement(kind)?;
Ok(())
}
#[cfg(test)]
thread_local! {
/// Force an error after N completed placements of one kind, on this test thread only.
pub(crate) static MARK_PLACEMENT_FAILURE: std::cell::Cell<Option<(MarkKind, usize, usize)>> = const { std::cell::Cell::new(None) };
}
#[cfg(test)]
fn fail_after_mark_placement(kind: MarkKind) -> Result<(), EditError> {
MARK_PLACEMENT_FAILURE.with(|failure| {
if let Some((target, after, completed)) = failure.get()
&& target == kind
{
let completed = completed.saturating_add(1);
failure.set(Some((target, after, completed)));
if completed == after {
return Err(EditError::Invalid("injected mark placement failure".into()));
}
}
Ok(())
})
}
/// Put content on a page, tagged `tag` (see [`place`]). On top, whatever graphics state the
+3
View File
@@ -4,6 +4,9 @@ use pdfcraft_cos::{Document, SaveOptions, write_full, write_incremental};
use super::*;
#[path = "mark_transaction_tests.rs"]
mod mark_transactions;
/// Three pages: an upright page with content that leaves the graphics state changed (an
/// unbalanced `cm`), a page rotated 90° and one with inherited, shared resources.
fn fixture() -> Document {
+93
View File
@@ -8491,6 +8491,99 @@ mod devicen_inks;
// patch 27).
mod isolated_cmyk_groups;
/// The generation-0 stand-in a rebuilt table files an object under must not make the object a
/// second object: enumeration yielded it once per key, so a document recovered without a readable
/// page tree reported the page twice (noted in review of #5580).
///
/// And a later header for the same object number replaces the stand-in, so `N 0 R` cannot be left
/// pointing at a body the exact key no longer names.
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn a_rebuilt_tables_generation_0_stand_in_is_not_a_second_object() {
// No table, no `startxref`, and no readable page tree: the pages are recovered by looking for
// objects that are pages, which is where a doubled object shows up as a doubled page.
let pdf = "%PDF-1.4\n\
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\
3 99999 obj << /Type /Page /MediaBox [0 0 200 100] /Contents 4 0 R >> endobj\n\
4 0 obj << /Length 0 >> stream\n\nendstream endobj\n\
trailer << /Root 1 0 R >>\n\
%%EOF\n";
let mut r = PageRenderer::new(Arc::new(pdf.to_string().into_bytes()), RenderConfig::default());
let first = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0, preview: false });
assert!(first.error.is_none(), "the page is recovered: {:?}", first.error);
let second = r.render(RenderRequest { page: 1, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0, preview: false });
assert!(second.error.is_some(), "and it is one page, not two: page 2 must not exist");
// Two headers for object 3, the second the one the exact key names: the stand-in follows it.
// `(B)` is drawn by the later body, so the page that comes back says which one was read.
let twice = "%PDF-1.4\n\
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\
3 1 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] /Contents 5 0 R >> endobj\n\
3 1 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 300 150] /Contents 5 0 R >> endobj\n\
5 0 obj << /Length 0 >> stream\n\nendstream endobj\n\
trailer << /Root 1 0 R >>\n\
%%EOF\n";
let mut r = PageRenderer::new(Arc::new(twice.to_string().into_bytes()), RenderConfig::default());
let page = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0, preview: false });
assert!(page.error.is_none(), "the page is found: {:?}", page.error);
assert_eq!((page.width, page.height), (300, 150), "`3 0 R` reads the later body, as `3 1` does");
}
/// A file whose cross-reference table has to be rebuilt keeps an object whose header names a
/// generation the reference does not.
///
/// `poppler-85140-0.pdf` is 340 bytes with no table at all, and its one page's header reads
/// `3 18446744073709551616 obj` while the page tree points at `3 0 R`. Before #427 the digits
/// wrapped, and 2^64 wrapped to exactly 0, so the header read as `3 0 obj` and the file opened by
/// accident; once an overflowing integer became a real the object was unreachable and the file
/// stopped opening at all, which `cargo xtask check` reports as a regression (#5580).
///
/// A rebuilt table has no revision history to tell two generations of an object apart -- the scan
/// already files objects found in object streams under generation 0 -- so the object number is
/// what identifies one. A readable generation that simply is not the one referenced
/// (`3 99999 obj`) was lost the same way, and is covered here too.
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn a_rebuilt_table_finds_an_object_whose_header_names_another_generation() {
for generation in [
// The generation the reference names, which always worked.
"0",
// One that reads as an integer but is not the one referenced.
"99999",
// And one no generation may be: 2^64, which is what the reported file carries. A
// generation number is at most 65,535 (ISO 32000-2 §7.5.4).
"18446744073709551616",
] {
// No table and no `startxref`, so the objects are recovered by scanning the file.
let pdf = format!(
"%PDF-1.4\n\
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\
3 {generation} obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] >> endobj\n\
trailer << /Root 1 0 R >>\n\
%%EOF\n"
);
let mut r = PageRenderer::new(Arc::new(pdf.into_bytes()), RenderConfig::default());
let page = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0, preview: false });
assert!(page.error.is_none(), "generation {generation}: the page is found: {:?}", page.error);
assert_eq!((page.width, page.height), (200, 100), "generation {generation}: and it is the page's own size");
}
// A stray number before a header (`42 3 0 obj`) is not a header, and must not cost the one
// after it: the lenient read leaves the scan where it was when it fails (noted in review).
let pdf = "%PDF-1.4\n\
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\
2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\
42 3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] >> endobj\n\
trailer << /Root 1 0 R >>\n\
%%EOF\n";
let mut r = PageRenderer::new(Arc::new(pdf.to_string().into_bytes()), RenderConfig::default());
let page = r.render(RenderRequest { page: 0, kind: RequestKind::Pixels, tile: None, scale: 1.0, tag: 0, preview: false });
assert!(page.error.is_none(), "the header after a stray number is found: {:?}", page.error);
assert_eq!((page.width, page.height), (200, 100));
}
/// #3109 / #3116: clipping-only text (`7 Tr`) installs a clip for subsequent painting
/// but draws no pixels itself.
#[test]
+2
View File
@@ -149,6 +149,7 @@ impl PdfCraftApp {
#[cfg(all(test, not(target_arch = "wasm32")))]
open_prepare_gate: None,
pinned: Default::default(),
recent_check: Default::default(),
pinned_tools: Vec::new(),
pin_tool_search: String::new(),
toast: None,
@@ -457,6 +458,7 @@ impl eframe::App for PdfCraftApp {
}
self.poll_pending_opens();
}
self.check_restored_recent();
// Chinese wants its own faces before the Japanese ones (one baseline per line).
let cjk = theme::CjkPreference::for_language(lang.code());
if !self.styled {
+1
View File
@@ -332,6 +332,7 @@ impl PdfCraftApp {
#[cfg(target_os = "macos")]
macos_association::repair(std::path::Path::new(&p));
self.recent.retain(|r| r.path != p);
self.recent_check.opened(&p);
self.recent.insert(0, RecentFile { name: name.to_string(), path: p, pages, size });
self.recent.truncate(self.recent_limit);
}
+3 -3
View File
@@ -183,9 +183,9 @@ impl PdfCraftApp {
self.organize_zoom = zoom.clamp(*canvas::GRID_ZOOM_RANGE.start(), *canvas::GRID_ZOOM_RANGE.end());
}
if let Ok(r) = serde_json::from_value::<Vec<RecentFile>>(v["recent"].clone()) {
// Only keep entries whose files still exist.
#[cfg(not(target_arch = "wasm32"))]
let r: Vec<RecentFile> = r.into_iter().filter(|f| std::path::Path::new(&f.path).exists()).collect();
// Entries whose files are gone leave once the window is up: asking here could block
// startup on a mount that has stopped answering (#5682).
self.recent_check.restored(r.iter().map(|f| f.path.clone()).collect());
self.recent = r;
}
// Nonsense keeps the limit it had; settings from before the limit have none.
+16 -3
View File
@@ -14,6 +14,7 @@ pub(super) mod credits;
pub(super) mod marks_ui;
pub(super) mod pageboxes;
pub(super) mod palette;
pub(super) mod preferences;
mod prompts;
pub(super) mod protect;
pub(super) mod standards_ui;
@@ -128,6 +129,7 @@ fn dialogs(app: &mut PdfCraftApp, ctx: &egui::Context) {
Dialog::Properties(_) => 640.0,
Dialog::Print => 820.0,
Dialog::FieldProps | Dialog::BulkFieldProps => 600.0,
Dialog::Preferences => 610.0,
Dialog::About => 780.0,
Dialog::PinTool => 540.0,
_ => 520.0,
@@ -1387,10 +1389,13 @@ fn dialog_signature(ui: &mut egui::Ui, app: &mut PdfCraftApp, req: &mut Pending)
/// `Dialog::Preferences` content. Returns `false` when it has its own buttons and no footer is wanted.
fn dialog_preferences(ui: &mut egui::Ui, app: &mut PdfCraftApp, req: &mut Pending) -> bool {
ui.set_width(610.0);
let t = Tokens::get(ui.ctx());
preferences::preferences_header(ui, &t);
ui.add_space(10.0);
// The settings outgrow a short window: scroll them rather than run off the screen.
// The OK row stays below the scroll, in reach however far the settings are scrolled.
let max = (ui.ctx().content_rect().height() - 120.0 - crate::js_ui::PREFERENCES_BUTTON_ROW).max(crate::js_ui::PREFERENCES_MIN_SCROLL);
let max = (ui.ctx().content_rect().height() - 120.0 - preferences::PREFERENCES_BUTTON_ROW - 40.0).max(preferences::PREFERENCES_MIN_SCROLL);
// A scroll area starts from the room the dialog offers it, and a modal offers more
// each frame for the first few, so with OK outside the scroll the dialog would grow
// over those frames. Asking for the full height as the least it may scroll in
@@ -1399,9 +1404,17 @@ fn dialog_preferences(ui: &mut egui::Ui, app: &mut PdfCraftApp, req: &mut Pendin
// cards and other full-width rows (#3557).
ui.scope(|ui| {
ui.spacing_mut().scroll.floating = false;
egui::ScrollArea::vertical().max_height(max).min_scrolled_height(max).show(ui, |ui| crate::js_ui::preferences_body(ui, app, &t));
ui.spacing_mut().scroll.bar_inner_margin = 14.0;
ui.spacing_mut().scroll.bar_outer_margin = 2.0;
ui.style_mut().scroll_animation = egui::style::ScrollAnimation::duration(0.25);
egui::ScrollArea::vertical()
.id_salt("preferences-dialog-scroll")
.max_height(max)
.min_scrolled_height(max)
.animated(true)
.show(ui, |ui| preferences::preferences_body(ui, app, &t));
});
req.close = crate::js_ui::preferences_buttons(ui);
req.close = preferences::preferences_buttons(ui);
false
}
+76 -41
View File
@@ -1,11 +1,10 @@
//! Preferences › Appearance: the appearance mode (follow the system, light or dark) above a light
//! and a dark theme card, each with a small picture of PdfCraft in that theme.
use egui::{Rect, RichText, pos2, vec2};
use egui::{CornerRadius, Rect, RichText, Stroke, pos2, vec2};
use crate::PdfCraftApp;
use crate::theme::{self, ThemeKind, ThemePreference, Tokens};
use crate::widgets;
/// The themes each card offers. One of each today; a new theme is one more row here.
pub const LIGHT_THEMES: &[(ThemeKind, &str)] = &[(ThemeKind::Light, "Light gray")];
@@ -82,43 +81,70 @@ fn preview(ui: &mut egui::Ui, kind: ThemeKind, width: f32) {
}
}
/// One theme card: its title, Active when it is what shows now, a preview of the chosen theme
/// and a radio row per theme. Returns true when the card or one of its radio rows was clicked.
fn card(ui: &mut egui::Ui, t: &Tokens, title: &str, active: bool, themes: &[(ThemeKind, &str)]) -> bool {
let inner = egui::Frame::new()
.fill(t.card)
.stroke(egui::Stroke::new(1.0, if active { t.accent } else { t.border }))
.corner_radius(6.0)
.inner_margin(egui::Margin::same(8))
.show(ui, |ui| {
ui.set_width(ui.available_width());
ui.horizontal(|ui| {
ui.label(RichText::new(title).font(theme::semibold(12.5)).color(t.text));
if active {
ui.label(RichText::new(tl!("Active")).color(t.accent_text).small());
}
});
ui.add_space(4.0);
let shown = themes.first().map_or(ThemeKind::Light, |(kind, _)| *kind);
preview(ui, shown, ui.available_width());
ui.add_space(4.0);
let mut clicked = false;
for (kind, label) in themes {
// One theme per card today, so it is always the chosen one.
clicked |= ui.add(widgets::radio(*kind == shown, tl!(label))).clicked();
}
clicked
});
// The whole card picks its theme, not just the radio row.
let whole = inner.response.interact(egui::Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand);
inner.inner || whole.clicked()
/// One theme card: its title, Active when it is what shows now, and a preview of the chosen theme.
/// Returns whether the card was clicked and the control's Response.
fn card(ui: &mut egui::Ui, t: &Tokens, title: &str, active: bool, themes: &[(ThemeKind, &str)], query: &str) -> (bool, egui::Response) {
let mut card_clicked = false;
let frame_stroke = if active { Stroke::new(1.5, t.accent) } else { Stroke::new(1.0, t.border) };
let scope_res = ui.scope_builder(egui::UiBuilder::new().id_salt(title).sense(egui::Sense::click()), |ui| {
egui::Frame::new().fill(t.card).stroke(frame_stroke).corner_radius(CornerRadius::same(6)).inner_margin(egui::Margin::same(8)).show(
ui,
|ui| {
ui.set_width(ui.available_width());
ui.horizontal(|ui| {
let font = theme::semibold(12.5);
let ranges = crate::dialogs::preferences::find_match_ranges(title, query);
let galley = if ranges.is_empty() {
crate::bidi::layout_ui(ui, title.to_owned(), font, t.text)
} else {
let (job, _) = crate::dialogs::preferences::create_highlight_job(title, &ranges, font, t.text);
ui.painter().layout_job(job)
};
let (title_rect, _) = ui.allocate_exact_size(galley.size(), egui::Sense::hover());
ui.painter().galley(title_rect.min, galley, t.text);
if active {
ui.label(RichText::new(tl!("Active")).color(t.accent_text).small());
}
});
ui.add_space(4.0);
let shown = themes.first().map_or(ThemeKind::Light, |(kind, _)| *kind);
preview(ui, shown, ui.available_width());
},
);
});
let resp = scope_res.response;
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, true, active, title));
if resp.has_focus() {
ui.painter().rect_stroke(resp.rect, CornerRadius::same(6), Stroke::new(2.0, t.accent_text), egui::StrokeKind::Outside);
}
let resp = theme::hand(resp);
let key_select = resp.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Space) || i.key_pressed(egui::Key::Enter));
if resp.clicked() || key_select {
card_clicked = true;
}
(card_clicked, resp)
}
/// The Appearance section of Preferences.
#[cfg_attr(not(test), expect(dead_code, reason = "called by unit tests"))]
pub fn preferences_section(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) {
ui.label(RichText::new(tl_ctx!("theme", "Appearance")).font(theme::semibold(13.0)));
let mut ctx = crate::dialogs::preferences::PrefSearchContext::new("", false);
preferences_section_with_context(ui, app, t, &mut ctx);
}
/// The Appearance section of Preferences with live search highlighting and scrolling context.
pub(crate) fn preferences_section_with_context(
ui: &mut egui::Ui,
app: &mut PdfCraftApp,
t: &Tokens,
ctx: &mut crate::dialogs::preferences::PrefSearchContext,
) {
ctx.label(ui, tl_ctx!("theme", "Appearance"), theme::semibold(13.0), t.text);
ui.horizontal(|ui| {
let label = ui.label(tl!("Appearance mode"));
let label = ctx.label(ui, tl!("Appearance mode"), theme::regular(13.0), t.text);
let combo = craft_ui::ComboBox::from_id_salt("appearance-mode").selected_text(tl!(mode_label(app.theme_preference))).show_ui(ui, |ui| {
for preference in [ThemePreference::System, ThemePreference::Light, ThemePreference::Dark] {
if ui.selectable_label(app.theme_preference == preference, tl!(mode_label(preference))).clicked() {
@@ -132,18 +158,29 @@ pub fn preferences_section(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens)
});
ui.add_space(4.0);
let light_active = app.theme == ThemeKind::Light;
let light_title = tl!("Light theme");
let dark_title = tl!("Dark theme");
let light_matches = crate::dialogs::preferences::find_match_ranges(light_title, ctx.query).len();
let dark_matches = crate::dialogs::preferences::find_match_ranges(dark_title, ctx.query).len();
ctx.total_matches += light_matches + dark_matches;
ui.columns(2, |cols| {
let [light, dark] = cols else { return };
if card(light, t, tl!("Light theme"), light_active, LIGHT_THEMES) {
let (light_clicked, light_resp) = card(light, t, light_title, light_active, LIGHT_THEMES, ctx.query);
if light_clicked {
app.execute(mode_command(ThemePreference::Light));
}
if card(dark, t, tl!("Dark theme"), !light_active, DARK_THEMES) {
ctx.scroll_if_first_match(&light_resp, light_matches);
let (dark_clicked, dark_resp) = card(dark, t, dark_title, !light_active, DARK_THEMES, ctx.query);
if dark_clicked {
app.execute(mode_command(ThemePreference::Dark));
}
ctx.scroll_if_first_match(&dark_resp, dark_matches);
});
ui.add_space(4.0);
// Acrobat's "Highlight existing fields": shared with the toggle in the form bar.
ui.add(crate::widgets::checkbox(&mut app.view_defaults.highlight_fields, tl!("Highlight fields")));
ctx.checkbox(ui, &mut app.view_defaults.highlight_fields, tl!("Highlight fields"), t);
}
#[cfg(test)]
@@ -175,7 +212,6 @@ mod tests {
);
h.run();
assert!(h.query_by_label("Light theme").is_some() && h.query_by_label("Dark theme").is_some());
assert!(h.query_by_label("Light gray").is_some() && h.query_by_label("Dark gray").is_some());
assert_eq!(h.query_all_by_label("Active").count(), 1);
if let Ok(path) = std::env::var("PDFCRAFT_APPEARANCE_SHOT") {
h.render().unwrap().save(path).unwrap();
@@ -200,7 +236,7 @@ mod tests {
assert_eq!(h.state().theme_preference, ThemePreference::System);
}
/// Clicking a theme card, or its radio row, picks that theme, not only the mode combo box.
/// Clicking a theme card picks that theme, not only the mode combo box.
#[test]
fn clicking_a_theme_card_picks_that_theme() {
let mut app = PdfCraftApp::new();
@@ -219,10 +255,9 @@ mod tests {
app,
);
h.run();
h.get_by_label("Dark gray").click();
h.get_by_label("Dark theme").click();
h.run();
assert_eq!((h.state().theme_preference, h.state().theme), (ThemePreference::Dark, ThemeKind::Dark));
// The card's title is not a widget of its own: the click lands on the card.
h.get_by_label("Light theme").click();
h.run();
assert_eq!((h.state().theme_preference, h.state().theme), (ThemePreference::Light, ThemeKind::Light));
File diff suppressed because it is too large. Load diff
+2
View File
@@ -405,6 +405,8 @@ pub struct PdfCraftApp {
open_prepare_gate: Option<std::sync::Arc<open_worker::PrepareGate>>,
/// Folders pinned to Home, and what they held when last listed.
pub pinned: folders_ui::PinnedFolders,
/// The recent files restored from settings, checked off the UI thread (#5682).
recent_check: persist::recent_check::RecentCheck,
/// Tools pinned to Home, in user-defined order.
pub pinned_tools: Vec<String>,
/// Search query for the Pin a tool selection dialog.
+10 -1
View File
@@ -22,7 +22,9 @@ pub(crate) fn parse(text: &str, count: usize) -> Result<Vec<usize>, PrintError>
let mut pages = BTreeSet::new();
let mut budget = 1_000_000usize;
let number = |token: &str| {
let n = token.trim().parse::<usize>().map_err(|_| PrintError::NotAPage(token.into()))?;
let t = token.trim();
let n =
if t.bytes().all(|b| b.is_ascii_digit()) { t.parse::<usize>().ok() } else { None }.ok_or_else(|| PrintError::NotAPage(token.into()))?;
if n == 0 || n > count { Err(PrintError::OutOfRange(n, count)) } else { Ok(n - 1) }
};
for part in text.split([',', ';']).map(str::trim) {
@@ -132,6 +134,13 @@ impl PageSelectionInput {
mod tests {
use super::*;
#[test]
fn plus_sign_is_not_a_page_number() {
for text in ["+3", "+2-4", "2-+4"] {
assert!(matches!(parse(text, 100), Err(PrintError::NotAPage(_))), "{text}");
}
}
#[test]
fn selection_ranges_are_sorted_unique_and_bounded() {
let pages = parse("1,12,16-18,89,92,93,97,99", 100).unwrap();
+1
View File
@@ -1,6 +1,7 @@
pub mod last_session;
pub mod last_view;
pub mod paper;
pub(crate) mod recent_check;
pub(super) mod recovery;
pub mod units;
#[cfg(not(target_arch = "wasm32"))]
+125
View File
@@ -0,0 +1,125 @@
//! Recent files whose files are gone leave the list, without the window waiting to find out
//! (#5682).
//!
//! A recent file can be on a network or cloud mount that has stopped answering, where even
//! asking whether the file exists blocks in the kernel, and no timeout can cancel that. So
//! settings keep every recent entry when they load, and a worker asks about them once the window
//! is up; each frame only takes the answers it has so far. An entry the worker hasn't reached
//! yet, or can't tell about (the mount answers with an error), stays listed and can be opened or
//! removed by hand. A worker stuck on a dead mount stays stuck, but nothing waits for it.
use std::sync::{Arc, Mutex, PoisonError};
use crate::PdfCraftApp;
/// The recent files restored from settings that haven't been checked yet, and the check under way.
#[derive(Debug, Default)]
pub struct RecentCheck {
/// Paths restored from settings, checked on the next frame.
unchecked: Vec<String>,
/// The paths the worker has found gone so far; it adds to them as it goes.
gone: Option<Arc<Mutex<Vec<String>>>>,
/// Paths opened while a check was pending: the file is there now, whatever the worker found.
opened: Vec<String>,
}
impl RecentCheck {
/// Settings just restored these recent files: check them once the window is up.
pub(crate) fn restored(&mut self, paths: Vec<String>) {
self.unchecked = paths;
}
/// `path` was just opened: an answer the worker gives about it later is out of date.
pub(crate) fn opened(&mut self, path: &str) {
if self.gone.is_some() || !self.unchecked.is_empty() {
self.opened.push(path.to_string());
}
}
}
/// Whether `path` is known to be gone. Any other answer, an error included, keeps the entry.
fn gone(path: &str) -> bool {
matches!(std::fs::exists(path), Ok(false))
}
impl PdfCraftApp {
/// Start checking the recent files restored from settings, and drop the ones found gone so
/// far (called each frame). The check runs on a worker thread, inline in tests
/// ([`PdfCraftApp::run_inline`]).
pub(crate) fn check_restored_recent(&mut self) {
let paths = std::mem::take(&mut self.recent_check.unchecked);
// The web build's recent files aren't paths on a file system.
if !paths.is_empty() && !cfg!(target_arch = "wasm32") {
let slot = Arc::new(Mutex::new(Vec::new()));
let out = slot.clone();
let ctx = self.ctx.clone();
let work = move || {
for path in paths {
if gone(&path) {
out.lock().unwrap_or_else(PoisonError::into_inner).push(path);
if let Some(ctx) = &ctx {
ctx.request_repaint();
}
}
}
};
if self.run_inline {
work();
} else if std::thread::Builder::new().name("pdfcraft-recent".into()).spawn(work).is_err() {
// No worker: the entries stay listed, as if the check hadn't reached them.
return;
}
self.recent_check.gone = Some(slot);
}
let Some(slot) = &self.recent_check.gone else { return };
// Asked before taking, so a path the worker adds after this is taken on a later frame.
let finished = Arc::strong_count(slot) == 1;
let gone = std::mem::take(&mut *slot.lock().unwrap_or_else(PoisonError::into_inner));
if !gone.is_empty() {
// A file opened since the check began is there, whatever the worker found earlier.
let opened = &self.recent_check.opened;
self.recent.retain(|r| !gone.contains(&r.path) || opened.contains(&r.path));
}
// The worker has finished (or panicked) and everything it found is taken.
if finished {
self.recent_check.gone = None;
self.recent_check.opened.clear();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A file opened after the worker found it gone, but before that answer was taken, stays
/// listed (CodeRabbit on #5692).
#[test]
fn a_file_opened_while_the_check_is_pending_stays() {
let mut app = PdfCraftApp::new();
app.recent = vec![crate::state::RecentFile { name: "a.pdf".into(), path: "/gone/a.pdf".into(), pages: 1, size: 0 }];
// The worker's answer is waiting: it found the file gone.
app.recent_check.gone = Some(Arc::new(Mutex::new(vec!["/gone/a.pdf".to_string()])));
app.recent_check.opened("/gone/a.pdf");
app.check_restored_recent();
assert_eq!(app.recent.len(), 1, "the reopened file stays");
assert!(app.recent_check.gone.is_none() && app.recent_check.opened.is_empty());
// Without the open, the answer removes it.
app.recent_check.gone = Some(Arc::new(Mutex::new(vec!["/gone/a.pdf".to_string()])));
app.check_restored_recent();
assert!(app.recent.is_empty());
}
#[test]
fn only_a_path_known_to_be_missing_is_gone() {
let dir = std::env::temp_dir().join(format!("pdfcraft-recent-check-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let here = dir.join("here.pdf");
std::fs::write(&here, b"%PDF-1.7").unwrap();
assert!(!gone(&here.to_string_lossy()));
assert!(gone(&dir.join("missing.pdf").to_string_lossy()));
// A path that can't be asked about (here: one with a NUL) is not known to be gone.
assert!(!gone("bad\0path.pdf"));
std::fs::remove_dir_all(&dir).unwrap();
}
}
+4 -443
View File
@@ -316,449 +316,10 @@ pub(crate) fn document_js_body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tok
close
}
/// The height the Preferences dialog keeps below its scrolling settings for the OK row: the
/// button, and the space above it.
pub(crate) const PREFERENCES_BUTTON_ROW: f32 = 52.0;
/// The least height the scrolling settings are given. The dialog around them takes about 80 more,
/// so this still fits the smallest window (520 pt) at the largest interface size (300%, which
/// leaves 173 pt): a taller floor would push OK off the screen again.
pub(crate) const PREFERENCES_MIN_SCROLL: f32 = 60.0;
/// Whether the interface can draw a language picker's native name. On the web the browser's glyph
/// rasterizer draws scripts no embedded face has, so the native names stay; on native, ask the
/// fonts this build installed (including an installed fallback face, unless system fonts are off).
fn picker_text_is_drawable(ui: &egui::Ui, text: &str) -> bool {
#[cfg(target_arch = "wasm32")]
{
let _ = (ui, text);
true
}
#[cfg(not(target_arch = "wasm32"))]
{
ui.fonts_mut(|fonts| fonts.has_glyphs(&egui::FontId::proportional(13.0), text))
}
}
/// The date picker's displayed name. Its languages are the interface languages, so it uses the
/// same drawable-name fallback: a native name whose script this build has no face for would
/// otherwise abort under egui 0.37's `MissingGlyphPolicy::Panic` (for example Hindi without a
/// Devanagari face and installed system fonts turned off).
fn date_language_picker_name(l: &pdfcraft_engine::dates::DateLanguage, drawable: impl FnOnce(&str) -> bool) -> &'static str {
match crate::i18n::Lang::from_code(l.code) {
Some(language) => language.picker_name(drawable),
None => l.name,
}
}
/// Preferences: interface language and size, appearance, identity and JavaScript. Drawn in a scroll
/// area; [`preferences_buttons`] goes below it, outside the scroll, so OK is always in reach.
pub(crate) fn preferences_body(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) {
ui.label(egui::RichText::new(tl!("Preferences")).font(theme::semibold(18.0)));
ui.label(egui::RichText::new(tl!("Appearance")).font(theme::semibold(13.0)));
if ui.add(widgets::checkbox(&mut app.show_page_edge_shadows, tl!("Show Page Edge Shadows"))).changed() {
ui.ctx().request_repaint();
}
ui.horizontal(|ui| {
let label = ui.label(tl!("Interface language"));
// A native name is only drawn when these fonts can draw it; otherwise the English name
// keeps the list readable instead of aborting on a missing glyph (for example Hindi
// without a Devanagari face, and installed system fonts turned off).
let (selected, picker) = {
let drawable = |text: &str| picker_text_is_drawable(ui, text);
let selected = crate::i18n::Lang::from_code(&app.language)
.map_or_else(|| tl!("Auto").to_owned(), |language| language.picker_name(drawable).to_owned());
let picker = crate::i18n::Lang::for_picker_by(|language| language.picker_name(drawable))
.into_iter()
.map(|language| (language, language.picker_name(drawable)))
.collect::<Vec<_>>();
(selected, picker)
};
let before = app.language.clone();
craft_ui::ComboBox::from_id_salt("interface-language")
.selected_text(selected)
.show_ui(ui, |ui| {
if ui.selectable_value(&mut app.language, crate::i18n::AUTO.to_string(), tl!("Auto")).clicked() {
ui.close();
}
for (language, name) in &picker {
if ui.selectable_value(&mut app.language, language.code().to_string(), *name).clicked() {
ui.close();
}
}
})
.response
.labelled_by(label.id);
// Relabel the rest of this dialog in the new language right away, not next frame.
if app.language != before {
crate::i18n::set_current(crate::i18n::Lang::from_pref(&app.language));
}
});
ui.horizontal(|ui| {
use crate::ui_scale;
let label = ui.label(tl!("Interface size"));
// Auto shows the size it draws at: the display's scale times the system's text scale.
let native = ui.ctx().native_pixels_per_point().unwrap_or(1.0);
let auto_percent = ui_scale::percent(ui_scale::drawn(None, app.system_text_scale, native));
let auto = crate::i18n::fmt(tl!("Auto ({percent}%)"), &[("percent", &auto_percent.to_string())]);
let selected = app.ui_scale.map_or_else(|| auto.clone(), |f| format!("{}%", ui_scale::percent(f)));
craft_ui::ComboBox::from_id_salt("interface-size")
.selected_text(selected)
.show_ui(ui, |ui| {
if ui.selectable_value(&mut app.ui_scale, None, auto).clicked() {
ui.close();
}
for p in ui_scale::PRESETS {
let factor = f32::from(p) / 100.0;
if ui.selectable_label(app.ui_scale.is_some_and(|f| ui_scale::percent(f) == u32::from(p)), format!("{p}%")).clicked() {
app.ui_scale = Some(factor);
ui.close();
}
}
})
.response
.labelled_by(label.id);
});
ui.label(
egui::RichText::new(tl!("Auto follows the system's text size. Pages always render at the display's full resolution."))
.small()
.color(t.text_muted),
);
ui.horizontal(|ui| {
ui.label(tl!("Tools panel side"));
let right = app.side_panels.tools_on_right();
if ui.selectable_label(!right, tl!("Left")).clicked() {
app.side_panels.tools_side = crate::side_panels::ToolsSide::Left;
}
if ui.selectable_label(right, tl!("Right")).clicked() {
app.side_panels.tools_side = crate::side_panels::ToolsSide::Right;
}
});
ui.horizontal(|ui| {
ui.label(tl!("Navigation rail side"));
let right = app.side_panels.rail_on_right();
let left_btn = ui.selectable_label(!right, tl!("Left"));
left_btn.widget_info(|| {
egui::WidgetInfo::selected(egui::Role::Button, true, !right, format!("{}: {}", tl!("Navigation rail side"), tl!("Left")))
});
if left_btn.clicked() {
app.side_panels.rail_side = crate::side_panels::ToolsSide::Left;
}
let right_btn = ui.selectable_label(right, tl!("Right"));
right_btn.widget_info(|| {
egui::WidgetInfo::selected(egui::Role::Button, true, right, format!("{}: {}", tl!("Navigation rail side"), tl!("Right")))
});
if right_btn.clicked() {
app.side_panels.rail_side = crate::side_panels::ToolsSide::Right;
}
});
ui.add_space(8.0);
crate::appearance::preferences_section(ui, app, t);
ui.add_space(8.0);
reading_colours_section(ui, app, t);
ui.add_space(8.0);
ui.label(egui::RichText::new(tl!("Documents and view")).font(theme::semibold(13.0)));
ui.horizontal(|ui| {
ui.label(tl!("Default workspace mode"));
for (mode, label) in [
(crate::Mode::AllTools, "All tools"),
(crate::Mode::Read, "Read"),
(crate::Mode::Edit, "Edit"),
(crate::Mode::Convert, "Convert"),
(crate::Mode::Sign, "E-Sign"),
] {
widgets::radio_value(ui, &mut app.default_mode, mode, tl!(label));
}
});
ui.label(
egui::RichText::new(tl!("Used when opening PDFs. An explicit launch or control mode takes precedence for the session."))
.small()
.color(t.text_muted),
);
let defaults = &mut app.view_defaults;
ui.horizontal(|ui| {
ui.label(tl!("Default page display"));
for l in crate::canvas::PageLayout::ORDER {
widgets::radio_value(ui, &mut defaults.layout, l, tl!(l.label()));
}
ui.add(widgets::checkbox(&mut defaults.continuous, tl!("Continuous scrolling")));
});
ui.add(widgets::checkbox(&mut defaults.show_page_gaps, tl!("Show gaps between pages")));
ui.label(egui::RichText::new(tl!("Hide gaps to join page edges. Margins inside the PDF remain unchanged.")).small().color(t.text_muted));
ui.horizontal(|ui| {
use crate::canvas::Fit;
ui.label(tl!("Default zoom"));
widgets::radio_value(ui, &mut defaults.fit, Fit::Width, tl!("Fit to width"));
widgets::radio_value(ui, &mut defaults.fit, Fit::Page, tl!("Zoom to page level"));
widgets::radio_value(ui, &mut defaults.fit, Fit::None, tl!("Custom"));
// Editing the percentage selects Custom.
let mut percent = defaults.zoom * 100.0;
if ui.add(egui::DragValue::new(&mut percent).range(8.0..=6400.0).max_decimals(0).suffix("%")).changed() {
(defaults.fit, defaults.zoom) = (Fit::None, percent / 100.0);
}
});
ui.label(
egui::RichText::new(tl!("Used when a PDF doesn't ask for a layout or zoom. Continuous scrolling never snaps between pages."))
.small()
.color(t.text_muted),
);
ui.add(widgets::checkbox(&mut app.always_default_view, tl!("Always use my default zoom and page layout")));
ui.horizontal(|ui| {
ui.label(tl!("Units"));
for u in crate::units::Unit::ALL {
widgets::radio_value(ui, &mut app.units, u, u.label());
}
});
ui.label(egui::RichText::new(tl!("For page sizes and margins.")).small().color(t.text_muted));
// The web build has no file paths to list.
#[cfg(not(target_arch = "wasm32"))]
{
ui.horizontal(|ui| {
let label = ui.label(tl!("Recent files to keep"));
ui.add(egui::DragValue::new(&mut app.recent_limit).range(0..=crate::RECENT_FILES_MAX)).labelled_by(label.id);
});
ui.label(egui::RichText::new(tl!("Lowering this forgets the oldest files. At 0 there is no list.")).small().color(t.text_muted));
}
// The web build has no file paths to reopen.
#[cfg(not(target_arch = "wasm32"))]
ui.add(widgets::checkbox(&mut app.reopen_last_session, tl!("Reopen the files that were open when PdfCraft last closed")));
// Acrobat's "Restore last view settings when reopening documents" (#1767).
#[cfg(not(target_arch = "wasm32"))]
ui.add(widgets::checkbox(&mut app.restore_last_view, tl!("Restore the last view (page, zoom and page display) when a document is opened again")));
// The web build has no files on disk to watch.
#[cfg(not(target_arch = "wasm32"))]
ui.add(widgets::checkbox(&mut app.reload_changed_files, tl!("Reload documents when their files change on disk")));
// The notice's "Don't show again" turns this off (#4035); the restrictions stay either way.
ui.add(widgets::checkbox(&mut app.show_secured_notice, tl!("Show a notice when a document is secured")));
ui.horizontal(|ui| {
ui.label(tl!("Scroll speed (mouse wheel and arrow keys)"));
for speed in crate::scroll_speed::ScrollSpeed::ALL {
widgets::radio_value(ui, &mut app.scroll_speed, speed, tl_ctx!("scroll speed", speed.label()));
}
});
// Whether anything animates, the wheel's scrolling and zooming included; left alone it
// follows the system's animation setting.
ui.horizontal(|ui| {
ui.label(tl!("Animation effects"));
for choice in crate::motion::AnimationEffects::ALL {
widgets::radio_value(ui, &mut app.animation_effects, choice, tl_ctx!("animation effects", choice.label()));
}
});
// Only where the app draws the title bar (GNOME on Wayland); elsewhere the desktop draws it.
if app.window_controls.is_some() {
ui.add(widgets::checkbox(&mut app.system_title_bar, tl!("Use system title bar")))
.on_hover_text(tl!("Show a basic title bar for the window buttons instead of the tab strip. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme."));
}
ui.add_space(8.0);
// Identity: the author of new comments (Acrobat: Preferences ▸ Identity).
ui.label(egui::RichText::new(tl!("Identity")).font(theme::semibold(13.0)));
ui.horizontal(|ui| {
let label = ui.label(tl!("Name on new comments"));
ui.add(crate::widgets::line(&mut app.comment_prefs.author).desired_width(220.0).char_limit(crate::MAX_AUTHOR_CHARS)).labelled_by(label.id);
});
ui.add(widgets::checkbox(&mut app.comment_prefs.hide_empty_highlight_hover, tl!("Hide hover previews for highlights without comment text")));
ui.add_space(8.0);
ui.label(egui::RichText::new(tl!("Fill & Sign")).font(theme::semibold(13.0)));
ui.add(widgets::checkbox(&mut app.flatten_fill_sign_on_save, tl!("Flatten Fill & Sign when saving")));
ui.add_enabled(
!app.flatten_fill_sign_on_save,
widgets::checkbox(&mut app.ask_to_lock_signatures, tl!("Otherwise, ask on the first save after a signature is placed")),
);
ui.label(
egui::RichText::new(tl!("Text, marks and signatures become part of the page. Other comments stay editable.")).small().color(t.text_muted),
);
ui.add_space(8.0);
date_format(ui, app, t);
ui.add_space(8.0);
ui.label(egui::RichText::new("JavaScript").font(theme::semibold(13.0)));
egui::Frame::new().fill(t.hover).corner_radius(egui::CornerRadius::same(6)).inner_margin(egui::Margin::same(10)).show(ui, |ui| {
ui.set_width(ui.available_width());
let mut on = app.session.javascript();
if ui.add(widgets::checkbox(&mut on, tl!("Enable Acrobat JavaScript"))).changed() {
app.session.set_javascript(on);
}
ui.label(
egui::RichText::new(tl!("Scripts run in a sandbox without file or network access. A script that asks to open a web page needs your permission first. With JavaScript off, Acrobat's standard format, validate and calculate functions still work."))
.small()
.color(t.text_muted),
);
});
}
/// The Preferences dialog's OK row. Returns `true` to close.
pub(crate) fn preferences_buttons(ui: &mut egui::Ui) -> bool {
ui.add_space(10.0);
buttons(ui, tl!("OK"), &[]).is_some()
}
/// Preferences ▸ Date format: a preset, or any pattern typed in, for Fill & Sign dates, and the
/// language of its month and weekday names. A valid pattern applies as it's typed; an invalid
/// one stays in the box with the reason, and the last valid one stays in use.
fn date_format(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) {
use pdfcraft_engine::dates::{DATE_FORMATS, DATE_LANGUAGES, MAX_DATE_FORMAT_CHARS};
ui.label(egui::RichText::new(tl!("Date format")).font(theme::semibold(13.0)));
let sample = |app: &PdfCraftApp, f: &str| format!("{} {f}", app.date_text(Some(f)).unwrap_or_default());
ui.horizontal(|ui| {
let label = ui.label(tl!("Fill & Sign dates"));
let current = app.session.date_format().to_string();
let selected = if DATE_FORMATS.contains(&current.as_str()) { sample(app, &current) } else { tl!("Custom").to_string() };
craft_ui::ComboBox::from_id_salt("date-format")
.selected_text(selected)
.width(240.0)
.show_ui(ui, |ui| {
for f in DATE_FORMATS {
if ui.selectable_label(current == f, sample(app, f)).clicked() && app.session.set_date_format(f).is_ok() {
app.date_format_draft = None;
ui.close();
}
}
})
.response
.labelled_by(label.id);
});
ui.horizontal(|ui| {
let label = ui.label(tl!("Pattern"));
let mut text = app.date_format_draft.clone().unwrap_or_else(|| app.session.date_format().to_string());
let edit = ui.add(egui::TextEdit::singleline(&mut text).desired_width(160.0).char_limit(MAX_DATE_FORMAT_CHARS)).labelled_by(label.id);
// The box keeps the text as typed (a trailing space included) while it has focus; the
// setting takes the trimmed pattern whenever it's valid.
if edit.changed() {
let _ = app.session.set_date_format(&text);
app.date_format_draft = Some(text.clone());
}
if !edit.has_focus() && pdfcraft_engine::dates::check_date_format(&text).is_ok() {
app.date_format_draft = None;
}
match app.date_text(Some(&text)) {
Ok(today) => ui.label(egui::RichText::new(crate::i18n::fmt(tl!("Today: {date}"), &[("date", &today)])).color(t.text_muted)),
// The engine's reason, in English.
Err(e) => ui.label(egui::RichText::new(e).color(egui::Color32::from_rgb(0xD1, 0x3B, 0x3B))),
};
});
// Fill & Sign refuses a date it would save as "?"; say so before anyone tries.
let bad = app.date_text(None).map(|today| pdfcraft_engine::dates::unwritable(&today)).unwrap_or_default();
if !bad.is_empty() {
ui.label(
egui::RichText::new(crate::i18n::fmt(
tl!(
"{chars} can't be written into the PDF yet: Fill & Sign text is Western European only. Pick a numeric format such as dd.mm.yyyy."
),
&[("chars", &bad)],
))
.color(egui::Color32::from_rgb(0xD1, 0x3B, 0x3B)),
);
}
ui.horizontal(|ui| {
let label = ui.label(tl!("Language"));
// Build every label before the combo box mutably borrows `ui`, with the same drawable
// fallback the interface language picker uses.
let (follow, selected, current, names) = {
let drawable = |text: &str| picker_text_is_drawable(ui, text);
let interface = crate::i18n::current().picker_name(drawable);
let follow = crate::i18n::fmt(tl!("Same as interface ({language})"), &[("language", interface)]);
let current = app.session.date_language().map(str::to_string);
let selected = DATE_LANGUAGES
.iter()
.find(|l| current.as_deref() == Some(l.code))
.map_or_else(|| follow.clone(), |l| date_language_picker_name(l, drawable).to_string());
let names = DATE_LANGUAGES.iter().map(|l| (l, date_language_picker_name(l, drawable))).collect::<Vec<_>>();
(follow, selected, current, names)
};
craft_ui::ComboBox::from_id_salt("date-language")
.selected_text(selected)
.width(240.0)
.show_ui(ui, |ui| {
if ui.selectable_label(current.is_none(), follow).clicked() && app.session.set_date_language(None).is_ok() {
ui.close();
}
for (l, name) in &names {
if ui.selectable_label(current.as_deref() == Some(l.code), *name).clicked() && app.session.set_date_language(Some(l.code)).is_ok()
{
ui.close();
}
}
})
.response
.labelled_by(label.id);
});
ui.label(
egui::RichText::new(crate::i18n::fmt(
tl!("yyyy or yy year · m or mm month · mmm or mmmm month name · d or dd day · ddd or dddd weekday. H, h, M, s and t are time letters and can't be used on their own: put {escape} before a letter to show it as is."),
&[("escape", "\\")],
))
.small()
.color(t.text_muted),
);
}
fn reading_colours_section(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens) {
// Reading colours (Acrobat: Replace Document Colors): solid text and line-art paints are
// remapped while rendering, and the page clears to the background colour. The preference
// is app-wide: every open document follows it, and documents open with it.
ui.label(egui::RichText::new(tl!("Reading colours")).font(theme::semibold(13.0)));
let mode = app.reading_colors.mode_name();
ui.horizontal_wrapped(|ui| {
for (name, label, colors) in [
("off", "Off", pdfcraft_render::ReadingColors::default()),
("black-on-white", "Black on white", pdfcraft_render::ReadingColors::BLACK_ON_WHITE),
("white-on-black", "White on black", pdfcraft_render::ReadingColors::WHITE_ON_BLACK),
("yellow-on-black", "Yellow on black", pdfcraft_render::ReadingColors::YELLOW_ON_BLACK),
("green-on-black", "Green on black", pdfcraft_render::ReadingColors::GREEN_ON_BLACK),
] {
let params = colors.params.unwrap_or(pdfcraft_render::ReadingParams {
text: [0, 0, 0],
background: [255, 255, 255],
only_black: false,
line_art: true,
});
ui.vertical(|ui| {
ui.set_width(104.0);
let sample = egui::RichText::new("Aa").size(22.0).color(egui::Color32::from_rgb(params.text[0], params.text[1], params.text[2]));
let button = egui::Button::new(sample)
.fill(egui::Color32::from_rgb(params.background[0], params.background[1], params.background[2]))
.min_size(egui::vec2(94.0, 44.0))
.stroke(egui::Stroke::new(if mode == name { 2.0 } else { 1.0 }, if mode == name { t.accent } else { t.border }));
let response = ui.add(button);
response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, mode == name, tl!(label)));
if response.clicked() {
app.set_reading_colors(colors);
}
ui.label(tl!(label));
});
}
});
ui.add_space(8.0);
if let Some(params) = app.reading_colors.params {
let text = egui::Color32::from_rgb(params.text[0], params.text[1], params.text[2]);
let background = egui::Color32::from_rgb(params.background[0], params.background[1], params.background[2]);
egui::Frame::new().fill(background).inner_margin(16.0).show(ui, |ui| {
ui.set_min_width((ui.available_width() - 32.0).max(0.0));
ui.label(egui::RichText::new(tl!("Reading colours")).size(18.0).color(text));
ui.label(egui::RichText::new(tl!("Colours are remapped while rendering; the document itself never changes.")).color(text));
});
} else {
ui.label(tl!("Original"));
}
egui::CollapsingHeader::new(tl!("Custom")).default_open(mode == "custom").show(ui, |ui| {
let mut colors = if app.reading_colors.params.is_some() { app.reading_colors } else { pdfcraft_render::ReadingColors::BLACK_ON_WHITE };
let mut changed = false;
if let Some(params) = colors.params.as_mut() {
ui.horizontal(|ui| {
let text = ui.label(tl!("Text"));
changed |= ui.color_edit_button_srgb(&mut params.text).labelled_by(text.id).changed();
let background = ui.label(tl!("Page background"));
changed |= ui.color_edit_button_srgb(&mut params.background).labelled_by(background.id).changed();
});
changed |= ui.add(crate::widgets::checkbox(&mut params.only_black, tl!("Only change the colour of black text or line art"))).changed();
changed |= ui.add(crate::widgets::checkbox(&mut params.line_art, tl!("Change the colour of line art as well as text"))).changed();
}
if changed {
app.set_reading_colors(colors);
}
});
ui.label(egui::RichText::new(tl!("Colours are remapped while rendering; the document itself never changes.")).small().color(t.text_muted));
ui.add_space(8.0);
}
#[expect(unused_imports, reason = "re-exported for tests and backward compatibility")]
pub(crate) use crate::dialogs::preferences::{
PREFERENCES_BUTTON_ROW, PREFERENCES_MIN_SCROLL, date_language_picker_name, preferences_body, preferences_buttons, preferences_header,
};
#[cfg(test)]
mod tests {
@@ -102,3 +102,152 @@ fn a_very_tall_window_does_not_leave_a_blank_gap_above_ok() {
assert!(on_screen(ok, 2600.0) && on_screen(last, 2600.0), "{last:?} {ok:?}");
assert!(ok.min.y - last.max.y < 120.0, "a gap of {} pt between the last setting and OK", ok.min.y - last.max.y);
}
#[test]
fn segmented_pill_controls_switch_modes_and_layouts() {
let mut h = harness(900.0);
// Switch workspace mode via segmented pill
h.get_by_role_and_label(egui::accesskit::Role::RadioButton, "Convert").scroll_to_me();
h.run_steps(3);
h.get_by_role_and_label(egui::accesskit::Role::RadioButton, "Convert").click();
h.run_steps(2);
assert_eq!(h.state().default_mode, pdfcraft_ui_egui::Mode::Convert);
let continuous_before = h.state().view_defaults.continuous;
// Switch page layout via segmented pill
h.get_by_label("Two-page view").scroll_to_me();
h.run_steps(3);
h.get_by_label("Two-page view").click();
h.run_steps(2);
assert_eq!(h.state().view_defaults.layout, pdfcraft_ui_egui::canvas::PageLayout::TwoUp);
assert_eq!(h.state().view_defaults.continuous, continuous_before, "Two-page view retains continuous scrolling");
// Switch continuous scrolling pill (can be combined with Two-page view)
h.get_by_label("Continuous scrolling").click();
h.run_steps(2);
assert_eq!(h.state().view_defaults.continuous, !continuous_before);
assert_eq!(h.state().view_defaults.layout, pdfcraft_ui_egui::canvas::PageLayout::TwoUp, "two-page continuous scrolling is supported");
// Switch to single page mode (continuous setting remains independent)
h.get_by_label("Single page").click();
h.run_steps(2);
assert_eq!(h.state().view_defaults.layout, pdfcraft_ui_egui::canvas::PageLayout::Single);
assert_eq!(h.state().view_defaults.continuous, !continuous_before);
// Switch tools panel side via segmented pill
h.get_by_label("Left").scroll_to_me();
h.run_steps(3);
h.get_by_label("Left").click();
h.run_steps(2);
assert_eq!(h.state().side_panels.tools_side, pdfcraft_ui_egui::side_panels::ToolsSide::Left);
// Switch measurement units via segmented pill
h.get_by_label("pt").scroll_to_me();
h.run_steps(3);
h.get_by_label("pt").click();
h.run_steps(2);
assert_eq!(h.state().units, pdfcraft_ui_egui::units::Unit::Points);
}
#[test]
fn search_settings_scans_and_highlights_in_situ_without_hiding_cards() {
let mut h = harness(900.0);
// Initially all card titles exist
assert!(h.query_by_label("General & Interface").is_some());
assert!(h.query_by_label("Comment").is_some());
assert!(h.query_by_label("JavaScript").is_some());
// Type "Hide hover" in search box
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search settings…").click();
h.run_steps(1);
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search settings…").type_text("Hide hover");
h.run_steps(4);
// In browser-style search, cards are NOT hidden
assert!(h.query_by_label("General & Interface").is_some());
assert!(h.query_by_label("Comment").is_some());
assert!(h.query_by_label("JavaScript").is_some());
// The setting "Hide hover previews for highlights without comment text" is present and matched
assert!(h.query_by_label("Hide hover previews for highlights without comment text").is_some());
// Match badge displays 1 match
assert!(h.query_by_label("1 match").is_some());
// Clearing search clears match badge
h.get_by_label("Clear search").click();
h.run_steps(4);
assert!(h.query_by_label("1 match").is_none());
// Search for "javascript"
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search settings…").click();
h.run_steps(1);
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search settings…").type_text("javascript");
h.run_steps(4);
// Cards remain visible and multiple matches are reported
assert!(h.query_by_label("JavaScript").is_some());
assert!(h.query_by_label("General & Interface").is_some());
assert!(h.query_by_label_contains("matches").is_some());
// Clearing search shows everything again
h.get_by_label("Clear search").click();
h.run_steps(4);
assert!(h.query_by_label("General & Interface").is_some());
assert!(h.query_by_label("Comment").is_some());
assert!(h.query_by_label("JavaScript").is_some());
}
#[test]
fn preferences_dialog_scrollbar_spacing_and_controls() {
let h = harness(600.0);
let title = h.get_by(|n| n.role() == egui::accesskit::Role::Label && n.value().as_deref() == Some("Preferences")).rect();
let search = h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search settings…").rect();
let ok = h.get_by_label("OK").rect();
assert!(on_screen(ok, 600.0));
// Header title and search box are vertically aligned
assert!((title.center().y - search.center().y).abs() <= 2.0);
// Search box right edge is aligned within the dialog
assert!(search.max.x <= ok.max.x);
}
#[test]
fn search_scrolls_option_only_and_theme_card_matches_into_visible_viewport() {
let mut h = harness(480.0);
let title = h.get_by(|n| n.role() == egui::accesskit::Role::Label && n.value().as_deref() == Some("Preferences")).rect();
let ok = h.get_by_label("OK").rect();
// "Two-page view" is an option in Card 3 (Documents and view).
// In a 480 pt window, it starts out below the visible scroll viewport.
let opt_before = h.get_by_label("Two-page view").rect();
assert!(opt_before.min.y >= ok.min.y, "Two-page option starts out below the visible viewport: {opt_before:?} vs OK {ok:?}");
// Searching "Two-page" (which only occurs inside that segmented pill option)
// auto-scrolls the matching option into the visible viewport between title and OK.
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search settings…").click();
h.run_steps(1);
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search settings…").type_text("Two-page");
h.run_steps(4);
let opt_after = h.get_by_label("Two-page view").rect();
assert!(
opt_after.min.y >= title.max.y && opt_after.max.y <= ok.min.y,
"Two-page option scrolled into visible scroll viewport: {opt_after:?} between title {title:?} and OK {ok:?}"
);
// Clear search and test a theme-card-only match
h.get_by_label("Clear search").click();
h.run_steps(4);
// Search for "Dark theme" (which occurs only in the dark theme card in Card 2).
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search settings…").click();
h.run_steps(1);
h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search settings…").type_text("Dark theme");
h.run_steps(4);
let dark_card = h.get_by_label("Dark theme").rect();
assert!(
dark_card.min.y >= title.max.y && dark_card.max.y <= ok.min.y,
"Dark theme card scrolled into visible viewport: {dark_card:?} between title {title:?} and OK {ok:?}"
);
}
+33
View File
@@ -221,6 +221,39 @@ fn the_limit_is_saved_and_restored_and_cuts_a_longer_list() {
std::fs::remove_dir_all(&dir).unwrap();
}
/// #5682: restoring settings never asks the file system about recent files, which can block on a
/// mount that has stopped answering. A gone file leaves the list once frames run, and a file that
/// is there stays.
#[test]
fn restoring_settings_does_not_check_recent_files_and_a_frame_drops_the_gone_ones() {
let dir = std::env::temp_dir().join(format!("pdfcraft-recent-restore-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let here = dir.join("here.pdf");
std::fs::write(&here, PDF).unwrap();
let here = here.to_string_lossy().into_owned();
let gone = dir.join("gone.pdf").to_string_lossy().into_owned();
let entries: Vec<RecentFile> =
[&here, &gone].iter().map(|p| RecentFile { name: "x.pdf".into(), path: (*p).clone(), pages: 1, size: 0 }).collect();
let json = serde_json::json!({ "recent": entries }).to_string();
let mut restored = PdfCraftApp::new();
restored.restore(&json);
let paths: Vec<&str> = restored.recent.iter().map(|r| r.path.as_str()).collect();
assert_eq!(paths, [here.as_str(), gone.as_str()], "restoring keeps every entry without asking whether its file exists");
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 1600.0)).build_eframe(move |_cc| {
let mut app = PdfCraftApp::new();
app.set_option("language", "en").unwrap();
app.run_inline = true;
app.restore(&json);
app
});
h.run_steps(2);
let paths: Vec<&str> = h.state().recent.iter().map(|r| r.path.as_str()).collect();
assert_eq!(paths, [here.as_str()], "the gone file leaves once the window is up");
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn a_settings_file_can_not_ask_for_a_limit_that_is_not_one() {
for (saved, want) in [
+3 -3
View File
@@ -242,11 +242,11 @@ fn preferences_theme_cards_and_use_system_setting_stay_in_sync() {
assert_theme(&h, ThemePreference::System, ThemeKind::Dark);
assert_eq!(mode_shown(&h), "Use system setting");
// The OS is dark: the Dark card's radio row picks Dark, and the combo box says so.
// The OS is dark: the Dark card picks Dark, and the combo box says so.
// The cards sit below the fold of the Preferences scroll area at this window size.
h.get_by_label("Dark gray").scroll_to_me();
h.get_by_label("Dark theme").scroll_to_me();
h.run_steps(3);
h.get_by_label("Dark gray").click();
h.get_by_label("Dark theme").click();
h.run_steps(3);
assert_theme(&h, ThemePreference::Dark, ThemeKind::Dark);
assert_eq!(mode_shown(&h), "Dark");
+4 -1
View File
@@ -1,5 +1,7 @@
# PdfCraft roadmap: milestones and what's next
> **Last reviewed:** 2026-11-01 | **Last updated:** 2026-11-01 | **Change:** patch (M7 #5657: header/footer, watermark and background operations commit all selected pages together; later-page errors preserve marks, content, shared/inherited resources and pending edits; estimates unchanged)
> **Last reviewed:** 2026-11-01 | **Last updated:** 2026-11-01 | **Change:** patch (M7, PR #2155 further review: inherited drawing/text state, affine image gestures, paste/selection ownership, no-op scripts and menu permissions; estimates unchanged)
> **Last reviewed:** 2026-11-01 | **Last updated:** 2026-11-01 | **Change:** patch (M7, PR #2155 latest comments: explicit image-paste events, mixed-size field refresh, and documented mixed-script normalization with Undo; estimates unchanged)
@@ -223,7 +225,7 @@ total matches the parity estimate.
| M6 | Forms + JavaScript | 160–320 | 50% | 40–75 | Done: filling all field types with regenerated appearances; Prepare a form (every field type, multi-select/shared properties, move/resize/delete, Field Properties General/Appearance/Position/Options/Format/Validate/Calculate); Acrobat's AF format/keystroke/validate/calculate functions and simplified field notation run natively in Acrobat's event order; tab order; push-button actions; flatten; agent tools. Form data exchange (FDF, XFDF, XML, CSV, text) done; XFDF values retain text across XML comments and processing instructions. Plain AcroForm XML imports retain all direct text around comments and processing instructions, including CDATA and character references.<br>Done since: JavaScript engine (boa, sandboxed) running custom keystroke/validate/calculate/format and button scripts, document JavaScripts, console. Missing: Actions tab, wider object model (annotations, layers, dialogs), XFA<br>Done since: Multi-select choice fields write ascending `/I` option indices while preserving `/V` selection order; synthetic forms/engine regressions cover reverse selection and save/reopen. CSV export preserves carriage returns in names and values. |
| M6 | Forms + JavaScript | 160–320 | 50% | 40–75 | Done: filling all field types with regenerated appearances; Prepare a form (every field type, multi-select/shared properties, move/resize/delete, Field Properties General/Appearance/Position/Options/Format/Validate/Calculate); Acrobat's AF format/keystroke/validate/calculate functions and simplified field notation run natively in Acrobat's event order; tab order; push-button actions; flatten; agent tools. Form data exchange (FDF, XFDF, XML, CSV, text) done; XFDF values retain text across XML comments and processing instructions. XML/XFDF exports preserve tabs and line breaks in names and comment metadata. Refreshed against upstream `99941daa` (2026-10-15).<br>Done since: JavaScript engine (boa, sandboxed) running custom keystroke/validate/calculate/format and button scripts, document JavaScripts, console. Missing: Actions tab, wider object model (annotations, layers, dialogs), XFA<br>Done since: Multi-select choice fields write ascending `/I` option indices while preserving `/V` selection order; synthetic forms/engine regressions cover reverse selection and save/reopen. CSV export preserves carriage returns in names and values. |
| M6 | Forms + JavaScript | 160–320 | 50% | 40–75 | Done: filling all field types with regenerated appearances; Prepare a form (every field type, multi-select/shared properties, move/resize/delete, Field Properties General/Appearance/Position/Options/Format/Validate/Calculate); Acrobat's AF format/keystroke/validate/calculate functions and simplified field notation run natively in Acrobat's event order; tab order; push-button actions; flatten; agent tools. Form data exchange (FDF, XFDF, XML, CSV, text) done; XFDF values retain text across XML comments and processing instructions. XML/XFDF exports preserve tabs and line breaks in names and comment metadata. Plain AcroForm XML imports retain all direct text around comments and processing instructions, including CDATA and character references. CSV export and spreadsheet merging quote tabs, and import distinguishes quoted tabs from TSV delimiters without changing field identities.<br>Done since: JavaScript engine (boa, sandboxed) running custom keystroke/validate/calculate/format and button scripts, document JavaScripts, console. Missing: Actions tab, wider object model (annotations, layers, dialogs), XFA<br>Done since: Multi-select choice fields write ascending `/I` option indices while preserving `/V` selection order; synthetic forms/engine regressions cover reverse selection and save/reopen. CSV export preserves carriage returns in names and values. |
| M7 | Content editing (text, images, header/footer, watermark) | 250–500 | 20% | 100–180 | Done: header & footer, watermarks, backgrounds, Bates; added text and images that stay editable (move, resize, format, rotate, flip, crop, replace); links (Link tool, Link Properties, create from URLs, remove all). Done since: Edit text preserves Arabic/Hebrew `/ActualText` typing order, with font-independent regressions; single-glyph RTL ligature spans (including lam-alef) join their surrounding word. Done since (#1116): editable text regions grouped across compatible words and subset fonts, one rich-text editor over a background with the source text removed, embedded sfnt faces reused as editor faces, and visible (clipped) bounds for cropped-image selection and resize. Exclusive crops now resize across nested states and content streams, with shared clips fixed.<br>Done since: #594 ordinary paragraph drags preserve overlapping source text; UI/engine regressions, native save/reopen, independent-reader checks and full CI passed in the Linux test environment. #1200 candidate: local GoToR links open in desktop tabs and through root-confined automation; appearance-only edits preserve existing actions. Named destinations remain unapplied and `/NewWindow` is a tab hint. Done since: #3187: Added-image automation normalizes extreme signed rotation angles before combining them with the current orientation; integer bounds, history, pixels, save/reopen and MCP have regressions. Done since: #2592: Styled fallback fonts batch up to 240 glyphs per actual face and retain source styles. Budget refusal and distinct same-BaseFont descriptor weights have mutation-checked regressions; coverage and complex mixed runs remain limited. Missing: editing existing text and images in place (the longest pole), image/PDF watermarks PR #2155 candidate: editor-owned crops preserve original clips through group moves; Arrange preserves added-item stream ownership and refuses unsafe scope/state/tag extraction; image handles and flips follow page orientation; general transforms and Unicode script toggles have headless tools. Clipboard, mixed-size formatting, Home pins and reloadable installed-font discovery have review regressions. Latest follow-up uses explicit image-paste events, refreshes the mixed-size display, and documents script normalization with Undo. Further review covers inherited Form text and mask chronology, scoped transform composition, affine resize/rotation pivots, paste/selection ownership, no-op scripts and page-menu permissions. |
| M7 | Content editing (text, images, header/footer, watermark) | 250–500 | 20% | 100–180 | Done: header & footer, watermarks, backgrounds, Bates; added text and images that stay editable (move, resize, format, rotate, flip, crop, replace); links (Link tool, Link Properties, create from URLs, remove all). Done since: Edit text preserves Arabic/Hebrew `/ActualText` typing order, with font-independent regressions; single-glyph RTL ligature spans (including lam-alef) join their surrounding word. Done since (#1116): editable text regions grouped across compatible words and subset fonts, one rich-text editor over a background with the source text removed, embedded sfnt faces reused as editor faces, and visible (clipped) bounds for cropped-image selection and resize. Exclusive crops now resize across nested states and content streams, with shared clips fixed.<br>Done since: #594 ordinary paragraph drags preserve overlapping source text; UI/engine regressions, native save/reopen, independent-reader checks and full CI passed in the Linux test environment. #1200 candidate: local GoToR links open in desktop tabs and through root-confined automation; appearance-only edits preserve existing actions. Named destinations remain unapplied and `/NewWindow` is a tab hint. Done since: #3187: Added-image automation normalizes extreme signed rotation angles before combining them with the current orientation; integer bounds, history, pixels, save/reopen and MCP have regressions. Done since: #2592: Styled fallback fonts batch up to 240 glyphs per actual face and retain source styles. Budget refusal and distinct same-BaseFont descriptor weights have mutation-checked regressions; coverage and complex mixed runs remain limited. Done since: #5657 page-mark operations are atomic across selected pages, including shared/inherited resources and existing unsaved edits. Missing: editing existing text and images in place (the longest pole), image/PDF watermarks PR #2155 candidate: editor-owned crops preserve original clips through group moves; Arrange preserves added-item stream ownership and refuses unsafe scope/state/tag extraction; image handles and flips follow page orientation; general transforms and Unicode script toggles have headless tools. Clipboard, mixed-size formatting, Home pins and reloadable installed-font discovery have review regressions. Latest follow-up uses explicit image-paste events, refreshes the mixed-size display, and documents script normalization with Undo. Further review covers inherited Form text and mask chronology, scoped transform composition, affine resize/rotation pivots, paste/selection ownership, no-op scripts and page-menu permissions. |
| M7 | Content editing (text, images, header/footer, watermark) | 250–500 | 20% | 100–180 | Done: header & footer, watermarks, backgrounds, Bates; added text and images that stay editable (move, resize, format, rotate, flip, crop, replace); links (Link tool, Link Properties, create from URLs, remove all). Done since: Edit text preserves Arabic/Hebrew `/ActualText` typing order, with font-independent regressions. Done since (#1116): editable text regions grouped across compatible words and subset fonts, one rich-text editor over a background with the source text removed, embedded sfnt faces reused as editor faces, and visible (clipped) bounds for cropped-image selection and resize. Exclusive crops now resize across nested states and content streams, with shared clips fixed.<br>Done since: #594 ordinary paragraph drags preserve overlapping source text; UI/engine regressions, native save/reopen, independent-reader checks and full CI passed in the Linux test environment. #1200 candidate: local GoToR links open in desktop tabs and through root-confined automation; appearance-only edits preserve existing actions. Named destinations remain unapplied and `/NewWindow` is a tab hint. #1316: replacing a line or paragraph keeps a neighbouring line whose glyph box overlaps when the baselines differ; a second copy on the same baseline is still replaced. Missing: editing existing text and images in place (the longest pole), image/PDF watermarks |
| M7 | Content editing (text, images, header/footer, watermark) | 250–500 | 20% | 100–180 | Done: header & footer, watermarks, backgrounds, Bates; added text and images that stay editable (move, resize, format, rotate, flip, crop, replace); links (Link tool, Link Properties, create from URLs, remove all). #3212: Headers, Bates numbers, watermarks and added text stay visible after unfinished marked content, without revealing hidden content. Tracked editable text distinguishes repeated glyph spacing from word gaps, with synthetic paragraph/object regressions. Missing: editing existing text and images in place (the longest pole), watermark print/screen visibility and repeat |
| M6 | Forms + JavaScript | 160–320 | 50% | 40–75 | Done: filling all field types with regenerated appearances; Prepare a form (every field type, multi-select/shared properties, move/resize/delete, Field Properties General/Appearance/Position/Options/Format/Validate/Calculate); Acrobat's AF format/keystroke/validate/calculate functions and simplified field notation run natively in Acrobat's event order; tab order; push-button actions; flatten; agent tools. Form data exchange (FDF, XFDF, XML, CSV, text) done; XFDF values retain text across XML comments and processing instructions.<br>Done since: JavaScript engine (boa, sandboxed) running custom keystroke/validate/calculate/format and button scripts, document JavaScripts, console. Missing: Actions tab, wider object model (annotations, layers, dialogs), XFA<br>Done since: Existing simple field-font encodings and Differences are respected when generating appearances; an unencodable value uses a separate Helvetica appearance font without changing the source font. Synthetic reopen regressions cover punctuation, subset fallback and multiline text. Exact font metrics/layout and broader Unicode fallback remain incomplete. |
@@ -296,6 +298,7 @@ Estimates unchanged.
| Date | Change | Summary |
|---|---|---|
| 2026-11-01 | patch | M7 #5657: header/footer, watermark and background operations commit all selected pages together; later-page errors preserve marks, content, shared/inherited resources and pending edits; estimates unchanged. |
| 2026-10-31 | patch | #1577: reconcile optional page shadows with current viewer/organizer and settings modules; CI validation pending. |
| 2026-10-31 | patch | M3 #1354: reconcile the launch override with split app/file modules and the structured open result; preserve headless help/version exits. CI validation pending. |
| 2026-10-31 | patch | M2, PR #4172: eight GBK font/alias cases compare exact pixels with independent installed-face and explicit-Unicode references; wrong-glyph and wrong-family negative controls fail. Estimates unchanged. |
+6 -6
View File
@@ -2460,8 +2460,8 @@ milestone = "M7"
status = "shipped"
commands = ["edit.header_footer.update", "edit.header_footer.remove"]
tools = ["doc_header_footer", "doc_remove_marks"]
evidence = ["crates/edit/src/tests.rs::replace_and_remove_restore_the_original_content", "crates/ui-egui/tests/it/marks.rs::header_and_footer_dialog_inserts_tokens_and_applies_to_a_subset"]
notes = "recognises PdfCraft marks; Acrobat-made headers are not detected yet"
evidence = ["crates/edit/src/tests.rs::replace_and_remove_restore_the_original_content", "crates/ui-egui/tests/it/marks.rs::header_and_footer_dialog_inserts_tokens_and_applies_to_a_subset", "crates/edit/src/mark_transaction_tests.rs::header_footer_changes_are_atomic_after_a_later_page_failure", "crates/edit/src/mark_transaction_tests.rs::replacements_commit_all_selected_pages_and_preserve_other_marks_and_shared_resources"]
notes = "Add and Update are atomic across all selected pages: errors preserve existing marks, page content/resources and pending edits (#5657). recognises PdfCraft marks; Acrobat-made headers are not detected yet"
[[feature]]
id = "edit.header-footer-tokens"
@@ -2532,8 +2532,8 @@ milestone = "M7"
status = "shipped"
commands = ["edit.watermark.update", "edit.watermark.remove"]
tools = ["doc_watermark", "doc_remove_marks"]
evidence = ["crates/edit/src/tests.rs::replace_and_remove_restore_the_original_content", "crates/engine/src/tests.rs::headers_footers_watermarks_and_backgrounds_show_update_and_remove"]
notes = ""
evidence = ["crates/edit/src/tests.rs::replace_and_remove_restore_the_original_content", "crates/engine/src/tests.rs::headers_footers_watermarks_and_backgrounds_show_update_and_remove", "crates/edit/src/mark_transaction_tests.rs::watermark_changes_are_atomic_after_a_later_page_failure", "crates/edit/src/mark_transaction_tests.rs::replacements_commit_all_selected_pages_and_preserve_other_marks_and_shared_resources"]
notes = "Add and Update are atomic across all selected pages: errors preserve existing marks, page content/resources and pending edits (#5657). "
[[feature]]
id = "edit.watermark-appearance"
@@ -2568,8 +2568,8 @@ milestone = "M7"
status = "shipped"
commands = ["edit.background.update", "edit.background.remove"]
tools = ["doc_background", "doc_remove_marks"]
evidence = ["crates/edit/src/tests.rs::replace_and_remove_restore_the_original_content", "crates/engine/src/tests.rs::headers_footers_watermarks_and_backgrounds_show_update_and_remove", "crates/edit/src/backdrop_tests.rs::a_white_fill_backdrop_is_replaced_and_put_back_when_the_background_goes", "crates/edit/src/backdrop_tests.rs::an_edit_after_the_fill_is_kept_and_the_backdrop_still_comes_back", "crates/edit/src/backdrop_tests.rs::a_copy_written_out_again_with_other_spacing_still_comes_back", "crates/edit/src/backdrop_tests.rs::a_change_before_the_fill_leaves_it_off_and_names_the_page", "crates/edit/src/backdrop_tests.rs::a_fill_that_would_cover_content_painted_before_it_stays_off", "crates/engine/src/tests.rs::remove_background_names_the_pages_whose_own_backdrop_stays_off", "crates/automation/tests/it/backdrop.rs::removed_text_leaves_the_file_when_a_background_replaced_the_pages_backdrop"]
notes = "Remove also turns back on a page backdrop Add replaced, keeping edits made after it; where that isn't safe it says which pages keep it off"
evidence = ["crates/edit/src/tests.rs::replace_and_remove_restore_the_original_content", "crates/engine/src/tests.rs::headers_footers_watermarks_and_backgrounds_show_update_and_remove", "crates/edit/src/backdrop_tests.rs::a_white_fill_backdrop_is_replaced_and_put_back_when_the_background_goes", "crates/edit/src/backdrop_tests.rs::an_edit_after_the_fill_is_kept_and_the_backdrop_still_comes_back", "crates/edit/src/backdrop_tests.rs::a_copy_written_out_again_with_other_spacing_still_comes_back", "crates/edit/src/backdrop_tests.rs::a_change_before_the_fill_leaves_it_off_and_names_the_page", "crates/edit/src/backdrop_tests.rs::a_fill_that_would_cover_content_painted_before_it_stays_off", "crates/engine/src/tests.rs::remove_background_names_the_pages_whose_own_backdrop_stays_off", "crates/automation/tests/it/backdrop.rs::removed_text_leaves_the_file_when_a_background_replaced_the_pages_backdrop", "crates/edit/src/mark_transaction_tests.rs::background_changes_are_atomic_after_a_later_page_failure", "crates/edit/src/mark_transaction_tests.rs::replacements_commit_all_selected_pages_and_preserve_other_marks_and_shared_resources"]
notes = "Add and Update are atomic across all selected pages: errors preserve existing marks, page content/resources and pending edits (#5657). Remove also turns back on a page backdrop Add replaced, keeping edits made after it; where that isn't safe it says which pages keep it off"
[[feature]]
id = "edit.decoration-profiles"
+1 -1
View File
@@ -43,7 +43,7 @@ Other resource categories retain their existing parent-chain lookup.
| hayro | 0.7.1 | Apache-2.0 OR MIT | (1) `RenderSettings::{x_offset, y_offset}` to render one tile of a large page; (2) images over `MAX_IMAGE_PIXELS` (2^28) are skipped (a fuzzed `/W 4294967295` hung in resampling); (3) `tiling_cell_scale` keeps a tiling pattern's cell pixmap within 3000 px a side whatever its `/XStep`/`/YStep` (a fuzzed step far beyond `/BBox` allocated 2 GB); (4) stroke widths clamped to 4 × (canvas width + height) device pixels (a fuzzed `/LW 9223372036854775807` allocated 10 GB in stroke expansion); (5) `usable_dash_pattern`: a stroke whose dash pattern could cut it into more than `MAX_DASHES_PER_STROKE` (250,000) pieces, counting kurbo's restart of the pattern at every subpath and `ClosePath`, is drawn solid (a fuzzed `/D [[11] 0]` on a line from x = 92234775807 allocated over 5 GB, `[0.000001] 0 d` on a 20 pt line over 10 GB); (6) a dash pattern with a negative or non-finite entry, or a period that isn't positive, is drawn solid (`[-1 -1] 0 d` looped for ever in kurbo); (7) `render_size` and `render_into`: render into a buffer the caller allocates (PdfCraft renders into pixel-aligned memory that the GUI takes over as texture data); `render` is `render_into` on a new pixmap; (8) checked image source/target/RGBA, alpha-premultiplication scratch and intermediate sizes before resampling, finite transforms and exact source/mask buffers; sources wider than u16 may shrink before backend limits, with a 2^20 source-axis cap and conservative 128 MiB filter-planning estimate; an over-limit or failed resize keeps the original image resolution and geometry when the source fits the backend, otherwise skips it, with a logged warning; staging, resampling output/scratch, RGBA conversion and padding buffers use fallible reserves; (9) `may_paint_canvas`: a fill or stroke whose control-point box, grown by how far its paint reaches past the path (half the stroke width times the larger of the miter limit and √2) plus 0.5 user units and 2 pixels, misses the canvas is not drawn, so a tile no longer strokes and fills every path of its page (item 5 of #623); `set_skip_offscreen_paths` turns this off for the regression test; (10) `/Interpolate` governs the pre-resize too (#624): a minified image that does not request interpolation is pre-resized with nearest-neighbour, planned without the Catmull-Rom filter limits (`image_resampling_size` takes the flag); a Type 3 glyph image is sampled bicubically only when interpolated; a minified image with a matching soft mask is nearest-sampled straight into premultiplied RGBA; (11) `may_paint_rect`: an image whose stream-size box, mapped to the device, misses the canvas is skipped before decoding (decoded data can only shrink against that box), so a tile of an image-heavy page no longer decodes, resamples and rasterizes every image on it; (12) preview renders (`InterpreterSettings::preview`: backdrops, thumbnails, grid cells, signature-drag backgrounds) skip images under `PREVIEW_MIN_IMAGE_AREA` device pixels, while final renders always draw them; (13) reading colours (#897): `RenderSettings::color_replacement` takes a `ColorReplacement` (text colour, background, `only_black`, `line_art`) that remaps solid text and line-art paint while rendering, glyph outlines counting as text and stencil-mask ink as line art; images, image alpha masks, soft masks and pattern cells keep their colours; `render_pdf` gains a `color_replacement: Option<ColorReplacement>` argument (pass `None` for true colours); the upstream-only `[dev-dependencies.log]` entry is removed from `Cargo.toml` (log is a normal dependency since the logging patch), so `cargo test -p hayro` runs this crate's unit tests; (14) a shrunk, interpolated image whose axes lie along the device's (upright, mirrored or a quarter turn, as on a page under `/Rotate`) is snapped to whole device pixels: shrunk once to its rounded device rectangle and drawn 1:1 from the rounded corner, instead of a ceil-sized raster resampled again at a fractional scale and offset (`snap_minified_image`; scans looked soft next to Acrobat, and until #5530 a turned one still did, up to 200 grey levels off the same page drawn upright). An image counts as axis-aligned when the terms the snap drops move its far edges by at most a hundredth of a device pixel (`SNAP_SKEW`), not by a tolerance on the coefficients, which let a slight skew of a very wide image through; and the snapped 1:1 transform is used only when the shrink produced the snapped size, so a failed resize keeps the full transform instead of drawing the source raster at its source size; (15) a soft mask of another size than its image is filtered when shrunk, whatever its `/Interpolate` (#1649): such a mask carries the shape on its own (Word saves text as a tiny black image with a glyph-bitmap mask), and nearest-neighbour dropped every stroke thinner than the shrink factor; (16) under a soft mask or a blend mode, axial and radial shadings are sampled instead of drawn as native gradients (#Line truncated
| hayro-jbig2 | 0.3.0 | Apache-2.0 OR MIT | (1) at most 2^28 pixels per bitmap and page bitmap, and 2^25 cells per halftone grid and grayscale image (each side could be 65535: 4.3 billion pixels decoded one by one, and a 4-byte value per cell); (2) at most 2^26 symbol pixels per symbol dictionary (a fuzzed dictionary decoded for minutes); (3) a symbol dictionary's height classes are capped at one per new symbol and its export runs at `2 × symbols + 1`, each plus `EXTRA_EMPTY_STEPS` (1024): an empty height class or a zero-length export run doesn't advance, and past the end of its data the arithmetic decoder can decode them for ever (one changed byte hung the renderer); (4) a segment header's long-form referred-to segment count is capped at `u16::MAX` and a larger count is refused before its retention or referred-to bytes are read: the 29-bit count went straight to `Vec::with_capacity`, a reservation of about 2 GiB whose failure aborts the process (from storytold/craft-libs#176); (5) what a page's segments hold for later ones (intermediate regions, pattern and symbol dictionaries with their headers and retained contexts, and Huffman tables) is at most 64 MiB, two square bitmaps of 16,384 a side (`MAX_RETAINED_WORDS`), and a dictionary's new and exported symbols are counted against it as they are made: each was bounded on its own, but a few dozen bytes an intermediate region held 33 MB each, and 8 MiB symbols exported again and again killed the process, so a few kilobytes could exhaust memory; (6) a segment may refer to at most 2^20 symbols, checked before any are collected: references may repeat, and 65,535 of them to one dictionary, in a 78 KB stream, asked for 17 GB; (7) a pattern dictionary keeps at most 16 MiB of shifted copies, which only speed up drawing, and none that wouldn't fit what the page has left (`MAX_SHIFTED_WORDS`); (8) a custom Huffman table has at most 2^16 lines, and a stream with its globals at most 2^20 segments and 2^22 references, checked as they are read: both grew before anything counted them, and PDFs of a kilobyte or so reached 5 GB and more behind nested Flate; (9) a page past the bounds of (1) is refused when the stream is opened: a caller sizes its output from the header before the page bitmap is made, and an Indexed image in a 743-byte PDF asked for 137 GB, which aborts; (10) a stream may ask for at most 2^30 units of decoding work, four of the largest pages, about 6 s to 17 s (`MAX_WORK`): decoding a bitmap costs a pixel each and 4 a row, copying one a word each and 1 a row, and each integer an item reads costs 38, what one takes at worst, so one with no pixels pays too, before it is decoded: each bitmap was bounded, but nothing bounded how many there were, and a 795-byte PDF took 265 s; (12) adding to a location, a reference offset, a symbol's corner or a Huffman range line near the end of an `i32`, and negating a decoded integer of 2^31, overflowed: a panic wherever overflow is checked. The refinement context, a text region's corners, the integer decoder and the Huffman table wrap, as a release build did, and `Bitmap::combine` saturates, which comes to the same, as a location that overflows is past the end of any page. What is drawn doesn't change | (1) `raster::tests::jbig2_regions_of_billions_of_pixels_are_refused`, `raster::tests::jbig2_halftone_grids_past_their_bound_are_refused`; (2) the nightly `cargo xtask fuzz` finding, which now finishes in about a second; (3) `raster::tests::jbig2_symbol_dictionaries_that_never_advance_terminate`; (4) `segment::tests::test_referred_to_count_is_capped` (`cargo test --manifest-path vendor/hayro-jbig2/Cargo.toml`); (5) `raster::tests::jbig2_regions_held_past_a_pages_bound_are_refused`, `jbig2_symbols_without_pixels_count_towards_a_pages_bound`, `jbig2_retained_contexts_count_towards_a_pages_bound`, `jbig2_huffman_tables_count_towards_a_pages_bound`, `jbig2_new_symbols_count_towards_a_pages_bound`, `jbig2_new_symbols_are_held_to_what_a_page_has_left`, `jbig2_pattern_dictionaries_count_towards_a_pages_bound`, and in the crate (`cargo test --manifest-path vendor/hayro-jbig2/Cargo.toml`) `decode::symbol::tests::exported_symbols_are_counted_before_they_are_copied`, `tests::the_room_left_shrinks_as_segments_are_stored`; (6) `raster::tests::jbig2_segments_referring_to_too_many_symbols_are_refused`; (7) `raster::tests::jbig2_pattern_dictionaries_too_large_to_shift_still_draw`, `jbig2_shifted_patterns_never_refuse_an_image`; (8) `raster::tests::jbig2_huffman_tables_of_too_many_lines_are_refused`, `jbig2_streams_of_too_many_segments_are_refused`, `jbig2_streams_of_too_many_references_are_refused`, and in the crate `tests::the_segments_of_a_stream_and_its_globals_count_together`; (9) `raster::tests::jbig2_pages_past_the_bounds_are_refused_before_anything_is_sized_from_them`, `tests::a_page_past_the_bounds_is_refused_when_opened`; (10) `raster::tests::jbig2_decoding_work_is_counted_item_by_item`; (12) `raster::tests::jbig2_placements_at_the_endLine truncated
| lopdf | 0.45.0 | MIT | (1) PNG predictor rows longer than the data are refused before their buffers are allocated (a fuzzed `/Columns 4294967295` allocated two 4 GiB rows), and empty frames return without row buffers; (2) predictor row widths use saturating arithmetic or reject overflow; (3) sub-byte TIFF Predictor 2 scratch is bounded by the samples present in the input instead of the declared `/Colors`, aligned with [lopdf#589](https://github.com/J-F-Liu/lopdf/pull/589); (4) the object lookup keeps its cycle history through compressed objects, requires an ordinary in-file container, and caps the chain of indirect lookups at 16 (a chain of new objects, each a `/Length` compressed in a container whose own `/Length` names the next, or a stream whose `/Length` names the next stream, overflowed the stack: a dev build's 2 MiB thread within 800 hops); (5) object-stream members are parsed within their own extent (up to the next distinct offset), an entry whose offset repeats an earlier entry's is skipped (so a repeated object number can resolve to its earlier entry), and offsets are processed in index order; (6) `find_latest_trailer`: a rebuild takes a `/Type /XRef` stream dictionary as the trailer when the file has no `trailer` keyword (the latest in the file wins, as a later `trailer` would), so a concatenated or truncated file keeps its /Info and /ID instead of failing to load; a candidate whose /Root is the catalog beats one whose /Root is another dictionary, and an in-file /Root must match its generation (#2365) | (1) `inspect::tests::png_predictor_rows_longer_than_the_data_are_refused_before_allocating`, `inspect::tests::empty_png_predictor_frames_do_not_allocate_rows`; (2) `inspect::tests::tiff_subbyte_predictor_row_width_overflow_is_refused`; (3) `inspect::tests::tiff_subbyte_predictor_scratch_is_bounded_by_available_samples`, `inspect::tests::tiff_subbyte_predictors_keep_components_rows_and_padding`; (4) `inspect::tests::compressed_object_self_container_does_not_recurse`, `inspect::tests::compressed_object_mutual_containers_do_not_recurse`, `inspect::tests::object_stream_length_cycle_does_not_recurse`, `inspect::tests::compressed_object_container_chain_does_not_recurse`, `inspect::tests::compressed_length_chain_does_not_recurse`, `inspect::tests::plain_stream_length_chain_does_not_recurse`, `inspect::tests::compressed_objects_and_indirect_stream_length_still_load`, `inspect::tests::compressed_length_in_a_container_with_an_indirect_length_still_loads`; (5) `inspect::tests::object_stream_member_extents_bound_owned_strings`, `inspect::tests::object_stream_member_extents_preserve_index_order_and_whitespace`; (6) `inspect::tests::rebuilt_file_keeps_the_info_of_its_cross_reference_stream`, `inspect::tests::rebuilt_file_prefers_a_trailer_whose_root_is_the_catalog` |
| hayro-syntax | 0.7.2 | Apache-2.0 OR MIT | (1) Page-tree cycle guard in `resolve_pages` (visited set + depth cap): a `/Kids` loop among compressed objects overflowed the stack and aborted the process; (2) `ccitt_size_ok`: CCITT images wider than 2^20 columns or over 2^28 pixels are not decoded (a fuzzed `/Columns 4294967295` allocated 4 GiB); (3) Flate/LZW predictor row widths are saturating `usize`, a zero width is refused and a row longer than the data is not allocated (a fuzzed `/Columns 9223372036854775807` wrapped to a 2^61-byte allocation and aborted); (4) the inline-image end-of-data check (`EI`) doesn't nest inside its own look-ahead and examines at most 256 candidates and steps (50 images with "EI" in their data ran for over ten minutes); an EI followed by a delimiter (EI%..., EI[...) ends the image like one followed by white space; only a regular character after EI skips the candidate; (5) a stream whose `/Length` is wrong is recovered only when `stream` is the next token — scanning ahead to a later object's `stream` made an indirect appearance-state dictionary (Quartz checkboxes: `/AP /N` → `<< /Yes … /Off … >>`) render as a non-form, so the widget was skipped; (6) JPX rescaling uses an exact integer sample range for 1–32-bit components (32 shifted past u32, and floating-point maxima at 25–31 bits wrapped to zero), and refuses zero-sized rows; (7) `decode_limit`: Flate (through flate2 and the fallback inflater), LZW, RunLength and ASCII85 never write past `MAX_DECODED_STREAM` (256 MiB), or, for the last filter of an image of known size, past twice its pixel bytes (a predictor tag byte per byte), at most 1 GiB; `Stream::decoded_within` for budgeted callers; a page's `/Contents` array shares one `MAX_DECODED_STREAM` (a 2 MB page whose content stream or 8 × 8 image inflated to 2 GB took the renderer past 3 GB in under a second; naming the stream twenty times in `/Contents`, 5 GB); (8) high-precision numbers (jsPDF MediaBox coordinates with over 19 digits) parse without overflowing the u64 mantissa: fractional digits past it are dropped, integer digits past it scale the value (a real, kept finite); (9) large dictionary indexes are built on first use and shared across repeated reads within each PDF (#307); the validated-byte cache is bounded, reader contexts remain separate, repairs and inline/content dictionaries bypass sharing, and small dictionaries stay eager; (10) decoded object-stream slots publish once under contention, cold loading rejects recursive dependencies, and xref repair serializes without holding recursive read guards; this permits one parser per native render pool with private worker caches; (11) `sync.rs`: a poisoned lock is recovered instead of unwrapped (a worker panic no longer cascades into every reader of the same PDF), and xref repair takes a blocking write lock instead of asserting a non-blocking one; (12) `SegmentList` (`util.rs`) returns `None` for an out-of-range index instead of panicking; (13) a page's `/UserUnit` scales `render_dimensions` and `initial_transform`, so the page and everything on it are sized in points, as Acrobat shows them; it is read as Acrobat reads it (the page's own entry, not inherited; a number from 1 up, at most 75,000; anything else counts as 1), and a page without it keeps exactly the transform it had; (14) revision 2–4 passwords are tried as given and then in PDFDocEncoding (`legacy_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Convert to PDFDocEncoding`): passwords arrive as UTF-8 text, so a password with characters outside ASCII (`Çok güzel`, `ılık€`) written in PDFDocEncoding, as ISO 32000-2 §7.6.4.3.2 asks and qpdf and Acrobat write it, was always wrong; (15) page content is read a piece at a time (`page::ContentReader`, `Page::content_reader`): plain streams and Flate streams without a predictor are decoded as they are read, with a budget of 64 times their compressed size and never less than `MAX_DECODED_STREAM` (a stream that expands past it is cut and reported); other streams are decoded whole, as before, and share `MAX_DECODED_STREAM`. The content tokenizer reads a window at a time (`UntypedIter::new_window`, `TypedIter::needs_more`, `TypedIter::committed`): an instruction that runs past the window is not decided until more data follows, which `Reader` records by flagging reads and `at_end` past the end of the data, including through the clones the parser makes. The Flate decoder keeps its own 32 KiB history, so it pauses at any output size. `ContentReader::new` reuses raw/decrypted stream bytes for budget accounting and piece creation, and `decoded_raw_within` applies the existing Whole-stream filters and limits to those bytes without decrypting twice; (16) revision 5–6 (AES-256) passwords are tried in their SASLprep form (RFC 4013, then UTF-8, at most 127 bytes, as ISO 32000-2 §7.6.4.3.3 Algorithm 2.A asks and pdfcraft-crypt writes them) and then, if that differs, as given (`aes256_passwLine truncated
| hayro-syntax | 0.7.2 | Apache-2.0 OR MIT | (1) Page-tree cycle guard in `resolve_pages` (visited set + depth cap): a `/Kids` loop among compressed objects overflowed the stack and aborted the process; (2) `ccitt_size_ok`: CCITT images wider than 2^20 columns or over 2^28 pixels are not decoded (a fuzzed `/Columns 4294967295` allocated 4 GiB); (3) Flate/LZW predictor row widths are saturating `usize`, a zero width is refused and a row longer than the data is not allocated (a fuzzed `/Columns 9223372036854775807` wrapped to a 2^61-byte allocation and aborted); (4) the inline-image end-of-data check (`EI`) doesn't nest inside its own look-ahead and examines at most 256 candidates and steps (50 images with "EI" in their data ran for over ten minutes); an EI followed by a delimiter (EI%..., EI[...) ends the image like one followed by white space; only a regular character after EI skips the candidate; (5) a stream whose `/Length` is wrong is recovered only when `stream` is the next token — scanning ahead to a later object's `stream` made an indirect appearance-state dictionary (Quartz checkboxes: `/AP /N` → `<< /Yes … /Off … >>`) render as a non-form, so the widget was skipped; (6) JPX rescaling uses an exact integer sample range for 1–32-bit components (32 shifted past u32, and floating-point maxima at 25–31 bits wrapped to zero), and refuses zero-sized rows; (7) `decode_limit`: Flate (through flate2 and the fallback inflater), LZW, RunLength and ASCII85 never write past `MAX_DECODED_STREAM` (256 MiB), or, for the last filter of an image of known size, past twice its pixel bytes (a predictor tag byte per byte), at most 1 GiB; `Stream::decoded_within` for budgeted callers; a page's `/Contents` array shares one `MAX_DECODED_STREAM` (a 2 MB page whose content stream or 8 × 8 image inflated to 2 GB took the renderer past 3 GB in under a second; naming the stream twenty times in `/Contents`, 5 GB); (8) high-precision numbers (jsPDF MediaBox coordinates with over 19 digits) parse without overflowing the u64 mantissa: fractional digits past it are dropped, integer digits past it scale the value (a real, kept finite); (9) large dictionary indexes are built on first use and shared across repeated reads within each PDF (#307); the validated-byte cache is bounded, reader contexts remain separate, repairs and inline/content dictionaries bypass sharing, and small dictionaries stay eager; (10) decoded object-stream slots publish once under contention, cold loading rejects recursive dependencies, and xref repair serializes without holding recursive read guards; this permits one parser per native render pool with private worker caches; (11) `sync.rs`: a poisoned lock is recovered instead of unwrapped (a worker panic no longer cascades into every reader of the same PDF), and xref repair takes a blocking write lock instead of asserting a non-blocking one; (12) `SegmentList` (`util.rs`) returns `None` for an out-of-range index instead of panicking; (13) a page's `/UserUnit` scales `render_dimensions` and `initial_transform`, so the page and everything on it are sized in points, as Acrobat shows them; it is read as Acrobat reads it (the page's own entry, not inherited; a number from 1 up, at most 75,000; anything else counts as 1), and a page without it keeps exactly the transform it had; (14) revision 2–4 passwords are tried as given and then in PDFDocEncoding (`legacy_passwords` in `crypto/mod.rs`, which resolves the upstream `TODO: Convert to PDFDocEncoding`): passwords arrive as UTF-8 text, so a password with characters outside ASCII (`Çok güzel`, `ılık€`) written in PDFDocEncoding, as ISO 32000-2 §7.6.4.3.2 asks and qpdf and Acrobat write it, was always wrong; (15) page content is read a piece at a time (`page::ContentReader`, `Page::content_reader`): plain streams and Flate streams without a predictor are decoded as they are read, with a budget of 64 times their compressed size and never less than `MAX_DECODED_STREAM` (a stream that expands past it is cut and reported); other streams are decoded whole, as before, and share `MAX_DECODED_STREAM`. The content tokenizer reads a window at a time (`UntypedIter::new_window`, `TypedIter::needs_more`, `TypedIter::committed`): an instruction that runs past the window is not decided until more data follows, which `Reader` records by flagging reads and `at_end` past the end of the data, including through the clones the parser makes. The Flate decoder keeps its own 32 KiB history, so it pauses at any output size. `ContentReader::new` reuses raw/decrypted stream bytes for budget accounting and piece creation, and `decoded_raw_within` applies the existing Whole-stream filters and limits to those bytes without decrypting twice; (16) revision 5–6 (AES-256) passwords are tried in their SASLprep form (RFC 4013, then UTF-8, at most 127 bytes, as ISO 32000-2 §7.6.4.3.3 Algorithm 2.A asks and pdfcraft-crypt writes them) and then, if that differs, as given (`aes256_passwLine truncated
| winit | 0.30.13 | Apache-2.0 | (1) on Windows 11 (build 22000 and later), `WM_DPICHANGED` applies the rect Windows suggests. It used to nudge the window onto the monitor `MonitorFromWindow` names, which during a drag is still the monitor being left; the nudge sent another `WM_DPICHANGED`, so a window dragged to a monitor with another scale factor grew and stayed on the wrong monitor at the wrong scale (#324). Backport of winit master 488c036a ([winit#4341](https://github.com/rust-windowing/winit/pull/4341)), which no 0.30 release has; Windows 10 keeps the old adjustment, as on winit master. (2) on Wayland, a seat's text input is destroyed when the seat goes away, not whenever it loses a capability: losing any capability (a touch screen or tablet unplugged, a remote-desktop session ending) destroyed it, and only an added capability recreated it, so IME stopped working until restart. Port of [winit#4747](https://github.com/rust-windowing/winit/pull/4747); (3) on Windows, an IME composition reports its cursor from `GCS_CURSORPOS` only when `WM_IME_COMPOSITION` says it is set, and at the end of the composition otherwise: the Microsoft Korean IME never sets it, so the cursor read as 0 (egui then drew no caret while composing; it now draws it after the syllable). Port of [winit#4746](https://github.com/rust-windowing/winit/pull/4746); (4) on Windows, a hidden window is not maximized until it is shown, and a hidden window shown while maximized gets one `ShowWindow(SW_MAXIMIZE)`: `SW_MAXIMIZE` shows a hidden window, so PdfCraft, which eframe keeps hidden until its first frame is drawn, appeared unpainted (white) when it restored a maximized window, and could lose its focus. Port of [winit#4587](https://github.com/rust-windowing/winit/pull/4587) (the later, focus-safe form of [winit#4575](https://github.com/rust-windowing/winit/pull/4575)); (5) on X11, when allowing or disallowing IME replaces the focused window's input context (egui does it each time a text field gains or loses focus), the new context is focused: no focus event follows, so it stayed unfocused until the window lost and regained focus. Port of [winit#4727](https://github.com/rust-windowing/winit/pull/4727); (6) on macOS, `insertText` commits through IME when a composition was started (`pending_commit`, set by `setMarkedText`) rather than when marked text is left: input methods that end a composition with `unmarkText` before `insertText` lost the text, and Apple Korean dropped the key typed after a syllable (`한` then `5` or `;`); other `insertText` calls stay `KeyboardInput`; a commit outside a key press (a candidate clicked with the mouse, dictation) clears the marked text and leaves no key to swallow, as in [winit#4748](https://github.com/rust-windowing/winit/pull/4748) (without it the next key, such as Backspace, was lost). `validAttributesForMarkedText` lists the underline and marked-clause attributes, without which some input methods don't compose. Port of [winit#4650](https://github.com/rust-windowing/winit/pull/4650), the 0.30 backport of [winit#4651](https://github.com/rust-windowing/winit/pull/4651) (merged on winit master), with the underline attribute spelled as AppKit's `NSUnderlineStyleAttributeName` (`NSUnderline`); (7) on macOS, disallowing IME with a composition in progress (focus leaving a text field) tells the input method to discard its marked text (`discardMarkedText`): it kept composing it once IME was allowed again, so the abandoned syllable came back (`하`, then `가` typed in the next field, became `학`, then `하` + `가`; Japanese `か` then `さ` became `傘`). Port of [winit#4745](https://github.com/rust-windowing/winit/pull/4745); (8) on macOS, text inserted outside a key press without a composition (the emoji picker) is reported as `Ime::Commit`; it was dropped. Port of the emoji-picker part of [winit#4749](https://github.com/rust-windowing/winit/pull/4749) (0.30 backport of [winit#4748](https://github.com/rust-windowing/winit/pull/4748)); its `selectedRange` change for dictation is left out because it switches on press-and-hold for every held key (an accent menu instead of key repeat, and the chosen accent added after the repeated letters); (9) on macOS, a key whose text was committed through IME isn't also sent as `KeyboardInput` unless AppKit forwards it as a command (Enter): Apple Korean answers Space with no syllable in progress with `setMarkedText(" ")`, `insertText(" ")`, `setMarkedText("")`, and the last call reset winit's state, so the space arrived twice. Same goal as [winit#4478](https://github.com/rust-windowing/winit/pull/4478), whose changes don't reach this call order (macOS 14); to be proposed upstream there; (10) on macOS, when the first key in a fresh app reaches Apple Korean's `insertText` as a raw compatibility jamo instead of starting a composition, that key is interpreted once more, synchronously, before it is sent as `KeyboardInput` (g k s typed ㅎㅏㄴ instead of 한); only an unmodified, Line truncated
| egui-wgpu | 0.36.2 | MIT OR Apache-2.0 | (1) `winit::surface_fit`: a window's surface is configured within the device's `max_texture_dimension_2d`, both sides shrunk by one factor that egui then draws at (`pixels_per_point × render_scale`), so the whole window is drawn into the surface (on DX12 it is stretched over the window and lines up with the pointer; wgpu's GL backend copies it unscaled into a corner); the longer side becomes exactly the limit; the depth and MSAA textures follow, and a recreated surface starts again from the window's own size. egui-wgpu configured the window's size as is, and `Surface::configure` panics beyond the limit: a window restored at another monitor's scale (opening an Outlook attachment on a mixed-DPI laptop asked an 8192-pixel device for 8600 × 3423, #577) or stretched across monitors closed PdfCraft, before its window appeared when it happened at start-up ([emilk/egui#8361](https://github.com/emilk/egui/issues/8361)). The published crate leaves out egui's licence files; `LICENSE-APACHE` and `LICENSE-MIT` are from the 0.36.2 tag; (2) `winit::catch_errors`: a new window's surface is configured inside wgpu error scopes (validation, out of memory, internal), and a failure is returned as `WgpuError::ConfigureSurface` (for the root window at start-up eframe returns it as `Error::Wgpu`, which PdfCraft retries with OpenGL); nothing is kept for the window. wgpu's default handler panicked instead, and eframe configures the root surface before the app is created, so a driver that can't configure one closed PdfCraft at launch (a 2015 Intel GPU through wgpu's GL backend timed out waiting for the GPU to go idle, `GpuWaitTimeout`, #519). Unchanged, so still a panic: an error in a later reconfigure (resize, a lost surface), a device lost during the first configure (wgpu reports it only to a callback), and a window shown at zero size (first configured on resize) | (1) `pdfcraft` `tests::a_window_larger_than_the_gpu_limit_gets_a_surface_within_it`, `tests::surface_fit_never_empties_or_overflows_a_surface`, and `tests::vendor_provenance_egui_wgpu_surface_fit_identity`, which keeps the patch in the build and in the paths that size a surface; (2) `pdfcraft` `tests::a_gpu_error_while_a_window_is_set_up_is_returned_not_a_panic` (a real device: an error inside `catch_errors` is returned, not a panic) and `tests::vendor_provenance_egui_wgpu_catch_errors_identity`, which keeps it around `add_surface`'s configure |
| vello_common | 0.0.8 | Apache-2.0 OR MIT | (1) `clip::intersect` (the clip step every clipped path passes through) starts its row walk at the first row both paths have strips in, not the earlier of the two first rows. The walk visited every row from the top of the clip for each path (on the A1 sample's full-page canvas, about half its strip rows per stroke), and rows where one path has no strips produce no output, so the strips are unchanged (vello_common 0.1 starts at the later row too). Its cost grew with the page, and a full-page render of the A1 sample was about 30% faster; the output is byte-identical | (1) `clip::tests::intersect_walks_only_rows_both_paths_have_strips` counts the rows the walk visits (`cargo test --manifest-path vendor/vello_common/Cargo.toml`) and fails without the patch; the render crate's pixel tests run through the patched crate |
+123 -2
View File
@@ -4,6 +4,7 @@ use crate::crypto::{DecryptionError, DecryptionTarget, Decryptor, get};
use crate::data::Data;
use crate::metadata::Metadata;
use crate::object::Name;
use crate::object::Number;
use crate::object::ObjectIdentifier;
use crate::object::Stream;
use crate::object::dict::keys::{
@@ -80,6 +81,65 @@ pub(crate) fn fallback(data: PdfData, password: &[u8]) -> Option<XRef> {
}
}
/// PdfCraft patch: an `N G obj` header for the repair scan, taking a generation number that
/// cannot be read as 0.
///
/// A generation number is at most 65,535 (ISO 32000-2 §7.5.4), so `3 18446744073709551616 obj` is
/// malformed and [`ObjectIdentifier::read`] is right to refuse it everywhere else. This scan runs
/// only when a file's cross-reference table is unusable and its objects are being recovered by
/// reading the file, where refusing the header drops the object and whatever it holds (#5580).
/// Before #427 the digits wrapped, and 2^64 wrapped to exactly 0, which is the only reason such a
/// file used to open.
///
/// Only here: reading numbers anywhere else is unchanged.
fn read_object_header<'a>(r: &mut Reader<'a>, ctx: &ReaderContext<'a>) -> Option<ObjectIdentifier> {
let mut strict = r.clone();
if let Some(obj_id) = strict.read::<ObjectIdentifier>(ctx) {
*r = strict;
return Some(obj_id);
}
// On a clone as well, so a header that isn't one leaves `r` where it was for the caller.
let mut lenient = r.clone();
let obj_number = lenient.read_without_context::<i32>()?;
lenient.skip_white_spaces_and_comments();
// Any number at all in the generation position, including one no generation may be.
lenient.skip::<Number>(false)?;
lenient.skip_white_spaces_and_comments();
lenient.forward_tag(b"obj")?;
*r = lenient;
Some(ObjectIdentifier::new(obj_number, 0))
}
/// PdfCraft patch: the body of the object at `offset` whose `N G obj` header cannot be read
/// strictly, for a table rebuilt by scanning the file (#5580). The steps are
/// `IndirectObject::read`'s, with [`read_object_header`] in place of the strict identifier.
fn read_repaired_body<'a, T>(
data: &'a [u8],
offset: usize,
id: ObjectIdentifier,
ctx: &ReaderContext<'a>,
) -> Option<T>
where
T: ObjectLike<'a>,
{
let mut r = Reader::new(data);
r.jump(offset);
// The number is what identifies the object; the generation is what could not be read.
if read_object_header(&mut r, ctx)?.obj_number != id.obj_number {
return None;
}
let mut ctx = ctx.clone();
if ctx.parent_chain_contains(&id) {
warn!("cycle detected in indirect object: {id:?}");
return None;
}
ctx.set_obj_number(id);
ctx.parent_chain_push(id);
r.skip_white_spaces_and_comments();
r.read_with_context::<T>(&ctx)
}
fn fallback_xref_map<'a>(data: &'a PdfData, password: &[u8]) -> (XrefMap, Option<XRefInput<'a>>) {
fallback_xref_map_inner(data, ReaderContext::dummy(), true, password)
}
@@ -91,6 +151,10 @@ fn fallback_xref_map_inner<'a>(
password: &[u8],
) -> (XrefMap, Option<XRefInput<'a>>) {
let mut xref_map = FxHashMap::default();
// PdfCraft patch: the generation-0 keys below that stand in for a header with another
// generation, so a later header can replace one while a real `N 0 obj` is never displaced
// (noted in review of #5580).
let mut aliases: rustc_hash::FxHashSet<ObjectIdentifier> = rustc_hash::FxHashSet::default();
let mut trailer_dicts = vec![];
let mut root_ref = None;
@@ -105,12 +169,32 @@ fn fallback_xref_map_inner<'a>(
// First try to check if we have an object identifier.
if r.peek_byte().is_some_and(|b: u8| b.is_ascii_digit()) {
if let Some(obj_id) = r.read::<ObjectIdentifier>(&dummy_ctx) {
if let Some(obj_id) = read_object_header(&mut r, &dummy_ctx) {
let mut cloned = r.clone();
// Check that the object following it is actually valid before inserting it.
cloned.skip_white_spaces_and_comments();
if cloned.skip::<Object<'_>>(false).is_some() {
xref_map.insert(obj_id, EntryType::Normal(cur_pos));
// PdfCraft patch: also reachable by object number alone, so a reference that
// names a different generation than the header still finds it. A rebuilt
// table has no revision history to tell two generations apart, and a file
// that needs rebuilding references everything as `N 0 R` whatever its headers
// say: `poppler-85140-0.pdf` has one page whose header reads
// `3 18446744073709551616 obj` with a page tree pointing at `3 0 R`, so the
// page was lost and the file did not open at all (#5580). `or_insert`, so a
// real `N 0 obj` is never displaced by this alias.
let by_number = ObjectIdentifier::new(obj_id.obj_number, 0);
if obj_id.gen_number == 0 {
// A real `N 0 obj`: it owns the key from here on, and the last one wins
// as every other entry does.
aliases.remove(&by_number);
} else if !xref_map.contains_key(&by_number) || aliases.contains(&by_number) {
// Stand in for it, and let a later header for the same number replace the
// stand-in -- the exact key moves on, so an alias left behind would send
// `N 0 R` to a body the exact key no longer names (noted in review).
xref_map.insert(by_number, EntryType::Normal(cur_pos));
aliases.insert(by_number);
}
last_obj_num = Some(obj_id);
dummy_ctx.set_obj_number(obj_id);
}
@@ -498,6 +582,14 @@ impl XRef {
// Try to yield in the order the objects appeared in the
// PDF.
elements.sort_by(|e1, e2| e1.1.cmp(&e2.1));
// PdfCraft patch: one object per location. A rebuilt table can hold two keys for
// one object -- its own generation and the generation-0 stand-in (#5580) -- and
// enumeration yielded the object once for each, so a document recovered by
// `Pages::new_brute_force` reported the page twice (noted in review). Both keys
// stay for lookups; only this walk is deduplicated. The object number is part of
// the key: an object stream at (offset, 0) and its first member, also
// (offset, 0), are two objects.
elements.dedup_by(|a, b| a.1 == b.1 && a.0.obj_number == b.0.obj_number);
let mut iter = elements.into_iter();
@@ -653,10 +745,27 @@ impl XRef {
}
if let Some(object) = r.read_with_context::<IndirectObject<T>>(&ctx) {
if object.id() == &id {
// PdfCraft patch: in a table rebuilt by scanning the file, the object number
// is what identifies an object. There is no revision history to tell two
// generations apart, the scan already files objects found in object streams
// under generation 0, and a malformed generation in a header would otherwise
// make the object unreadable through the reference that names it (#5580). A
// table read from the file's own xref keeps the exact match.
if object.id() == &id || (repaired && object.id().obj_number == id.obj_number) {
return Some(Fetched::Object(object.get()));
}
} else {
// PdfCraft patch: the strict read of the header failed. In a table rebuilt by
// scanning the file that can be a generation number no generation may be --
// `3 18446744073709551616 obj` -- and refusing it loses the object the
// reference names (#5580). The object number still has to be the one asked
// for; only an unreadable generation is tolerated, and only here.
if repaired
&& let Some(object) =
read_repaired_body::<T>(repr.data.get().as_ref(), offset, id, &ctx)
{
return Some(Fetched::Object(object));
}
// There is a valid object at the offset, it's just not of the type the caller
// expected, which is fine.
if r.skip::<IndirectObject<Object<'_>>>(false).is_some() {
@@ -1734,6 +1843,18 @@ mod tests {
}
}
#[test]
fn an_object_stream_and_its_first_member_are_both_enumerated() {
// Both sit at (stream offset, 0) in `objects`' ordering; one object per location must
// not cost either of them.
let pdf = crate::Pdf::new(object_stream_fixture(false)).unwrap();
let objects: Vec<_> = pdf.xref().objects().into_iter().collect();
assert!(objects.iter().any(|o| matches!(o, Object::Stream(_))));
assert!(objects.iter().any(
|o| matches!(o, Object::Dict(d) if d.get::<i32>(b"Marker") == Some(123))
));
}
#[test]
fn recursive_object_stream_locations_fail_without_recursing() {
let pdf = crate::Pdf::new(object_stream_fixture(true)).unwrap();