From 51edea9894ae54d23e869443fc615ee11e419c3f Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Sat, 17 Oct 2026 23:51:25 +0800 Subject: [PATCH 01/30] M7: pick pictures where they show, not across transparent margins A picture with a soft mask, a stencil or colour-key /Mask, or /ImageMask is hit only where it shows: Edit text & images selection and hover, image_hit and Copy Image. Its opacity is read once per document generation onto a grid of at most 256 x 256 cells. Form artwork and pictures that can't be decoded keep their whole box. Co-Authored-By: Claude Opus 5.5 --- crates/automation/src/dispatch.rs | 8 +- crates/automation/src/tools.rs | 2 +- crates/automation/tests/it/automation.rs | 47 ++++++ crates/engine/src/copy_image.rs | 2 +- crates/engine/src/document.rs | 2 + crates/engine/src/image_alpha.rs | 152 ++++++++++++++++++ crates/engine/src/lib.rs | 1 + crates/engine/src/open.rs | 1 + crates/engine/src/tests.rs | 142 +++++++++++++++- crates/ui-egui/src/canvas.rs | 7 +- .../ui-egui/src/tools/edit_text_ui/image.rs | 18 ++- crates/ui-egui/tests/it/editing.rs | 65 ++++++++ docs/editing-images.md | 9 +- parity/acrobat-features.toml | 4 +- 14 files changed, 445 insertions(+), 15 deletions(-) create mode 100644 crates/engine/src/image_alpha.rs diff --git a/crates/automation/src/dispatch.rs b/crates/automation/src/dispatch.rs index 36e0d00454..9066735b1e 100644 --- a/crates/automation/src/dispatch.rs +++ b/crates/automation/src/dispatch.rs @@ -339,7 +339,13 @@ impl Automation { let doc = self.doc(&a)?; let p = &doc.info.pages[page]; let user = p.view_to_user(point[0] as f32, point[1] as f32).map(f64::from); - let images: Vec<_> = doc.page_images(page).iter().enumerate().filter(|(_, im)| im.contains(user)).map(|(i, _)| i + 1).collect(); + let images: Vec<_> = doc + .page_images(page) + .iter() + .enumerate() + .filter(|(_, im)| im.contains(user) && doc.image_shows_at(im, user)) + .map(|(i, _)| i + 1) + .collect(); json!({"page":page+1,"images":images}) } "page_images" => { diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index c6c200cece..696855e0b6 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -1370,7 +1370,7 @@ pub fn tools() -> Vec { .ro() .cmd("edit.edit_text") .with(schema(json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 } }), &["doc", "page"])), - t("image_hit", "Hit test page artwork", "List image/Form numbers whose placement and all clipping paths contain point [x,y] in top-left-origin points. Bezier curves, even-odd/nonzero fill and holes are respected. Read only.") + t("image_hit", "Hit test page artwork", "List image/Form numbers whose placement and all clipping paths contain point [x,y] in top-left-origin points. Bezier curves, even-odd/nonzero fill and holes are respected; a picture with transparency (soft mask, /Mask, stencil) counts only where it shows. Read only.") .ro() .cmd("edit.edit_text") .with(schema(json!({"doc":doc(),"page":{"type":"integer","minimum":1},"point":{"type":"array","items":{"type":"number"},"minItems":2,"maxItems":2}}), &["doc","page","point"])), diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index 6a5765b911..d13191f60d 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -10190,3 +10190,50 @@ fn simple_rule_scan_drawn(content: &[u8]) -> Vec { } write_full(&doc, &SaveOptions::default()).unwrap() } + +/// `image_hit` counts a picture with transparency only where it shows: through a soft-masked +/// picture's transparent margin, only the picture below is hit. +#[test] +fn image_hit_sees_through_transparent_parts_of_pictures() { + let dir = workdir("alpha-hit"); + let stream = |dict: &str, data: &[u8]| { + let mut o = format!("<< {dict} /Length {} >>\nstream\n", data.len()).into_bytes(); + o.extend_from_slice(data); + o.extend_from_slice(b"\nendstream"); + o + }; + let image = "/Type /XObject /Subtype /Image /Width 4 /Height 4 /BitsPerComponent 8"; + // The soft mask shows the top-right quarter only. + let mask: Vec = [[0, 0, 255, 255], [0, 0, 255, 255], [0; 4], [0; 4]].concat(); + let objs: Vec> = vec![ + b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 300] >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /Contents 4 0 R /Resources << /XObject << /Low 5 0 R /Top 6 0 R >> >> >>".to_vec(), + stream("", b"q 100 0 0 100 20 20 cm /Low Do Q q 100 0 0 100 60 60 cm /Top Do Q"), + stream(&format!("{image} /ColorSpace /DeviceRGB"), &[0x80; 48]), + stream(&format!("{image} /ColorSpace /DeviceRGB /SMask 7 0 R"), &[0x40; 48]), + stream(&format!("{image} /ColorSpace /DeviceGray"), &mask), + ]; + let mut out = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes()); + out.extend_from_slice(o); + out.extend_from_slice(b"\nendobj\n"); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offsets { + out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + std::fs::write(dir.join("overlap.pdf"), out).unwrap(); + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({"path":"overlap.pdf"}))["doc"].as_u64().unwrap(); + let hit = |a: &mut Automation, x: i32, y: i32| ok(a, "image_hit", json!({"doc":doc,"page":1,"point":[x, 300 - y]}))["images"].clone(); + assert_eq!(hit(&mut a, 70, 70), json!([1]), "the top picture's transparent margin"); + assert_eq!(hit(&mut a, 115, 115), json!([1, 2]), "where the top picture shows"); + assert_eq!(hit(&mut a, 150, 70), json!([]), "transparent, over nothing"); + assert_eq!(hit(&mut a, 150, 150), json!([2])); +} diff --git a/crates/engine/src/copy_image.rs b/crates/engine/src/copy_image.rs index b377903ee4..8a026bec03 100644 --- a/crates/engine/src/copy_image.rs +++ b/crates/engine/src/copy_image.rs @@ -22,7 +22,7 @@ impl Document { self.page_images(page).iter().rposition(|i| { inside(&i.rect) && match (i.is_form, i.object) { - (false, Some(_)) => true, + (false, Some(_)) => self.image_shows_at(i, at), (true, Some(form)) => picture_in_form(&editor.cos, form).is_some(), _ => false, } diff --git a/crates/engine/src/document.rs b/crates/engine/src/document.rs index fa98a18417..15a98f339a 100644 --- a/crates/engine/src/document.rs +++ b/crates/engine/src/document.rs @@ -63,6 +63,8 @@ pub struct Document { /// [`EditNotice`]): text its fonts can't draw, pages whose own backdrop stays off. The /// interface shows it; tools return it. pub edit_notices: Vec, + /// Which parts of pictures with transparency show, for picking them ([`Document::image_shows_at`]). + pub(crate) alpha: crate::image_alpha::AlphaCache, } /// Something the last successful edit did that the user should hear about, never left silent diff --git a/crates/engine/src/image_alpha.rs b/crates/engine/src/image_alpha.rs new file mode 100644 index 0000000000..9e6b50d181 --- /dev/null +++ b/crates/engine/src/image_alpha.rs @@ -0,0 +1,152 @@ +//! Edit text & images: a picture is picked where it shows, not across its whole box. A PNG +//! signature or a cut-out photo with a transparent margin overlaps its neighbours; clicking a +//! neighbour through that margin picked the transparent picture on top. +//! +//! A picture with transparency (a soft mask, a stencil or colour-key `/Mask`, or a stencil image +//! `/ImageMask`) gets an opacity grid of at most [`MAX_GRID`] cells a side, built once from its +//! pixels and kept until the document changes. A cell counts as opaque if any pixel +//! in it is: thin strokes and the edges of a shape stay easy to pick. Pictures without +//! transparency, Form artwork, and pictures that can't be decoded keep their whole box. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use pdfcraft_cos::{ObjRef, Object}; + +use crate::Document; + +/// The opacity grid's largest side, in cells. +const MAX_GRID: u32 = 256; +/// Grids kept at once (at most 64 KiB each); past this the cache starts over. +const MAX_CACHED: usize = 256; +/// Pictures larger than this many pixels keep their whole box rather than being decoded. +const MAX_DECODE_PIXELS: u64 = 64_000_000; +/// Alpha at or above this (of 255) counts as showing. +const OPAQUE: u8 = 16; + +/// Which cells of a picture show, row 0 at the top of the picture. +#[derive(Debug)] +pub(crate) struct Opacity { + width: u32, + height: u32, + cells: Vec, +} + +/// Opacity grids by picture object, for the document generation they were built at; `None` for +/// a picture that is opaque everywhere or couldn't be read (its whole box counts). The +/// generation, not the picture object alone, says when to rebuild: an edit may change the +/// picture's soft mask without touching the picture. +type Grids = (u64, HashMap>>); + +#[derive(Default)] +pub(crate) struct AlphaCache(Mutex); + +impl Document { + /// Whether `image` shows at user-space `point` (assumed inside its placement): `false` only + /// where a picture with transparency is see-through. Form artwork, pictures without + /// transparency and pictures that can't be read show everywhere in their box. + pub fn image_shows_at(&self, image: &pdfcraft_edit::PageImage, point: [f64; 2]) -> bool { + if image.is_form { + return true; + } + let Some(object) = image.object else { return true }; + let Some(grid) = self.opacity(object) else { return true }; + let Some((x, y)) = unit_point(image.matrix, point) else { return true }; + if !(0.0..=1.0).contains(&x) || !(0.0..=1.0).contains(&y) { + return true; + } + // Image space: row 0 is the top of the unit square (y = 1). + let col = ((x * f64::from(grid.width)) as u32).min(grid.width.saturating_sub(1)); + let row = (((1.0 - y) * f64::from(grid.height)) as u32).min(grid.height.saturating_sub(1)); + let at = usize::try_from(u64::from(row) * u64::from(grid.width) + u64::from(col)).unwrap_or(usize::MAX); + grid.cells.get(at).copied().unwrap_or(true) + } + + /// The opacity grid of picture `object`, built on first use and kept until the document + /// changes. + fn opacity(&self, object: ObjRef) -> Option> { + let editor = self.editor.as_ref()?; + // A poisoned cache is only a cache: build without it. + if let Ok(cache) = self.alpha.0.lock() + && cache.0 == self.generation + && let Some(grid) = cache.1.get(&object) + { + return grid.clone(); + } + let grid = build(&editor.cos, object).map(Arc::new); + if let Ok(mut cache) = self.alpha.0.lock() { + if cache.0 != self.generation || cache.1.len() >= MAX_CACHED { + *cache = (self.generation, HashMap::new()); + } + cache.1.insert(object, grid.clone()); + } + grid + } +} + +/// The picture's opacity grid, or `None` when it is opaque everywhere or can't be read. +fn build(cos: &pdfcraft_cos::Document, object: ObjRef) -> Option { + let current = cos.get(object); + let Object::Stream(s) = &*current else { return None }; + let flag = |key: &[u8]| s.dict.get(key).is_some_and(|v| matches!(&*cos.resolve(v), Object::Bool(true))); + let stencil = flag(b"ImageMask"); + let soft = s.dict.get(b"SMask").is_some_and(|v| cos.resolve(v).as_name() != Some(b"None")); + let in_data = s.dict.int(b"SMaskInData").is_some_and(|v| v != 0); + if !(stencil || soft || in_data || s.dict.get(b"Mask").is_some()) { + return None; + } + let size = |key: &[u8]| u64::try_from(s.dict.int(key).unwrap_or(0)).unwrap_or(0); + if size(b"Width").saturating_mul(size(b"Height")) > MAX_DECODE_PIXELS { + return None; + } + let (_, bytes) = pdfcraft_create::image_file(cos, object).ok()?; + let format = image::guess_format(&bytes).ok()?; + let mut reader = image::ImageReader::with_format(std::io::Cursor::new(bytes.as_slice()), format); + let mut limits = image::Limits::default(); + limits.max_alloc = Some(MAX_DECODE_PIXELS.saturating_mul(4)); + reader.limits(limits); + let picture = reader.decode().ok()?; + let (w, h) = (picture.width(), picture.height()); + if w == 0 || h == 0 { + return None; + } + let shows: Box bool> = if picture.color().has_alpha() { + let rgba = picture.into_rgba8(); + Box::new(move |x, y| rgba.get_pixel_checked(x, y).is_none_or(|p| p.0[3] >= OPAQUE)) + } else if stencil { + // The export draws a stencil image's painted samples white, whatever its `/Decode`. + let luma = picture.into_luma8(); + Box::new(move |x, y| luma.get_pixel_checked(x, y).is_none_or(|p| p.0[0] >= 128)) + } else { + return None; + }; + let (gw, gh) = (w.min(MAX_GRID), h.min(MAX_GRID)); + let mut cells = vec![false; usize::try_from(u64::from(gw) * u64::from(gh)).ok()?]; + for y in 0..h { + let row = u64::from(y) * u64::from(gh) / u64::from(h); + for x in 0..w { + if shows(x, y) { + let col = u64::from(x) * u64::from(gw) / u64::from(w); + if let Some(cell) = usize::try_from(row * u64::from(gw) + col).ok().and_then(|i| cells.get_mut(i)) { + *cell = true; + } + } + } + } + if cells.iter().all(|c| *c) { + return None; + } + Some(Opacity { width: gw, height: gh, cells }) +} + +/// `point` in the placement's unit square: the inverse of `matrix` applied to it. +fn unit_point(m: [f64; 6], point: [f64; 2]) -> Option<(f64, f64)> { + let det = m[0] * m[3] - m[1] * m[2]; + if !det.is_finite() || det.abs() < 1e-12 { + return None; + } + let (dx, dy) = (point[0] - m[4], point[1] - m[5]); + let x = (m[3] * dx - m[2] * dy) / det; + let y = (m[0] * dy - m[1] * dx) / det; + (x.is_finite() && y.is_finite()).then_some((x, y)) +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 7cd2f96a96..2e81623cf9 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -32,6 +32,7 @@ pub mod export; pub mod field_table; mod fill_sign; mod history; +mod image_alpha; pub mod js; mod layers; pub mod links; diff --git a/crates/engine/src/open.rs b/crates/engine/src/open.rs index 58bc8327e2..ce2a98c201 100644 --- a/crates/engine/src/open.rs +++ b/crates/engine/src/open.rs @@ -352,6 +352,7 @@ impl Session { fonts_stale: false, xfa_warnings: Vec::new(), edit_notices: Vec::new(), + alpha: Default::default(), } } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 833fa16b9f..675bb09404 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -8020,7 +8020,9 @@ fn copy_image_finds_the_image_under_a_point_and_decodes_it_at_full_size() { let id = s.open("p.pdf", None, pic, None).unwrap(); let d = s.get(id).unwrap(); let r = d.page_images(0)[0].rect; - assert_eq!(d.page_image_at(0, [(r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0]), Some(0)); + // On its red top-left pixel; its other pixels but the blue one are transparent. + assert_eq!(d.page_image_at(0, [r[0] + (r[2] - r[0]) / 6.0, r[3] - (r[3] - r[1]) / 4.0]), Some(0)); + assert_eq!(d.page_image_at(0, [(r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0]), None); assert_eq!(d.page_image_at(0, [r[2] + 10.0, r[3] + 10.0]), None); assert_eq!(d.page_image_at(7, [0.0, 0.0]), None); let (w, h, rgba) = d.page_image_rgba(0, 0).unwrap(); @@ -9335,3 +9337,141 @@ fn repeated_backdrop_artwork_survives_background_undo_redo_and_both_save_modes() s.apply(rewritten, Edit::RemoveMarks { kind: MarkKind::Background }).unwrap(); black(&s, rewritten); } + +/// A one-page 300 × 300 PDF of `objects` (numbered from 5) drawn by `content`; the page's +/// XObjects are `xobjects`. +fn images_pdf(xobjects: &str, content: &[u8], objects: &[(String, Vec)]) -> Vec { + let stream = |dict: &str, data: &[u8]| { + let mut o = format!("<< {dict} /Length {} >>\nstream\n", data.len()).into_bytes(); + o.extend_from_slice(data); + o.extend_from_slice(b"\nendstream"); + o + }; + let mut objs: Vec> = vec![ + b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 300] >>".to_vec(), + format!("<< /Type /Page /Parent 2 0 R /Contents 4 0 R /Resources << /XObject << {xobjects} >> >> >>").into_bytes(), + stream("", content), + ]; + objs.extend(objects.iter().map(|(dict, data)| stream(dict, data))); + let mut out = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes()); + out.extend_from_slice(o); + out.extend_from_slice(b"\nendobj\n"); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offsets { + out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + out +} + +/// Pictures are picked where they show. Overlapping pictures with transparent margins (a PNG +/// signature over a table, cut-out photos side by side) give a click through the margin to the +/// picture below; stencil images and colour-keyed pictures likewise. Pictures that can't be +/// read, or show everywhere, keep their whole box. +#[test] +fn pictures_are_picked_where_they_show() { + let rgb = |n: usize| ("/Type /XObject /Subtype /Image /Width 4 /Height 4 /ColorSpace /DeviceRGB /BitsPerComponent 8".to_string(), vec![0x80; n]); + let with = |(d, data): (String, Vec), extra: &str| (format!("{d} {extra}"), data); + let gray = |rows: [[u8; 4]; 4]| { + ("/Type /XObject /Subtype /Image /Width 4 /Height 4 /ColorSpace /DeviceGray /BitsPerComponent 8".to_string(), rows.concat()) + }; + let (a, o) = (255, 0); + let objects = vec![ + rgb(48), // 5: Low, opaque + with(rgb(48), "/SMask 7 0 R"), // 6: Top + gray([[o, o, a, a], [o, o, a, a], [o, o, o, o], [o, o, o, o]]), // 7: its top-right quarter shows + ("/Type /XObject /Subtype /Image /Width 2 /Height 1 /ImageMask true".into(), vec![0x40]), // 8 + ("/Type /XObject /Subtype /Image /Width 2 /Height 1 /ImageMask true /Decode [1 0]".into(), vec![0x40]), // 9 + ( + "/Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace /DeviceRGB /BitsPerComponent 8 /Mask [250 255 0 5 0 5]".into(), + vec![255, 0, 0, 0, 0, 255], + ), // 10: red keyed out + ( + "/Type /XObject /Subtype /Image /Width 4 /Height 4 /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /JPXDecode /SMask 7 0 R".into(), + b"not a JPEG 2000 codestream".to_vec(), + ), // 11: can't be read + with(rgb(48), "/SMask 13 0 R"), // 12 + gray([[a; 4]; 4]), // 13: shows everywhere + ]; + let content = b"q 100 0 0 100 20 20 cm /Low Do Q q 100 0 0 100 60 60 cm /Top Do Q \ + q 40 0 0 40 200 20 cm /St Do Q q 40 0 0 40 250 20 cm /StI Do Q q 40 0 0 40 200 100 cm /Key Do Q \ + q 40 0 0 40 200 200 cm /Jpx Do Q q 40 0 0 40 250 200 cm /Full Do Q q -40 0 0 40 140 200 cm /Top Do Q q 0 40 -40 0 300 250 cm /Top Do Q"; + let xobjects = "/Low 5 0 R /Top 6 0 R /St 8 0 R /StI 9 0 R /Key 10 0 R /Jpx 11 0 R /Full 12 0 R"; + let mut s = Session::new(); + let id = s.open("alpha.pdf", None, Arc::new(images_pdf(xobjects, content, &objects)), None).unwrap(); + let d = s.get(id).unwrap(); + assert_eq!(d.page_images(0).len(), 9, "{:?}", d.page_images(0)); + let cases: [([f64; 2], Option); 14] = [ + // Top's transparent lower-left, over Low: Low is picked. + ([70.0, 70.0], Some(0)), + ([100.0, 100.0], Some(0)), + // Top's showing quarter, over Low and beyond it. + ([115.0, 145.0], Some(1)), + ([150.0, 150.0], Some(1)), + // Top's transparent lower-right, over nothing. + ([150.0, 70.0], None), + // A stencil paints its 0 samples; with /Decode [1 0], its 1 samples. + ([210.0, 40.0], Some(2)), + ([230.0, 40.0], None), + ([260.0, 40.0], None), + ([280.0, 40.0], Some(3)), + // The colour-keyed red half doesn't show. + ([210.0, 120.0], None), + ([230.0, 120.0], Some(4)), + // Unreadable, and showing everywhere: the whole box. + ([205.0, 205.0], Some(5)), + ([255.0, 205.0], Some(6)), + // Top mirrored: its showing quarter is on the left. + ([105.0, 235.0], Some(7)), + ]; + for (at, want) in cases { + assert_eq!(d.page_image_at(0, at), want, "at {at:?}"); + } + assert_eq!(d.page_image_at(0, [135.0, 235.0]), None, "the mirrored placement's transparent right"); + // Top turned a quarter: its showing quarter is at the top left. + assert_eq!(d.page_image_at(0, [265.0, 285.0]), Some(8)); + assert_eq!(d.page_image_at(0, [295.0, 285.0]), None); + assert_eq!(d.page_image_at(0, [265.0, 255.0]), None); + let images = d.page_images(0); + assert!(!d.image_shows_at(&images[1], [70.0, 70.0])); + assert!(d.image_shows_at(&images[1], [150.0, 150.0])); + + // An edit changing only Top's soft mask is seen at once: it now shows everywhere. + let doc = s.doc_mut(id).unwrap(); + let editor = doc.editor.as_mut().unwrap(); + let full = editor.cos.get(pdfcraft_cos::ObjRef::new(13, 0)); + editor.cos.set(pdfcraft_cos::ObjRef::new(7, 0), (*full).clone()); + doc.generation += 1; + let d = s.get(id).unwrap(); + assert_eq!(d.page_image_at(0, [70.0, 70.0]), Some(1)); + assert_eq!(d.page_image_at(0, [150.0, 70.0]), Some(1)); +} + +/// A picture larger than the opacity grid is picked where it shows, its pixels scaled onto the +/// grid: a 300 × 300 picture showing only its top-left 150 × 150. +#[test] +fn large_pictures_are_picked_where_they_show() { + let mask: Vec = (0..300).flat_map(|y| (0..300).map(move |x| if x < 150 && y < 150 { 255 } else { 0 })).collect(); + let objects = vec![ + ( + "/Type /XObject /Subtype /Image /Width 300 /Height 300 /ColorSpace /DeviceGray /BitsPerComponent 8 /SMask 6 0 R".to_string(), + vec![0x80; 90_000], + ), + ("/Type /XObject /Subtype /Image /Width 300 /Height 300 /ColorSpace /DeviceGray /BitsPerComponent 8".to_string(), mask), + ]; + let mut s = Session::new(); + let id = s.open("large.pdf", None, Arc::new(images_pdf("/Big 5 0 R", b"q 100 0 0 100 0 0 cm /Big Do Q", &objects)), None).unwrap(); + let d = s.get(id).unwrap(); + // Just inside and just outside the showing quarter, along each axis. + assert_eq!(d.page_image_at(0, [45.0, 55.5]), Some(0)); + assert_eq!(d.page_image_at(0, [45.0, 44.0]), None); + assert_eq!(d.page_image_at(0, [49.0, 80.0]), Some(0)); + assert_eq!(d.page_image_at(0, [56.0, 80.0]), None); +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 8b280ba75d..37605bc19a 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1158,6 +1158,7 @@ fn page_tool_input(ui: &mut egui::Ui, view: &mut DocView, frame: &mut PageFrame< added, lines: &lines, images: &images, + doc, clip: ui.clip_rect(), }; if let Some(o) = ptr.pressed().filter(|o| xf.rect.contains(*o)) { @@ -1324,6 +1325,7 @@ fn page_tool_input(ui: &mut egui::Ui, view: &mut DocView, frame: &mut PageFrame< ptr, page: i, info, + doc, allow_interaction: !others_own_pointer && (matches!(view.router.owner(i), Some(crate::page_router::Owner::Picture { .. })) || !text_used), }; let image_used = crate::edit_text_ui::image_input(&image_cx, &images, view, &mut frame.out.image_action); @@ -1396,6 +1398,8 @@ struct PageHits<'a> { added: &'a [pdfcraft_engine::Added], lines: &'a [pdfcraft_engine::TextBlock], images: &'a [pdfcraft_engine::PageImage], + /// Says where a picture with transparency shows, so it is picked only there. + doc: &'a pdfcraft_engine::Document, /// The pages' visible area (the picture's rotate knob stays inside it). clip: Rect, } @@ -1423,6 +1427,7 @@ impl PageHits<'_> { added, lines, images, + doc, clip, } = *self; let fields = if preparing { @@ -1447,7 +1452,7 @@ impl PageHits<'_> { let edit_text = tool == QuickTool::EditText; let on_paragraphs = edit_text || crate::edit_text_ui::over_paragraph(xf, info, page, lines, p); ( - edit_text.then(|| crate::edit_text_ui::picture_hit(xf, page, info, images, view, p)).flatten(), + edit_text.then(|| crate::edit_text_ui::picture_hit(xf, page, info, doc, images, view, p)).flatten(), on_paragraphs.then(|| crate::edit_text_ui::hit(xf, info, page, lines, open.map(|e| e.block), p)).flatten(), edit_text.then(|| crate::object_ui::hit(view, xf, info, page, frame, p)).flatten(), edit_text.then(|| crate::edit_text_ui::picture_handle_hit(clip, xf, page, info, images, view, p)).flatten(), diff --git a/crates/ui-egui/src/tools/edit_text_ui/image.rs b/crates/ui-egui/src/tools/edit_text_ui/image.rs index 6956e656af..04031d719b 100644 --- a/crates/ui-egui/src/tools/edit_text_ui/image.rs +++ b/crates/ui-egui/src/tools/edit_text_ui/image.rs @@ -57,6 +57,8 @@ pub(crate) struct ImageCx<'a> { pub ptr: &'a PagePointer, pub page: usize, pub info: &'a DocInfo, + /// Says where a picture with transparency shows, so it is picked only there. + pub doc: &'a pdfcraft_engine::Document, pub allow_interaction: bool, } @@ -69,7 +71,7 @@ fn crop_handles(k: Rect) -> [Pos2; 8] { /// Crop mode for the selected image `i` whose visible frame is `b` (screen). Returns `true` /// (the pointer and keys are the crop's while it lasts). fn crop_input(cx: &ImageCx<'_>, view: &mut DocView, i: usize, b: Rect) -> bool { - let ImageCx { ui, resp, xf, ptr, page, info, allow_interaction } = *cx; + let ImageCx { ui, resp, xf, ptr, page, info, allow_interaction, .. } = *cx; let painter = ui.painter(); let Some(mode) = view.image_selection.as_mut().and_then(|s| s.crop.as_mut()) else { return false }; let hover_pos = ptr.pos; @@ -254,10 +256,11 @@ pub(crate) fn handle_hit( Some(Hit::new(picture(PicturePart::Corner(corner)), Layer::Handle, icon)) } -/// The picture under `p` (its shape, not only its box): a click selects it, a drag moves the +/// The picture under `p` (its shape and where it shows, not only its box): a click selects it, a +/// drag moves the /// selected one. On the text layer, asked before the paragraphs: editable text on top of a /// picture takes the press. -pub(crate) fn body_hit(xf: &PageXform, page: usize, info: &DocInfo, images: &[pdfcraft_engine::PageImage], view: &DocView, p: Pos2) -> Option { +pub(crate) fn body_hit(xf: &PageXform, page: usize, info: &DocInfo, doc: &pdfcraft_engine::Document, images: &[pdfcraft_engine::PageImage], view: &DocView, p: Pos2) -> Option { if !xf.rect.contains(p) { return None; } @@ -265,7 +268,7 @@ pub(crate) fn body_hit(xf: &PageXform, page: usize, info: &DocInfo, images: &[pd let user = info.pages.get(page)?.view_to_user(x, y).map(f64::from); let index = images .iter() - .rposition(|im| im.visible_rect.is_some_and(|r| xf.user_rect(info, page, r.map(|v| v as f32)).contains(p)) && im.contains(user))?; + .rposition(|im| im.visible_rect.is_some_and(|r| xf.user_rect(info, page, r.map(|v| v as f32)).contains(p)) && im.contains(user) && doc.image_shows_at(im, user))?; let selected = view.image_selection.as_ref().is_some_and(|s| s.page == page && s.index == index); let icon = if selected { egui::CursorIcon::Move } else { egui::CursorIcon::PointingHand }; Some(Hit::new(Owner::Picture { index, part: PicturePart::Body }, Layer::Text, icon)) @@ -483,15 +486,16 @@ fn drag_preview( /// Images on a page: select, move, resize, right-click. Returns `true` when the pointer was used. pub(crate) fn image_input(cx: &ImageCx<'_>, images: &[pdfcraft_engine::PageImage], view: &mut DocView, action: &mut Option) -> bool { - let ImageCx { ui, resp, xf, ptr, page, info, allow_interaction } = *cx; + let ImageCx { ui, resp, xf, ptr, page, info, doc, allow_interaction } = *cx; let boxes: Vec = images.iter().map(|im| im.visible_rect.map_or(Rect::NOTHING, |r| xf.user_rect(info, page, r.map(|v| v as f32)))).collect(); let painter = ui.painter(); let hover_pos = ptr.pos; let image_contains = |index: usize, point: Pos2| { let (x, y) = xf.screen_to_view(point); let Some(p) = info.pages.get(page) else { return false }; - let user = p.view_to_user(x, y); - images.get(index).is_some_and(|im| im.contains(user.map(f64::from))) + let user = p.view_to_user(x, y).map(f64::from); + // A picture is picked where it shows: through its transparent parts, the one below is. + images.get(index).is_some_and(|im| im.contains(user) && doc.image_shows_at(im, user)) }; let selected = view.image_selection.as_ref().filter(|s| s.page == page).map(|s| s.index).filter(|i| *i < boxes.len()); let dragging = view.image_selection.as_ref().is_some_and(|s| s.drag.is_some()); diff --git a/crates/ui-egui/tests/it/editing.rs b/crates/ui-egui/tests/it/editing.rs index bdb0720dde..e87d0b51ce 100644 --- a/crates/ui-egui/tests/it/editing.rs +++ b/crates/ui-egui/tests/it/editing.rs @@ -7554,3 +7554,68 @@ fn escape_in_an_open_paragraph_selects_its_box_for_delete() { assert_eq!(blocks(&h)[0].text, "Page 1"); } } + +/// Edit text & images: a click through the transparent margin of a picture selects the picture +/// below it, and a click where it shows selects it. +#[test] +fn a_click_through_a_pictures_transparent_margin_selects_the_picture_below() { + let stream = |dict: &str, data: &[u8]| { + let mut o = format!("<< {dict} /Length {} >>\nstream\n", data.len()).into_bytes(); + o.extend_from_slice(data); + o.extend_from_slice(b"\nendstream"); + o + }; + let image = "/Type /XObject /Subtype /Image /Width 4 /Height 4 /BitsPerComponent 8"; + // The top picture's soft mask shows its top-right quarter only. + let mask: Vec = [[0, 0, 255, 255], [0, 0, 255, 255], [0; 4], [0; 4]].concat(); + let objs: Vec> = vec![ + b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 300] >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /Contents 4 0 R /Resources << /XObject << /Low 5 0 R /Top 6 0 R >> >> >>".to_vec(), + stream("", b"q 100 0 0 100 20 20 cm /Low Do Q q 100 0 0 100 60 60 cm /Top Do Q"), + stream(&format!("{image} /ColorSpace /DeviceRGB"), &[0x80; 48]), + stream(&format!("{image} /ColorSpace /DeviceRGB /SMask 7 0 R"), &[0x40; 48]), + stream(&format!("{image} /ColorSpace /DeviceGray"), &mask), + ]; + let mut bytes = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(bytes.len()); + bytes.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes()); + bytes.extend_from_slice(o); + bytes.extend_from_slice(b"\nendobj\n"); + } + let xref = bytes.len(); + bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offsets { + bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + let mut h = Harness::builder().with_size(egui::vec2(900.0, 800.0)).build_eframe(move |_cc| { + let mut app = PdfCraftApp::new(); + app.set_option("language", "en").unwrap(); + app.open_bytes("overlap.pdf", None, bytes).unwrap(); + app + }); + h.run_steps(4); + assert!(h.state_mut().execute("edit.edit_text")); + h.state_mut().views[0].fit = pdfcraft_ui_egui::canvas::Fit::Page; + h.run_steps(4); + let id = h.state().views[0].id; + let info = h.state().session.get(id).unwrap().info.pages[0].clone(); + let page = h.state().views[0].page_screen_rect(0).unwrap(); + let at = |x: f32, y: f32| { + let v = info.user_to_view(x, y); + page.min + egui::vec2(v[0], v[1]) * (page.width() / info.width) + }; + for ((x, y), want) in [((70.0, 70.0), 0), ((150.0, 150.0), 1), ((100.0, 100.0), 0), ((115.0, 145.0), 1)] { + let p = at(x, y); + h.hover_at(p); + h.run_steps(1); + h.drag_at(p); + h.run_steps(1); + h.drop_at(p); + h.run_steps(3); + assert_eq!(h.state().views[0].image_selection.as_ref().map(|s| s.index), Some(want), "click at {x}, {y}"); + } +} diff --git a/docs/editing-images.md b/docs/editing-images.md index 4ebafd115f..c2ba11d76f 100644 --- a/docs/editing-images.md +++ b/docs/editing-images.md @@ -42,7 +42,14 @@ with the selected image, also when the picture sits inside a clip it shares with (a report drawing each picture as `q re W n cm Do Q` within a table's clip): the picture's own clip scales with it, and shared clips stay fixed without moving neighbouring text or artwork. -`image_hit` applies the same path and hole checks headlessly. `page_images` retains `rect` as +A picture with transparency (a soft mask, a stencil or colour-key `/Mask`, or a stencil +image) is picked only where it shows: a click through the transparent margin of a PNG +signature or a cut-out photo goes to what is below it. Opacity is read on a grid of at most +256 cells a side, a cell counting as showing if any of its pixels does (alpha ≥ 16 of 255). +Form artwork, pictures without transparency, and pictures that can't be decoded (JPEG 2000, +JBIG2, CCITT) keep their whole box. + +`image_hit` applies the same path, hole and transparency checks headlessly. `page_images` retains `rect` as the full placement rectangle used by `image_edit` and adds `visible_rect` for selection (null when fully clipped). `object_list` reports visible artwork bounds while keeping the original source indexes. A selection frame does not create, remove or enlarge the PDF's clipping path. diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 1404247cd7..262d315b90 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -2153,8 +2153,8 @@ milestone = "M7" status = "shipped" commands = ["edit.edit_text"] tools = ["image_edit", "image_hit"] -evidence = ["crates/edit/src/tests.rs::private_image_crop_with_intervening_state_resizes_across_streams", "crates/automation/tests/it/automation.rs::private_crops_with_nested_state_resize_save_reopen_through_tools", "crates/edit/src/tests.rs::form_artwork_edits_only_the_selected_placement", "crates/ui-egui/tests/it/editing.rs::editing_existing_form_artwork_on_the_page", "crates/automation/tests/it/automation.rs::editing_form_artwork_through_tools", "crates/edit/src/tests.rs::page_images_move_turn_replace_and_delete", "crates/ui-egui/tests/it/editing.rs::editing_existing_images_on_the_page", "crates/automation/tests/it/automation.rs::editing_page_images_through_tools", "crates/edit/src/tests.rs::curved_image_clips_have_analytic_bounds_and_holes_do_not_capture_points", "crates/edit/src/tests.rs::cropped_image_resizing_moves_private_clips_and_keeps_shared_ones", "crates/ui-egui/tests/it/editing.rs::cropped_image_corner_resize_keeps_opposite_corner_and_scales_crop", "crates/edit/src/tests.rs::image_selection_bounds_respect_clips_and_restore_graphics_state", "crates/ui-egui/tests/it/editing.rs::cropped_images_do_not_intercept_text_and_stay_inside_each_page", "crates/automation/tests/it/automation.rs::clipped_image_bounds_and_text_edit_save_reopen_through_tools", "crates/edit/src/tests.rs::resizing_an_image_under_a_shared_clip_moves_its_own_clip"] -notes = "existing raster images and grouped Form artwork: select, drag to move, drag a corner to resize keeping proportions; Delete removes one placement. Forms include their nested content as a group; individual internal elements and inline images are not supported. See docs/editing-images.md; added images too Since #1116: raster images and grouped Forms move/resize/turn as placements; selected grips own the gesture and opposite anchor, with no PDF writes during movement. Curved path frames use analytic Bezier extrema and hit testing evaluates actual nonzero/even-odd fill rules, excluding holes; intersections can retain a loose frame. Selection and resize use the visible (clipped) frame; exclusive image clips move with their pixels across nested states, intervening operators and content streams, also inside a clip the picture shares with other content (its own clip scales, the shared one stays); shared clips stay fixed. Inline images and Form internals remain unsupported; see docs/editing-images.md" +evidence = ["crates/edit/src/tests.rs::private_image_crop_with_intervening_state_resizes_across_streams", "crates/automation/tests/it/automation.rs::private_crops_with_nested_state_resize_save_reopen_through_tools", "crates/edit/src/tests.rs::form_artwork_edits_only_the_selected_placement", "crates/ui-egui/tests/it/editing.rs::editing_existing_form_artwork_on_the_page", "crates/automation/tests/it/automation.rs::editing_form_artwork_through_tools", "crates/edit/src/tests.rs::page_images_move_turn_replace_and_delete", "crates/ui-egui/tests/it/editing.rs::editing_existing_images_on_the_page", "crates/automation/tests/it/automation.rs::editing_page_images_through_tools", "crates/edit/src/tests.rs::curved_image_clips_have_analytic_bounds_and_holes_do_not_capture_points", "crates/edit/src/tests.rs::cropped_image_resizing_moves_private_clips_and_keeps_shared_ones", "crates/ui-egui/tests/it/editing.rs::cropped_image_corner_resize_keeps_opposite_corner_and_scales_crop", "crates/edit/src/tests.rs::image_selection_bounds_respect_clips_and_restore_graphics_state", "crates/ui-egui/tests/it/editing.rs::cropped_images_do_not_intercept_text_and_stay_inside_each_page", "crates/automation/tests/it/automation.rs::clipped_image_bounds_and_text_edit_save_reopen_through_tools", "crates/edit/src/tests.rs::resizing_an_image_under_a_shared_clip_moves_its_own_clip", "crates/engine/src/tests.rs::pictures_are_picked_where_they_show", "crates/engine/src/tests.rs::large_pictures_are_picked_where_they_show", "crates/automation/tests/it/automation.rs::image_hit_sees_through_transparent_parts_of_pictures", "crates/ui-egui/tests/it/editing.rs::a_click_through_a_pictures_transparent_margin_selects_the_picture_below"] +notes = "existing raster images and grouped Form artwork: select, drag to move, drag a corner to resize keeping proportions; Delete removes one placement. Forms include their nested content as a group; individual internal elements and inline images are not supported. See docs/editing-images.md; added images too Since #1116: raster images and grouped Forms move/resize/turn as placements; selected grips own the gesture and opposite anchor, with no PDF writes during movement. Curved path frames use analytic Bezier extrema and hit testing evaluates actual nonzero/even-odd fill rules, excluding holes; intersections can retain a loose frame. Selection and resize use the visible (clipped) frame; exclusive image clips move with their pixels across nested states, intervening operators and content streams, also inside a clip the picture shares with other content (its own clip scales, the shared one stays); shared clips stay fixed. Pictures with transparency (soft mask, /Mask, stencil) are picked only where they show, on an opacity grid of at most 256 cells a side; JPEG 2000/JBIG2/CCITT pictures and Form artwork keep their whole box. Inline images and Form internals remain unsupported; see docs/editing-images.md" [[feature]] id = "edit.image-extract" From 1bdee95bac21891c9692f4efe226ec36591a8883 Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Mon, 19 Oct 2026 01:39:44 +0800 Subject: [PATCH 02/30] M2: a picture that shows nowhere keeps its whole box for picking Review follow-up on #3069: an all-transparent grid made a faint watermark or a transparent placeholder impossible to pick. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/image_alpha.rs | 9 ++++++--- crates/engine/src/tests.rs | 16 ++++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/image_alpha.rs b/crates/engine/src/image_alpha.rs index 9e6b50d181..9294c30f0c 100644 --- a/crates/engine/src/image_alpha.rs +++ b/crates/engine/src/image_alpha.rs @@ -6,7 +6,8 @@ //! `/ImageMask`) gets an opacity grid of at most [`MAX_GRID`] cells a side, built once from its //! pixels and kept until the document changes. A cell counts as opaque if any pixel //! in it is: thin strokes and the edges of a shape stay easy to pick. Pictures without -//! transparency, Form artwork, and pictures that can't be decoded keep their whole box. +//! transparency, Form artwork, pictures that show nowhere and pictures that can't be decoded +//! keep their whole box. use std::collections::HashMap; use std::sync::{Arc, Mutex}; @@ -33,7 +34,7 @@ pub(crate) struct Opacity { } /// Opacity grids by picture object, for the document generation they were built at; `None` for -/// a picture that is opaque everywhere or couldn't be read (its whole box counts). The +/// a picture that is opaque everywhere, shows nowhere or couldn't be read (its whole box counts). The /// generation, not the picture object alone, says when to rebuild: an edit may change the /// picture's soft mask without touching the picture. type Grids = (u64, HashMap>>); @@ -133,7 +134,9 @@ fn build(cos: &pdfcraft_cos::Document, object: ObjRef) -> Option { } } } - if cells.iter().all(|c| *c) { + // A picture that shows everywhere, or nowhere (a faint watermark, a transparent + // placeholder), keeps its whole box: one that showed nowhere couldn't be picked at all. + if cells.iter().all(|c| *c) || !cells.iter().any(|c| *c) { return None; } Some(Opacity { width: gw, height: gh, cells }) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 675bb09404..7661e4cfab 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -9371,6 +9371,22 @@ fn images_pdf(xobjects: &str, content: &[u8], objects: &[(String, Vec)]) -> out } +/// #3069 review: a picture that shows nowhere (a soft mask below the opacity threshold +/// everywhere: a faint watermark, a transparent placeholder) keeps its whole box, so it can still +/// be picked to move or delete. +#[test] +fn a_picture_that_shows_nowhere_is_picked_by_its_whole_box() { + let objects = vec![ + ("/Type /XObject /Subtype /Image /Width 4 /Height 4 /ColorSpace /DeviceRGB /BitsPerComponent 8 /SMask 6 0 R".to_string(), vec![0x80; 48]), + ("/Type /XObject /Subtype /Image /Width 4 /Height 4 /ColorSpace /DeviceGray /BitsPerComponent 8".to_string(), vec![8; 16]), + ]; + let mut s = Session::new(); + let id = s.open("faint.pdf", None, Arc::new(images_pdf("/Faint 5 0 R", b"q 100 0 0 100 20 20 cm /Faint Do Q", &objects)), None).unwrap(); + let d = s.get(id).unwrap(); + assert_eq!(d.page_image_at(0, [70.0, 70.0]), Some(0)); + assert!(d.image_shows_at(&d.page_images(0)[0], [30.0, 110.0])); +} + /// Pictures are picked where they show. Overlapping pictures with transparent margins (a PNG /// signature over a table, cut-out photos side by side) give a click through the margin to the /// picture below; stencil images and colour-keyed pictures likewise. Pictures that can't be From 89e371125371bd1a4fcc8c7975fc271d9e85a22b Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Sat, 31 Oct 2026 08:08:09 +0800 Subject: [PATCH 03/30] M7: format the picture hit test after the rebase onto main Rebasing moved the picking change onto main's page pointer router, where the picture hit test is `body_hit`. This wraps its comment and formats it; no behaviour changes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Pq7HyCfwzyRXj4VfQAVVdv --- .../ui-egui/src/tools/edit_text_ui/image.rs | 23 +++++++++++++------ 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/tools/edit_text_ui/image.rs b/crates/ui-egui/src/tools/edit_text_ui/image.rs index 04031d719b..bde79f94de 100644 --- a/crates/ui-egui/src/tools/edit_text_ui/image.rs +++ b/crates/ui-egui/src/tools/edit_text_ui/image.rs @@ -257,18 +257,27 @@ pub(crate) fn handle_hit( } /// The picture under `p` (its shape and where it shows, not only its box): a click selects it, a -/// drag moves the -/// selected one. On the text layer, asked before the paragraphs: editable text on top of a -/// picture takes the press. -pub(crate) fn body_hit(xf: &PageXform, page: usize, info: &DocInfo, doc: &pdfcraft_engine::Document, images: &[pdfcraft_engine::PageImage], view: &DocView, p: Pos2) -> Option { +/// drag moves the selected one. On the text layer, asked before the paragraphs: editable text on +/// top of a picture takes the press. +pub(crate) fn body_hit( + xf: &PageXform, + page: usize, + info: &DocInfo, + doc: &pdfcraft_engine::Document, + images: &[pdfcraft_engine::PageImage], + view: &DocView, + p: Pos2, +) -> Option { if !xf.rect.contains(p) { return None; } let (x, y) = xf.screen_to_view(p); let user = info.pages.get(page)?.view_to_user(x, y).map(f64::from); - let index = images - .iter() - .rposition(|im| im.visible_rect.is_some_and(|r| xf.user_rect(info, page, r.map(|v| v as f32)).contains(p)) && im.contains(user) && doc.image_shows_at(im, user))?; + let index = images.iter().rposition(|im| { + im.visible_rect.is_some_and(|r| xf.user_rect(info, page, r.map(|v| v as f32)).contains(p)) + && im.contains(user) + && doc.image_shows_at(im, user) + })?; let selected = view.image_selection.as_ref().is_some_and(|s| s.page == page && s.index == index); let icon = if selected { egui::CursorIcon::Move } else { egui::CursorIcon::PointingHand }; Some(Hit::new(Owner::Picture { index, part: PicturePart::Body }, Layer::Text, icon)) From b424c52fb639104388d6b3394d13d2289055ec45 Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Sat, 31 Oct 2026 08:08:10 +0800 Subject: [PATCH 04/30] M2: bound what the opacity grid decodes, and mark every cell a pixel reaches Review on #3069: - Only the picture's own Width x Height was checked before it was exported for its opacity grid. A soft mask or stencil /Mask is decoded in full before it is scaled to the picture's size, so a small picture with a mask of up to 100 million pixels allocated hundreds of megabytes on the first hover. Each mask stream is now held to the same pixel limit as the picture. - A lossless picture or mask whose stream inflates far past its declared samples was decoded in full (up to 1 GiB) before the declared samples were taken from it. Each is now decoded first within its declared sample bytes, plus a quarter and 64 KiB for padding, through decoded_image_within; past that the picture keeps its whole box. - A showing pixel was stored only in the grid cell its start falls in. When the picture is wider or taller than the grid, a pixel can cross into the next cell, and a point on that part was taken as see-through. Every cell a showing pixel reaches into now shows. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Pq7HyCfwzyRXj4VfQAVVdv --- crates/engine/src/image_alpha.rs | 109 ++++++++++++++++++++++++++++--- crates/engine/src/tests.rs | 74 +++++++++++++++++++++ 2 files changed, 175 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/image_alpha.rs b/crates/engine/src/image_alpha.rs index 9294c30f0c..3accb79df9 100644 --- a/crates/engine/src/image_alpha.rs +++ b/crates/engine/src/image_alpha.rs @@ -24,6 +24,12 @@ const MAX_CACHED: usize = 256; const MAX_DECODE_PIXELS: u64 = 64_000_000; /// Alpha at or above this (of 255) counts as showing. const OPAQUE: u8 = 16; +/// Colour components assumed for a colour space that can't be read: as many as a DeviceN space +/// may have in practice, so the decoding bound stays generous. +const MAX_COMPONENTS: u64 = 32; +/// Decoded bytes allowed past what a picture's declared size needs (with a quarter more), for +/// padding writers leave after the samples. +const DECODE_SLACK: u64 = 64 << 10; /// Which cells of a picture show, row 0 at the top of the picture. #[derive(Debug)] @@ -89,17 +95,26 @@ impl Document { fn build(cos: &pdfcraft_cos::Document, object: ObjRef) -> Option { let current = cos.get(object); let Object::Stream(s) = &*current else { return None }; - let flag = |key: &[u8]| s.dict.get(key).is_some_and(|v| matches!(&*cos.resolve(v), Object::Bool(true))); - let stencil = flag(b"ImageMask"); + let stencil = flag(cos, s, b"ImageMask"); let soft = s.dict.get(b"SMask").is_some_and(|v| cos.resolve(v).as_name() != Some(b"None")); let in_data = s.dict.int(b"SMaskInData").is_some_and(|v| v != 0); if !(stencil || soft || in_data || s.dict.get(b"Mask").is_some()) { return None; } - let size = |key: &[u8]| u64::try_from(s.dict.int(key).unwrap_or(0)).unwrap_or(0); - if size(b"Width").saturating_mul(size(b"Height")) > MAX_DECODE_PIXELS { + // The picture and the mask images it brings are decoded in full before anything is scaled + // down to the picture's size, so each must be small enough, in pixels and in decoded bytes, + // before any of it is decoded. + let components = if stencil { 1 } else { components(cos, s.dict.get(b"ColorSpace")) }; + if !within_budget(cos, s, components, stencil) { return None; } + for key in [&b"SMask"[..], b"Mask"] { + if let Some(Object::Stream(mask)) = s.dict.get(key).map(|v| cos.resolve(v)).as_deref() + && !within_budget(cos, mask, 1, key == b"Mask" || flag(cos, mask, b"ImageMask")) + { + return None; + } + } let (_, bytes) = pdfcraft_create::image_file(cos, object).ok()?; let format = image::guess_format(&bytes).ok()?; let mut reader = image::ImageReader::with_format(std::io::Cursor::new(bytes.as_slice()), format); @@ -124,12 +139,17 @@ fn build(cos: &pdfcraft_cos::Document, object: ObjRef) -> Option { let (gw, gh) = (w.min(MAX_GRID), h.min(MAX_GRID)); let mut cells = vec![false; usize::try_from(u64::from(gw) * u64::from(gh)).ok()?]; for y in 0..h { - let row = u64::from(y) * u64::from(gh) / u64::from(h); + let rows = cells_covered(y, h, gh); for x in 0..w { if shows(x, y) { - let col = u64::from(x) * u64::from(gw) / u64::from(w); - if let Some(cell) = usize::try_from(row * u64::from(gw) + col).ok().and_then(|i| cells.get_mut(i)) { - *cell = true; + // Every cell the pixel reaches into shows: a point anywhere on a showing pixel + // picks the picture, also where the pixel crosses into the next cell. + for row in rows.clone() { + for col in cells_covered(x, w, gw) { + if let Some(cell) = usize::try_from(row * u64::from(gw) + col).ok().and_then(|i| cells.get_mut(i)) { + *cell = true; + } + } } } } @@ -142,6 +162,79 @@ fn build(cos: &pdfcraft_cos::Document, object: ObjRef) -> Option { Some(Opacity { width: gw, height: gh, cells }) } +/// The grid cells, along an axis of `pixels` pixels and `cells` cells, that pixel `i` reaches +/// into: from the cell its start is in to the cell its end is in. `cells` is at most `pixels`, so +/// a pixel reaches into at most two. +fn cells_covered(i: u32, pixels: u32, cells: u32) -> std::ops::Range { + let (i, pixels, cells) = (u64::from(i), u64::from(pixels).max(1), u64::from(cells)); + let start = i * cells / pixels; + let end = ((i + 1) * cells).div_ceil(pixels).min(cells); + start..end.max(start) +} + +/// Whether the boolean `key` of image stream `s` is `true`. +fn flag(cos: &pdfcraft_cos::Document, s: &pdfcraft_cos::Stream, key: &[u8]) -> bool { + s.dict.get(key).is_some_and(|v| matches!(&*cos.resolve(v), Object::Bool(true))) +} + +/// Whether image stream `s`, of `components` colour components (one bit each for a `stencil`), +/// is small enough to decode for its opacity grid: at most [`MAX_DECODE_PIXELS`] pixels and, when +/// its samples are decoded through its filters, no more decoded bytes than its declared size +/// needs, with room for padding a writer left after the samples. Without that bound a 1 × 1 +/// picture whose stream inflates to a gigabyte would be decoded in full on the first hover. JPEG, +/// JPEG 2000 and JBIG2 data go to their own decoders instead. +fn within_budget(cos: &pdfcraft_cos::Document, s: &pdfcraft_cos::Stream, components: u64, stencil: bool) -> bool { + let size = |key: &[u8]| u64::try_from(s.dict.int(key).unwrap_or(0)).unwrap_or(0); + let (w, h) = (size(b"Width"), size(b"Height")); + if w.saturating_mul(h) > MAX_DECODE_PIXELS { + return false; + } + let codec = match s.dict.get(b"Filter").map(|f| cos.resolve(f)).as_deref() { + Some(Object::Name(n)) => Some(n.clone()), + Some(Object::Array(a)) => a.last().and_then(Object::as_name).map(<[u8]>::to_vec), + _ => None, + }; + if matches!(codec.as_deref(), Some(b"DCTDecode" | b"DCT" | b"JPXDecode" | b"JBIG2Decode")) { + return true; + } + let bpc = if stencil { 1 } else { u64::try_from(s.dict.int(b"BitsPerComponent").unwrap_or(8)).unwrap_or(8).clamp(1, 16) }; + let row = w.checked_mul(components).and_then(|n| n.checked_mul(bpc)).map(|bits| bits.div_ceil(8)); + let budget = row.and_then(|r| r.checked_mul(h)).and_then(|n| n.checked_add(n / 4)).and_then(|n| n.checked_add(DECODE_SLACK)); + let Some(budget) = budget.and_then(|n| usize::try_from(n).ok()) else { return false }; + cos.decoded_image_within(s, budget).is_ok() +} + +/// The colour components of an image in colour space `space` (ISO 32000-2 §8.6): one for an +/// indexed or separation space, the `/N` of an ICC-based one, as many as a DeviceN space names. +/// A space that can't be read counts as [`MAX_COMPONENTS`], which keeps the decoding bound +/// generous rather than refusing the picture. +fn components(cos: &pdfcraft_cos::Document, space: Option<&Object>) -> u64 { + let Some(space) = space.map(|s| cos.resolve(s)) else { return MAX_COMPONENTS }; + let array = space.as_array(); + let family = match (&*space, array.and_then(|a| a.first()).and_then(Object::as_name)) { + (Object::Name(n), _) => n.as_slice(), + (_, Some(n)) => n, + _ => return MAX_COMPONENTS, + }; + let operand = || array.and_then(|a| a.get(1)).map(|o| cos.resolve(o)); + match family { + b"DeviceGray" | b"G" | b"CalGray" | b"Indexed" | b"I" | b"Separation" => 1, + b"DeviceRGB" | b"RGB" | b"CalRGB" | b"Lab" => 3, + b"DeviceCMYK" | b"CMYK" => 4, + b"ICCBased" => match operand().as_deref() { + Some(Object::Stream(icc)) => { + icc.dict.int(b"N").and_then(|n| u64::try_from(n).ok()).filter(|n| (1..=MAX_COMPONENTS).contains(n)).unwrap_or(MAX_COMPONENTS) + } + _ => MAX_COMPONENTS, + }, + b"DeviceN" => match operand().as_deref() { + Some(Object::Array(names)) => u64::try_from(names.len()).unwrap_or(MAX_COMPONENTS).clamp(1, MAX_COMPONENTS), + _ => MAX_COMPONENTS, + }, + _ => MAX_COMPONENTS, + } +} + /// `point` in the placement's unit square: the inverse of `matrix` applied to it. fn unit_point(m: [f64; 6], point: [f64; 2]) -> Option<(f64, f64)> { let det = m[0] * m[3] - m[1] * m[2]; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 7661e4cfab..f3b49ed03d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -9491,3 +9491,77 @@ fn large_pictures_are_picked_where_they_show() { assert_eq!(d.page_image_at(0, [49.0, 80.0]), Some(0)); assert_eq!(d.page_image_at(0, [56.0, 80.0]), None); } + +/// `data` compressed with Flate, as a stream's bytes. +fn flated(data: &[u8]) -> Vec { + pdfcraft_cos::Stream::flate(pdfcraft_cos::Dict::default(), data).raw.to_vec() +} + +/// #3069 review: a showing pixel that crosses from one grid cell into the next marks both. In a +/// 257-pixel-wide picture on a 256-cell grid, pixel 1 starts in cell 0 and ends in cell 1; a point +/// on its right part, in cell 1, picks the picture. +#[test] +fn a_showing_pixel_marks_every_grid_cell_it_reaches_into() { + let mut mask = vec![0u8; 257]; + mask[1] = 255; + let objects = vec![ + ("/Type /XObject /Subtype /Image /Width 257 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /SMask 6 0 R".to_string(), vec![0x80; 257]), + ("/Type /XObject /Subtype /Image /Width 257 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8".to_string(), mask), + ]; + let mut s = Session::new(); + let id = s.open("wide.pdf", None, Arc::new(images_pdf("/Wide 5 0 R", b"q 257 0 0 10 0 0 cm /Wide Do Q", &objects)), None).unwrap(); + let d = s.get(id).unwrap(); + let image = &d.page_images(0)[0]; + for x in [1.2, 1.5, 1.8] { + assert!(d.image_shows_at(image, [x, 5.0]), "pixel 1 shows at x = {x}"); + } + assert!(!d.image_shows_at(image, [5.5, 5.0]), "pixel 5 is transparent"); +} + +/// #3069 review: a soft mask larger than the opacity grid's decoding limit keeps the picture's +/// whole box, however small the picture: the mask would be decoded in full before being scaled +/// to the picture's size. +#[test] +fn a_picture_whose_soft_mask_is_too_large_keeps_its_whole_box() { + // 8000 × 8001 pixels, just past 64 million; its left quarter shows, so once scaled to the + // picture's two pixels the left one shows and the right one doesn't. + let (w, h) = (8000usize, 8001usize); + let row: Vec = (0..w).map(|x| if x < w / 4 { 255 } else { 0 }).collect(); + let mask = flated(&row.repeat(h)); + let objects = vec![ + ("/Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /SMask 6 0 R".to_string(), vec![0x80; 2]), + (format!("/Type /XObject /Subtype /Image /Width {w} /Height {h} /ColorSpace /DeviceGray /BitsPerComponent 8 /Filter /FlateDecode"), mask), + ]; + let mut s = Session::new(); + let id = s.open("mask.pdf", None, Arc::new(images_pdf("/Small 5 0 R", b"q 100 0 0 100 0 0 cm /Small Do Q", &objects)), None).unwrap(); + let d = s.get(id).unwrap(); + assert!(d.image_shows_at(&d.page_images(0)[0], [75.0, 50.0]), "the whole box, without decoding the mask"); +} + +/// #3069 review: a picture or soft mask whose stream inflates far past what its declared size +/// needs keeps the picture's whole box, rather than being decoded in full on the first hover. +#[test] +fn picture_streams_that_inflate_past_their_size_keep_the_whole_box() { + let flate = "/Filter /FlateDecode"; + let image = |extra: &str, data: Vec| { + (format!("/Type /XObject /Subtype /Image /Width 2 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 {extra}"), data) + }; + let huge = || flated(&[255u8, 0].repeat(4 << 20)); + let objects = vec![ + image(&format!("{flate} /SMask 7 0 R"), huge()), // 5: its samples inflate to 8 MiB + image("/SMask 9 0 R", vec![0x80; 2]), // 6: its mask inflates to 8 MiB + image("", vec![255, 0]), // 7: the left half shows + image(&format!("{flate} /SMask 7 0 R"), flated(&[9, 9])), // 8: as declared + image(flate, huge()), // 9: 6's mask + ]; + let content = b"q 100 0 0 100 0 0 cm /A Do Q q 100 0 0 100 0 100 cm /B Do Q q 100 0 0 100 0 200 cm /C Do Q"; + let mut s = Session::new(); + let id = s.open("inflate.pdf", None, Arc::new(images_pdf("/A 5 0 R /B 6 0 R /C 8 0 R", content, &objects)), None).unwrap(); + let d = s.get(id).unwrap(); + let images = d.page_images(0); + assert_eq!(images.len(), 3); + assert!(d.image_shows_at(&images[0], [75.0, 50.0]), "the picture's samples are too large: its whole box"); + assert!(d.image_shows_at(&images[1], [75.0, 150.0]), "its soft mask's samples are too large: its whole box"); + assert!(!d.image_shows_at(&images[2], [75.0, 250.0]), "Flate data as large as declared is read"); + assert!(d.image_shows_at(&images[2], [25.0, 250.0])); +} From 8ca0b31dc4dda8e21ee07175693c980a992b4cf8 Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Sat, 24 Oct 2026 23:15:16 +0800 Subject: [PATCH 05/30] M6: a value the validate action rejects is dropped and the field keeps its value A text field whose validate action (ISO 32000-2 Table 199 /V) rejects the typed value, by range or by a script setting event.rc false, showed the message but reopened its editor with the rejected text and pulled focus back to it, so the user could not go on filling the form. Other readers (5 of 5) show the message, put the field back to its previous value and let focus move on. - forms: FormError::Rejected for a validate refusal (range or script); a keystroke/format refusal stays Invalid/Format. - engine: EditError::is_rejected_value(). - ui-egui: apply_edit wraps try_apply_edit; a rejected value's draft is dropped instead of reopened, so the editor Tab or a click opened on the next field stays open. Format refusals still reopen (#166). The message is the same notice; Save/Print/Export still stop after it. The engine already applied edits to a copy, so a rejection leaves the document and undo history untouched; the tests pin that too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0175FWj4xFhMhSH3UpMU8DSC --- crates/automation/tests/it/automation.rs | 3 + crates/engine/src/error.rs | 9 ++ crates/forms/src/lib.rs | 6 ++ crates/forms/src/scripting.rs | 7 +- crates/forms/src/tests.rs | 54 +++++++++++- crates/forms/src/values.rs | 2 +- crates/ui-egui/src/editing.rs | 98 ++++++++++++--------- crates/ui-egui/src/tools/forms_ui.rs | 5 +- crates/ui-egui/tests/it/forms.rs | 106 ++++++++++++++++++++--- parity/acrobat-features.toml | 8 +- 10 files changed, 232 insertions(+), 66 deletions(-) diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index 6a5765b911..ef0ecf44ba 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -7128,6 +7128,9 @@ fn javascript_through_tools() { assert!(page_text(&mut a, doc)[0].contains("EUR 2.500,00"), "{:?}", page_text(&mut a, doc)); let err = a.call("form_fill", &json!({ "doc": doc, "values": { "Qty": "0" } })).unwrap_err(); assert!(err.to_string().contains("Order at least one"), "{err}"); + let fields = ok(&mut a, "form_fields", json!({ "doc": doc })); + let qty = fields["fields"].as_array().unwrap().iter().find(|x| x["name"] == "Qty").unwrap(); + assert_eq!(qty["value"], "2", "the rejected value is reported, not stored"); let r = ok( &mut a, diff --git a/crates/engine/src/error.rs b/crates/engine/src/error.rs index 5ee915fcdf..75b239cbd2 100644 --- a/crates/engine/src/error.rs +++ b/crates/engine/src/error.rs @@ -78,3 +78,12 @@ impl From for EditError { EditError::Sign(e.to_string()) } } + +impl EditError { + /// A field's validate action refused the value it was given (ISO 32000-2 Table 199 `/V`). + /// The document is unchanged and the field keeps its value; an interface drops the typing + /// rather than holding the user in the field. + pub fn is_rejected_value(&self) -> bool { + matches!(self, EditError::Form(pdfcraft_forms::FormError::Rejected(_))) + } +} diff --git a/crates/forms/src/lib.rs b/crates/forms/src/lib.rs index 775306d865..3b3a98b71c 100644 --- a/crates/forms/src/lib.rs +++ b/crates/forms/src/lib.rs @@ -73,6 +73,12 @@ pub enum FormError { /// checked before any of the field's scripts run. #[error("{0}")] Format(String), + /// The field's validate action (ISO 32000-2 Table 199 `/V`: it "may check the new value + /// for validity") refused the value: a range it is outside, or a script that set `event.rc` + /// to false. The message is the script's alert, or the range's. Nothing was changed, and + /// the field keeps the value it had. + #[error("{0}")] + Rejected(String), #[error("{0}")] Cos(#[from] pdfcraft_cos::CosError), } diff --git a/crates/forms/src/scripting.rs b/crates/forms/src/scripting.rs index 7dd7bfde6c..cdfd5b3439 100644 --- a/crates/forms/src/scripting.rs +++ b/crates/forms/src/scripting.rs @@ -84,7 +84,12 @@ pub(crate) fn accept(doc: &mut Document, f: &Field, value: &str, scripts: &mut d let r = scripts.run(event, js, f, &v, &all); apply_changes(doc, &r.changes, &f.name)?; if !r.rc { - return Err(FormError::Invalid(r.message.unwrap_or_else(|| format!("{default} [ {} ]", f.name)))); + let message = r.message.unwrap_or_else(|| format!("{default} [ {} ]", f.name)); + // A keystroke refusal is about the typing; a validate refusal is about the value. + return Err(match event { + FieldEvent::Validate => FormError::Rejected(message), + _ => FormError::Invalid(message), + }); } v = r.value; } diff --git a/crates/forms/src/tests.rs b/crates/forms/src/tests.rs index cca4cb4881..004d8f6ef3 100644 --- a/crates/forms/src/tests.rs +++ b/crates/forms/src/tests.rs @@ -1497,7 +1497,7 @@ fn formats_validation_and_calculations_run_like_acrobat() { ); assert_eq!( set_value(&mut doc, "Qty", &FieldValue::Text("120".into())), - Err(FormError::Invalid("Invalid value: must be greater than or equal to 1 and less than or equal to 99.".into())) + Err(FormError::Rejected("Invalid value: must be greater than or equal to 1 and less than or equal to 99.".into())) ); assert_eq!(field(&fields(&doc), "Qty").value, ["2"]); // Dates: stored as typed, shown in the format; impossible dates are refused. @@ -5485,3 +5485,55 @@ fn locked_button_export_edits_leave_the_document_unchanged() { assert_eq!(write_incremental(&doc, &SaveOptions::default()).unwrap(), before); } } + +/// A validate action (ISO 32000-2 Table 199 `/V`) that refuses a value is a rejection the +/// caller can tell apart: the field keeps its value and the interface drops the typing. A +/// keystroke refusal is not one: it is about the typing, which the user may want to fix. +#[test] +fn a_validate_refusal_is_a_rejection_and_a_keystroke_refusal_is_not() { + use crate::af::Validate; + struct Checks; + impl Scripts for Checks { + fn run(&mut self, event: FieldEvent, script: &str, _: &Field, value: &str, _: &[Field]) -> ScriptResult { + let (rc, message) = match (event, script) { + (FieldEvent::Validate, "short") => (value.chars().count() <= 3, Some("At most 3 characters".to_string())), + (FieldEvent::Validate, "never") => (false, None), + (FieldEvent::Keystroke, "digits") => (value.chars().all(|c| c.is_ascii_digit()), Some("Digits only".to_string())), + _ => (true, None), + }; + ScriptResult { rc, value: value.to_string(), changes: Vec::new(), message: if rc { None } else { message } } + } + } + let mut doc = one_page(); + for (i, name) in ["G_range", "H_short", "code", "never"].into_iter().enumerate() { + let y = 10.0 + 30.0 * i as f64; + add_field(&mut doc, 0, [10.0, y, 100.0, y + 20.0], &NewField::Text { multiline: false }, Some(name)).unwrap(); + } + set_props(&mut doc, "G_range", &FieldProps { validate: Some(Validate::Range { min: Some(1.0), max: Some(100.0) }), ..FieldProps::default() }) + .unwrap(); + set_field_script(&mut doc, "H_short", "validate", Some("short")).unwrap(); + set_field_script(&mut doc, "code", "keystroke", Some("digits")).unwrap(); + set_field_script(&mut doc, "never", "validate", Some("never")).unwrap(); + let set = |doc: &mut Document, name: &str, v: &str| set_value_with(doc, name, &FieldValue::Text(v.into()), &mut Checks); + + assert_eq!( + set(&mut doc, "G_range", "150"), + Err(FormError::Rejected("Invalid value: must be greater than or equal to 1 and less than or equal to 100.".into())) + ); + assert!(field(&fields(&doc), "G_range").value.is_empty(), "the field keeps its (blank) value"); + assert_eq!(set(&mut doc, "G_range", "50"), Ok(())); + assert_eq!(field(&fields(&doc), "G_range").value, ["50"], "a value in range commits"); + assert_eq!( + set(&mut doc, "G_range", "0"), + Err(FormError::Rejected("Invalid value: must be greater than or equal to 1 and less than or equal to 100.".into())) + ); + assert_eq!(field(&fields(&doc), "G_range").value, ["50"], "and stays when the next one is refused"); + + assert_eq!(set(&mut doc, "H_short", "abcd"), Err(FormError::Rejected("At most 3 characters".into())), "the script's alert is the message"); + assert!(field(&fields(&doc), "H_short").value.is_empty()); + assert_eq!(set(&mut doc, "H_short", "abc"), Ok(())); + assert_eq!(set(&mut doc, "never", "x"), Err(FormError::Rejected("The value entered is not valid for the field [ never ]".into())), "no alert"); + + assert_eq!(set(&mut doc, "code", "x1"), Err(FormError::Invalid("Digits only".into())), "a keystroke refusal is not a rejected value"); + assert_eq!(set(&mut doc, "code", "12"), Ok(())); +} diff --git a/crates/forms/src/values.rs b/crates/forms/src/values.rs index e8615567b6..e167ffb433 100644 --- a/crates/forms/src/values.rs +++ b/crates/forms/src/values.rs @@ -208,7 +208,7 @@ pub(crate) fn write_value(doc: &mut Document, f: &Field, value: &FieldValue, scr } // Keystroke (on commit) and Validate, as Acrobat runs them before accepting a value. let t = &af::keystroke(&f.actions.format, &f.name, t).map_err(FormError::Format)?; - af::validate(&f.actions.validate, t).map_err(FormError::Invalid)?; + af::validate(&f.actions.validate, t).map_err(FormError::Rejected)?; let t = &scripting::accept(doc, f, t, scripts)?; let shadow = t.is_empty() && crate::author::ancestor_sets(doc, f.obj, b"V"); doc.update_dict(f.obj, |d| { diff --git a/crates/ui-egui/src/editing.rs b/crates/ui-egui/src/editing.rs index 8def569f58..94e0c37921 100644 --- a/crates/ui-egui/src/editing.rs +++ b/crates/ui-egui/src/editing.rs @@ -110,7 +110,12 @@ fn form_edit_pages( impl PdfCraftApp { /// Apply an edit to the active document. Returns `true` on success; failures are shown. pub fn apply_edit(&mut self, edit: Edit) -> bool { - let Some((i, id)) = self.active_ids() else { return false }; + self.try_apply_edit(edit).is_ok() + } + + /// [`Self::apply_edit`], returning why it failed (already shown to the user). + fn try_apply_edit(&mut self, edit: Edit) -> Result<(), pdfcraft_engine::EditError> { + let Some((i, id)) = self.active_ids() else { return Err(pdfcraft_engine::EditError::NoDocument) }; let label = edit.label(); let (form_before, page_count_before, had_xfa) = if let Some(d) = self.session.get(id) { (Some(std::sync::Arc::clone(&d.form)), d.info.pages.len(), d.xfa.is_some()) @@ -125,7 +130,7 @@ impl PdfCraftApp { }; match self.session.apply(id, edit.clone()) { Ok(()) => { - let Some(doc) = self.session.get(id) else { return true }; + let Some(doc) = self.session.get(id) else { return Ok(()) }; let info = &doc.info; let view = &mut self.views[i]; view.applied_editor = None; @@ -181,7 +186,7 @@ impl PdfCraftApp { } let out = self.session.take_js_output(id); self.handle_js(id, out); - true + Ok(()) } Err(e) => { if let Some(view) = self.views.get_mut(i) { @@ -199,7 +204,7 @@ impl PdfCraftApp { } let message = if matches!(edit, Edit::MoveObjects { .. }) { crate::object_ui::move_error(&e) } else { e.to_string() }; self.notify_fmt("{label} failed: {e}", &[("label", &crate::i18n::edit_label(&label)), ("e", &message)]); - false + Err(e) } } } @@ -390,7 +395,7 @@ impl PdfCraftApp { } /// Apply any edit a view queued this frame (organize toolbar, keys). - /// Returns false when a field refused the typing queued for it (its editor is open again). + /// Returns false when a field refused the typing queued for it (see [`Self::apply_queued_edit`]). pub(crate) fn process_pending_edits(&mut self) -> bool { let Some(i) = self.active else { return true }; let applied = self.apply_queued_edit(i); @@ -587,9 +592,10 @@ impl PdfCraftApp { /// anything reads the document: Save, Print, Export, Optimize, Sign, Extract, Split, Copy /// pages and button scripts. /// - /// Returns false when the field rejects the value (a validation script or format; the user - /// is told why). The editor stays open with the text, and the caller must stop: nothing is - /// saved, printed or exported without it. + /// Returns false when the field refuses the value (the user is told why), and the caller + /// must stop: nothing is saved, printed or exported behind the refusal. A value the field's + /// format refuses stays in the open editor, to be fixed; one its validate action rejects is + /// dropped and the field keeps its value (see [`Self::apply_queued_edit`]). pub(crate) fn commit_form_typing(&mut self) -> bool { let Some((i, id)) = self.active_ids() else { return true }; if !self.apply_queued_edit(i) { @@ -602,8 +608,11 @@ impl PdfCraftApp { if let Some(view) = self.views.get_mut(i) { view.forms.focus = None; } - if self.apply_edit(edit) { - return true; + match self.try_apply_edit(edit) { + Ok(()) => return true, + // The editor stays closed: the field shows the value it kept. + Err(e) if e.is_rejected_value() => return false, + Err(_) => {} } if let Some(view) = self.views.get_mut(i) { let mut draft = draft; @@ -614,8 +623,11 @@ impl PdfCraftApp { } /// Apply the edit queued on tab `i` (the active one). Returns false only when it was a - /// field's typing and the field refused it (#166): the editor reopens with the text, and the - /// user has been told why, so the typing isn't lost and the caller can stop. + /// field's typing and the field refused it, after telling the user why, so the caller can + /// stop. Typing the field's format refuses reopens in its editor (#166), so it isn't lost. + /// A value the field's validate action rejects (ISO 32000-2 Table 199 `/V`) is dropped + /// instead, as other readers do: the field keeps the value it had, and the editor Tab or a + /// click opened on the next field stays open, so the user can go on filling the form. fn apply_queued_edit(&mut self, i: usize) -> bool { let Some(edit) = self.views.get_mut(i).and_then(|v| v.pending_edit.take()) else { return true }; let signature_page = self.views.get_mut(i).and_then(|v| v.fill_signature_page.take()); @@ -624,43 +636,43 @@ impl PdfCraftApp { (Edit::SetFieldValue { name, .. }, Some(draft)) => *name == draft.name, _ => false, }; - if self.apply_edit(edit) { - // Tab can wrap to the same field (including another widget of that field). - // Its new editor was opened before this edit ran, so it still holds the old - // value. Refresh from the accepted form before Save can commit that stale draft. - if typed - && let Some(view) = self.views.get_mut(i) - && let Some(focus) = view.forms.focus.as_mut() - && focus.request_focus - && committed.as_ref().is_some_and(|draft| draft.name == focus.name) - && let Some(field) = self.session.get(view.id).and_then(|doc| doc.form.iter().find(|field| field.name == focus.name)) - { - focus.text = crate::forms_ui::draft_text(field); - focus.picked = field.value.clone(); + if let Err(e) = self.try_apply_edit(edit) { + if !typed { + return true; } - if let Some(page) = signature_page - && let Some(view) = self.views.get_mut(i) + if !e.is_rejected_value() + && let (Some(mut draft), Some(view)) = (committed, self.views.get_mut(i)) { - // Signature imports are a labeled batch; select their appended stamp just - // as AddAnnotation selects a typed or drawn signature. - let newest = self - .session - .get(view.id) - .and_then(|d| d.info.annotations.iter().filter(|a| a.page == page && !a.is_reply()).map(|a| a.index).max()); - view.comments.selected = newest.map(|index| (page, index)); - view.comments.reveal = true; - self.quick_tool = crate::QuickTool::Select; + draft.request_focus = true; + view.forms.focus = Some(draft); } - return true; + return false; } - if !typed { - return true; + // Tab can wrap to the same field (including another widget of that field). + // Its new editor was opened before this edit ran, so it still holds the old + // value. Refresh from the accepted form before Save can commit that stale draft. + if typed + && let Some(view) = self.views.get_mut(i) + && let Some(focus) = view.forms.focus.as_mut() + && focus.request_focus + && committed.as_ref().is_some_and(|draft| draft.name == focus.name) + && let Some(field) = self.session.get(view.id).and_then(|doc| doc.form.iter().find(|field| field.name == focus.name)) + { + focus.text = crate::forms_ui::draft_text(field); + focus.picked = field.value.clone(); } - if let (Some(mut draft), Some(view)) = (committed, self.views.get_mut(i)) { - draft.request_focus = true; - view.forms.focus = Some(draft); + if let Some(page) = signature_page + && let Some(view) = self.views.get_mut(i) + { + // Signature imports are a labeled batch; select their appended stamp just + // as AddAnnotation selects a typed or drawn signature. + let newest = + self.session.get(view.id).and_then(|d| d.info.annotations.iter().filter(|a| a.page == page && !a.is_reply()).map(|a| a.index).max()); + view.comments.selected = newest.map(|index| (page, index)); + view.comments.reveal = true; + self.quick_tool = crate::QuickTool::Select; } - false + true } /// [`Self::commit_form_typing`] for document `id`, which may not be the active tab (a save diff --git a/crates/ui-egui/src/tools/forms_ui.rs b/crates/ui-egui/src/tools/forms_ui.rs index 7232b1169b..f796b48268 100644 --- a/crates/ui-egui/src/tools/forms_ui.rs +++ b/crates/ui-egui/src/tools/forms_ui.rs @@ -52,8 +52,9 @@ pub struct Focus { #[derive(Clone, Debug, Default)] pub struct FormView { pub focus: Option, - /// The draft whose edit is queued (`DocView::pending_edit`): if the field refuses the value, - /// the editor reopens with it rather than losing the typing. + /// The draft whose edit is queued (`DocView::pending_edit`): if the field's format refuses + /// the value, the editor reopens with it rather than losing the typing. A value the field's + /// validate action rejects is dropped, and the field keeps its value. pub(crate) committed: Option, /// A press on a text field committed the field before it (#2213). Until the button is /// released, that field losing focus to the same gesture must not commit it again: a diff --git a/crates/ui-egui/tests/it/forms.rs b/crates/ui-egui/tests/it/forms.rs index fa828a8f9f..0b294f349b 100644 --- a/crates/ui-egui/tests/it/forms.rs +++ b/crates/ui-egui/tests/it/forms.rs @@ -846,8 +846,10 @@ fn pressing_another_text_field_validates_the_refused_value_once() { h.drop_at(p); h.run_steps(3); assert_eq!(h.state().toast, None, "the release did not validate it again"); - let focus = h.state().views[0].forms.focus.clone().expect("the refused field stays open"); - assert_eq!((focus.name.as_str(), focus.text.as_str()), ("qty", "4500")); + // The rejected value is dropped: qty keeps its value and the pressed field keeps the focus. + assert_eq!(value(&h, "qty"), ["4"]); + let focus = h.state().views[0].forms.focus.clone().expect("the pressed field is open"); + assert_eq!((focus.name.as_str(), focus.text.as_str()), ("note", "")); } /// `validated_form` plus a plain text field, `note`, under `qty`. @@ -862,6 +864,79 @@ fn validated_form_with_note() -> Vec { ]) } +/// Three blank text fields in tab order: `G_range` validates with the range function (1 to +/// 100), `H_short` with a script that alerts and sets `event.rc` false past 3 characters, and +/// `note` takes anything. +fn range_and_script_validated_form() -> Vec { + pdf_from_objects(&[ + "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R 5 0 R 6 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 7 0 R >> >> >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >>", + "<< /Type /Page /Parent 2 0 R /Annots [4 0 R 5 0 R 6 0 R] >>", + "<< /Type /Annot /Subtype /Widget /FT /Tx /T (G_range) /Rect [20 350 280 372] /P 3 0 R /F 4 /AA << /V << /S /JavaScript /JS (AFRange_Validate\\(true, 1, true, 100\\);) >> >> >>", + "<< /Type /Annot /Subtype /Widget /FT /Tx /T (H_short) /Rect [20 300 280 322] /P 3 0 R /F 4 /AA << /V << /S /JavaScript /JS (if \\(event.value.length > 3\\) { app.alert\\(\"At most 3 characters\"\\); event.rc = false; }) >> >> >>", + "<< /Type /Annot /Subtype /Widget /FT /Tx /T (note) /Rect [20 250 280 272] /P 3 0 R /F 4 >>", + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>", + ]) +} + +/// A value a field's validate action rejects (ISO 32000-2 Table 199 `/V`) is dropped, as other +/// readers do: the message shows, the field keeps its value, nothing is added to undo, and Tab +/// goes on to the next field instead of holding the user in the rejected one. +#[test] +fn a_value_the_validate_action_rejects_reverts_and_tab_moves_on() { + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| { + let mut app = PdfCraftApp::new(); + app.set_option("language", "en").unwrap(); + app.open_bytes("rows.pdf", None, range_and_script_validated_form()).unwrap(); + app.set_option("left", "closed").unwrap(); + app.set_option("zoom", "150").unwrap(); + app + }); + h.run_steps(6); + let toast = |h: &Harness<'static, PdfCraftApp>| h.state().toast.as_ref().map(|t| t.0.clone()).unwrap_or_default(); + let unchanged = |h: &Harness<'static, PdfCraftApp>| { + let doc = h.state().session.get(h.state().views[0].id).unwrap(); + !doc.dirty && doc.can_undo().is_none() + }; + let type_and_tab = |h: &mut Harness<'static, PdfCraftApp>, text: &str| { + h.event(egui::Event::Text(text.into())); + h.run_steps(2); + h.key_press(egui::Key::Tab); + h.run_steps(3); + }; + + click_field(&mut h, "G_range", 0); + type_and_tab(&mut h, "150"); + assert!(toast(&h).contains("Invalid value"), "the range's message shows: {:?}", toast(&h)); + assert!(value(&h, "G_range").is_empty(), "G keeps its blank value"); + assert_eq!(focused(&h).map(|(n, _)| n).as_deref(), Some("H_short"), "Tab moved on"); + assert_eq!(h.state().views[0].forms.focus.as_ref().map(|f| f.text.as_str()), Some("")); + assert!(unchanged(&h), "a rejected value is no change and no undo step"); + + h.state_mut().toast = None; + type_and_tab(&mut h, "abcd"); + assert!(toast(&h).contains("At most 3 characters"), "the script's alert shows: {:?}", toast(&h)); + assert!(value(&h, "H_short").is_empty()); + assert_eq!(focused(&h).map(|(n, _)| n).as_deref(), Some("note")); + assert!(unchanged(&h)); + + // The next field fills in as usual, and so does a value in range. + type_and_tab(&mut h, "x"); + assert_eq!(value(&h, "note"), ["x"]); + click_field(&mut h, "G_range", 0); + type_and_tab(&mut h, "50"); + assert_eq!(value(&h, "G_range"), ["50"]); + // Undo steps through the two accepted values only. + h.state_mut().undo(); + h.run_steps(2); + assert!(value(&h, "G_range").is_empty()); + assert_eq!(value(&h, "note"), ["x"]); + h.state_mut().undo(); + h.run_steps(2); + assert!(value(&h, "note").is_empty()); + assert!(h.state().session.get(h.state().views[0].id).unwrap().can_undo().is_none(), "and nothing else is left to undo"); +} + fn pdf_from_objects(objs: &[&str]) -> Vec { let mut out = b"%PDF-1.7\n".to_vec(); let mut offsets = Vec::new(); @@ -951,7 +1026,7 @@ fn buttons_over_text_show_the_pointing_hand_not_the_i_beam() { } #[test] -fn a_rejected_value_keeps_the_typing_and_stops_the_save() { +fn a_rejected_value_is_dropped_and_stops_the_save() { let dir = scratch("rejected"); let out = dir.join("saved.pdf"); let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| { @@ -969,13 +1044,15 @@ fn a_rejected_value_keeps_the_typing_and_stops_the_save() { h.state_mut().save_override = Some(out.to_string_lossy().into_owned()); h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::S); h.run_steps(4); - assert!(!out.exists(), "nothing is saved without the typed value"); + assert!(!out.exists(), "the save stops at the refusal, so the user sees it first"); + assert!(h.state().toast.as_ref().is_some_and(|t| t.0.contains("At most 100")), "the script's message is shown: {:?}", h.state().toast); assert_eq!(value(&h, "qty"), ["4"], "the field keeps its valid value"); - let focus = h.state().views[0].forms.focus.clone().expect("the editor stays open"); - assert_eq!(focus.text, "4500", "with the text (typed after the 4), so the user can fix it"); - // And closing asks rather than dropping it. + assert!(h.state().views[0].forms.focus.is_none(), "the rejected 4500 is dropped, not held in an editor"); + let doc = h.state().session.get(h.state().views[0].id).unwrap(); + assert!(!doc.dirty && doc.can_undo().is_none(), "a rejected value is no change and no undo step"); + // Closing has nothing to ask about. h.state_mut().request_close_tab(0); - assert!(h.state().close_request.is_some()); + assert!(h.state().close_request.is_none()); let _ = std::fs::remove_dir_all(&dir); } @@ -1027,11 +1104,11 @@ fn refused_value_stops_save(commit_key: egui::Key, case: &str) { h.run_steps(3); assert_eq!(value(&h, "qty"), ["4"]); assert!(!out.exists(), "nothing is saved right after the field refused its value"); - // The refused text is back in the field, so a later ⌘S stops again instead of saving 4. - assert_eq!(h.state().views[0].forms.focus.as_ref().map(|f| f.text.as_str()), Some("4500")); - h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::S); - h.run_steps(4); - assert!(!out.exists()); + // The rejected text is dropped: Enter closes the editor, and Tab wraps to the only field, + // which shows the value it kept. + let expected = if commit_key == egui::Key::Tab { Some("4") } else { None }; + assert_eq!(h.state().views[0].forms.focus.as_ref().map(|f| f.text.as_str()), expected); + assert!(!h.state().session.get(h.state().views[0].id).unwrap().dirty); let _ = std::fs::remove_dir_all(&dir); } @@ -1109,7 +1186,8 @@ mod revert_tests { h.run_steps(2); h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::S); h.run_steps(4); - assert_eq!(h.state().views[0].forms.focus.as_ref().unwrap().text, "99"); + assert!(h.state().views[0].forms.focus.is_none(), "the rejected 99 is dropped"); + assert_eq!(value(&h, "name"), ["Saved original"]); assert_eq!(std::fs::read(&path).unwrap(), saved, "rejection leaves the saved file untouched"); assert!(h.state_mut().execute("file.revert")); h.run_steps(2); diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 0b6f658dd6..c57a7fdd49 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -4643,8 +4643,8 @@ milestone = "M6" status = "shipped" commands = ["form.field.properties"] tools = ["form_set_props", "form_fill"] -evidence = ["crates/forms/src/af/tests.rs::validation_and_calculation", "crates/forms/src/tests.rs::formats_validation_and_calculations_run_like_acrobat", "crates/automation/tests/it/automation.rs::form_formats_and_calculations_through_tools"] -notes = "AFRange_Validate with Acrobat's messages" +evidence = ["crates/forms/src/af/tests.rs::validation_and_calculation", "crates/forms/src/tests.rs::formats_validation_and_calculations_run_like_acrobat", "crates/automation/tests/it/automation.rs::form_formats_and_calculations_through_tools", "crates/forms/src/tests.rs::a_validate_refusal_is_a_rejection_and_a_keystroke_refusal_is_not", "crates/ui-egui/tests/it/forms.rs::a_value_the_validate_action_rejects_reverts_and_tab_moves_on"] +notes = "AFRange_Validate with Acrobat's messages. A value it (or a custom validate script setting event.rc false) rejects is not stored: the app shows the message, the field keeps its previous value and Tab or a click moves on, with no undo step; form_fill reports it as an error. Messages still show as a notice, not a modal dialog." [[feature]] id = "form.af-simple-calculate" @@ -4679,8 +4679,8 @@ milestone = "M6" status = "shipped" commands = ["form.prepare"] tools = ["form_set_script"] -evidence = ["crates/engine/src/tests.rs::form_javascript_validates_calculates_and_formats", "crates/automation/tests/it/automation.rs::javascript_through_tools"] -notes = "Custom keystroke (commit), validate, calculate and format scripts run in Acrobat's event order; AF calls still run natively." +evidence = ["crates/engine/src/tests.rs::form_javascript_validates_calculates_and_formats", "crates/automation/tests/it/automation.rs::javascript_through_tools", "crates/ui-egui/tests/it/forms.rs::a_value_the_validate_action_rejects_reverts_and_tab_moves_on"] +notes = "Custom keystroke (commit), validate, calculate and format scripts run in Acrobat's event order; AF calls still run natively. A validate script that sets event.rc false rejects the value: it is not stored, its alert is the message shown, and the field keeps its previous value." [[feature]] id = "form.calculation-order" From 469ccef1c3383db2ff2f6ca54edb8f76eb68a175 Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Sun, 25 Oct 2026 01:53:18 +0800 Subject: [PATCH 06/30] M6: a toolbar action queued with a rejected field value does not run process_pending_edits already cleared the deferred shortcuts when the queued field edit was refused, but still ran the view's pending_action. Organize's Save pages queued in the same frame as a value the field's validate action (ISO 32000-2 Table 199 /V) rejects would therefore save behind the refusal, since the rejected draft is dropped and the commit before the save no longer stops it. The pending action is now taken and dropped unless the edit was applied. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0175FWj4xFhMhSH3UpMU8DSC --- crates/ui-egui/src/editing.rs | 72 ++++++++++++++++++++++++++++++++++- 1 file changed, 70 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/editing.rs b/crates/ui-egui/src/editing.rs index 94e0c37921..e6c072abb7 100644 --- a/crates/ui-egui/src/editing.rs +++ b/crates/ui-egui/src/editing.rs @@ -400,10 +400,11 @@ impl PdfCraftApp { let Some(i) = self.active else { return true }; let applied = self.apply_queued_edit(i); if !applied { - // Nor may a shortcut pressed with it (⌘S right after Enter) run behind the refusal. + // Nor may a shortcut pressed with it (⌘S right after Enter) run behind the refusal, + // nor a toolbar action queued in the same frame (Organize ▸ Save pages). self.deferred_commands.clear(); } - match self.views.get_mut(i).and_then(|v| v.pending_action.take()) { + match self.views.get_mut(i).and_then(|v| v.pending_action.take()).filter(|_| applied) { Some(crate::canvas::ViewAction::InsertFromFile) => self.insert_from_file_dialog(), Some(crate::canvas::ViewAction::InsertFromFileAt(at)) => self.insert_from_file_at(Some(at)), Some(crate::canvas::ViewAction::ReplacePages) => self.replace_pages_dialog(), @@ -1229,3 +1230,70 @@ mod attention_tests { assert!(attend(&mut app, &ctx, false).is_empty(), "the user has seen it"); } } + +#[cfg(test)] +mod rejected_value_tests { + use crate::PdfCraftApp; + use crate::canvas::ViewAction; + use crate::forms_ui::Focus; + use pdfcraft_engine::Edit; + + /// One page with a text field `qty` (value 4) whose validate action (ISO 32000-2 Table 199 + /// `/V`) rejects anything over 100. + fn validated_form() -> Vec { + let objs = [ + "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >>", + "<< /Type /Page /Parent 2 0 R /Annots [4 0 R] >>", + "<< /Type /Annot /Subtype /Widget /FT /Tx /T (qty) /V (4) /Rect [20 350 280 372] /P 3 0 R /F 4 /AA << /V << /S /JavaScript /JS (if (event.value > 100) { app.alert('At most 100'); event.rc = false; }) >> >> >>", + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>", + ]; + let mut out = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes()); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offsets { + out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + out + } + + /// A toolbar Save (Organize ▸ Save pages) queued in the frame whose typed value the validate + /// action rejects does not run behind the refusal, just as a ⌘S pressed with it does not. + #[test] + fn a_save_action_queued_with_a_rejected_value_does_not_run() { + let dir = std::env::temp_dir().join(format!("pdfcraft-ui-rejected-action-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let out = dir.join("saved.pdf"); + let mut app = PdfCraftApp::new(); + app.open_bytes("order.pdf", None, validated_form()).unwrap(); + app.active = Some(0); + app.save_override = Some(out.to_string_lossy().into_owned()); + let view = &mut app.views[0]; + view.forms.committed = Some(Focus { + name: "qty".into(), + widget: 0, + text: "4500".into(), + picked: Vec::new(), + request_focus: false, + select_all: false, + press: None, + calendar: None, + calendar_rect: None, + calendar_text: None, + had_focus: false, + }); + view.pending_edit = Some(Edit::SetFieldValue { name: "qty".into(), value: pdfcraft_engine::FieldValue::Text("4500".into()) }); + view.pending_action = Some(ViewAction::Save); + assert!(!app.process_pending_edits(), "the validate action rejects 4500"); + assert!(!out.exists(), "the queued Save does not run behind the refusal"); + assert!(app.views[0].pending_action.is_none(), "nor is it left to run later"); + let _ = std::fs::remove_dir_all(&dir); + } +} From e9df5b65a3b612097544bb12444c4984a1ae61e0 Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Sun, 25 Oct 2026 02:41:12 +0800 Subject: [PATCH 07/30] M3: a GoToE link opens the PDF embedded in the document A link with an embedded go-to action only reported "This PDF uses the unsupported GoToE action." although the Attachments panel could open the attached PDF it names. - render::inspect reads GoToE (ISO 32000-2 12.6.4.4, Tables 204-205) to a child target (/R /C) by its EmbeddedFiles /N key or its file attachment annotation (/P page or named destination, /A index or /NM), with /D read by the GoToR destination reader. The parent, nested paths, /F and malformed targets stay unsupported. - ui-egui opens the attachment from the document's own bytes through the Attachments panel's path (attachment_data, open_bytes) and goes to /D as a GoToR link does; a file that isn't attached or isn't a PDF opens nothing and says so. - link_open follows GoToE headlessly; doc_info reports the target. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0175FWj4xFhMhSH3UpMU8DSC --- crates/automation/src/json.rs | 13 ++ crates/automation/src/links.rs | 85 +++++++++--- crates/automation/src/tools.rs | 2 +- crates/automation/tests/it/automation.rs | 59 +++++++++ crates/render/src/inspect/annotations.rs | 59 ++++++++- crates/render/src/inspect/model.rs | 9 ++ crates/render/src/inspect/tests.rs | 65 +++++++++ crates/ui-egui/src/app/links.rs | 45 +++++++ crates/ui-egui/src/canvas.rs | 41 ++++-- crates/ui-egui/tests/it/embedded_links.rs | 152 ++++++++++++++++++++++ crates/ui-egui/tests/it/main.rs | 1 + parity/acrobat-features.toml | 4 +- 12 files changed, 498 insertions(+), 37 deletions(-) create mode 100644 crates/ui-egui/tests/it/embedded_links.rs diff --git a/crates/automation/src/json.rs b/crates/automation/src/json.rs index 9e93d4c347..8ee20e8950 100644 --- a/crates/automation/src/json.rs +++ b/crates/automation/src/json.rs @@ -353,6 +353,19 @@ pub(crate) fn info(d: &Document) -> Value { }, "new_window": new_window, }), + pdfcraft_render::LinkTarget::EmbeddedGoTo { source, destination, new_window } => json!({ + "action": "GoToE", + "embedded_file": match source { + pdfcraft_render::AttachmentSource::Document { key } => json!({ "name": key }), + pdfcraft_render::AttachmentSource::Annotation { page, index } => json!({ "page": page1(*page), "annotation": index.saturating_add(1) }), + }, + "destination": match destination { + pdfcraft_render::RemoteDestination::Default => json!({ "kind": "default" }), + pdfcraft_render::RemoteDestination::Page { page, view } => json!({ "kind": "page", "page": page1(*page), "view": format!("{view:?}") }), + pdfcraft_render::RemoteDestination::Named(name) => json!({ "kind": "named", "name": name }), + }, + "new_window": new_window, + }), pdfcraft_render::LinkTarget::Other(o) => json!({ "other": o }), }, })).collect::>(), diff --git a/crates/automation/src/links.rs b/crates/automation/src/links.rs index 41fda9b7db..65124bd12d 100644 --- a/crates/automation/src/links.rs +++ b/crates/automation/src/links.rs @@ -4,7 +4,7 @@ use pdfcraft_engine::{ Edit, LinkAction, LinkHighlight, LinkStyle, read_remote_document, remote_document_path_is_absolute, resolve_remote_document_path, }; -use pdfcraft_render::{DestView, LinkTarget, RemoteDestination}; +use pdfcraft_render::{AttachmentSource, DestView, LinkTarget, RemoteDestination}; use serde_json::{Value, json}; use std::path::Path; @@ -117,10 +117,15 @@ impl Automation { .iter() .find(|link| link.page == page && link.index == index) .ok_or_else(|| failed(format!("page {page_number} has no link {index_number} (see link_list)")))?; - let LinkTarget::RemoteGoTo { file, destination, new_window, .. } = &link.target else { - return Err(bad("the selected link is not a supported local PDF GoToR link")); + let (file, destination, new_window) = match &link.target { + LinkTarget::RemoteGoTo { file, destination, new_window, .. } => (file.clone(), destination.clone(), *new_window), + LinkTarget::EmbeddedGoTo { source: attached, destination, new_window } => { + let (attached, destination, new_window) = (attached.clone(), destination.clone(), *new_window); + return self.open_embedded_link(a, &attached, destination, new_window); + } + _ => return Err(bad("the selected link is not a supported local PDF GoToR or embedded GoToE link")), }; - (source.path.clone(), file.clone(), destination.clone(), *new_window) + (source.path.clone(), file, destination, new_window) }; let path = resolve_remote_document_path(source_path.as_deref().map(Path::new), &file).map_err(failed)?; let allow_absolute = a.opt_bool("allow_absolute")?.unwrap_or(false); @@ -135,20 +140,7 @@ impl Automation { let id = self.session.open(name, Some(path.to_string_lossy().into_owned()), std::sync::Arc::new(bytes), a.opt_str("password")?).map_err(failed)?; let opened = self.session.get(id).ok_or_else(|| failed("the linked document vanished"))?; - let (destination_applied, destination_value, warning) = match destination { - RemoteDestination::Default => (true, json!({ "kind": "default" }), None), - RemoteDestination::Named(name) => { - (false, json!({ "kind": "named", "name": name }), Some("The PDF opened, but the named destination was not applied.")) - } - RemoteDestination::Page { page, view } if page < opened.info.pages.len() => { - (true, json!({ "kind": "page", "page": page.saturating_add(1), "view": dest_view_value(view) }), None) - } - RemoteDestination::Page { page, view } => ( - false, - json!({ "kind": "page", "page": page.saturating_add(1), "view": dest_view_value(view) }), - Some("The PDF opened, but the link's page destination is out of range."), - ), - }; + let (destination_applied, destination_value, warning) = destination_report(destination, opened.info.pages.len()); let mut display_path = path.to_string_lossy().into_owned(); if let Some(root) = &self.root && let Ok(relative) = path.strip_prefix(root) @@ -165,6 +157,44 @@ impl Automation { })) } + /// `link_open` for an embedded Go-To link (ISO 32000-2 §12.6.4.4): open the PDF attached to + /// the document, from the document's own bytes, as a new document. No file is read, so + /// `--root` has nothing to confine. + fn open_embedded_link( + &mut self, + a: &Args, + attached: &AttachmentSource, + destination: RemoteDestination, + new_window: Option, + ) -> Result { + let (name, bytes) = { + let doc = self.doc(a)?; + let att = doc + .info + .attachments + .iter() + .find(|x| x.source == *attached) + .ok_or_else(|| failed("the file this GoToE link names is not attached to the document"))?; + let bytes = pdfcraft_render::attachment_data(&doc.bytes, doc.password.as_deref(), att).map_err(failed)?; + (att.name.clone(), bytes) + }; + // "Embedded go-to actions work only for files of Type PDF" (§12.6.4.4). + if !bytes.get(..bytes.len().min(1024)).is_some_and(|head| head.windows(5).any(|w| w == b"%PDF-")) { + return Err(failed(format!("{name} is not a PDF, so the GoToE link can't open it"))); + } + let id = self.session.open(name.clone(), None, std::sync::Arc::new(bytes), a.opt_str("password")?).map_err(failed)?; + let opened = self.session.get(id).ok_or_else(|| failed("the linked document vanished"))?; + let (destination_applied, destination_value, warning) = destination_report(destination, opened.info.pages.len()); + Ok(json!({ + "document": crate::summary(opened), + "embedded_file": name, + "destination_applied": destination_applied, + "destination": destination_value, + "warning": warning, + "new_window_hint": new_window, + })) + } + pub(crate) fn link_add(&mut self, a: &Args) -> Result { let page = self.page(a)?; let rect = self.view_rect(a, page)?.ok_or_else(|| bad("link_add needs rect"))?; @@ -225,6 +255,25 @@ impl Automation { } } +/// Whether a remote or embedded Go-To's destination could be applied in a document of `pages` +/// pages, as `link_open` reports it, with a warning when not. +fn destination_report(destination: RemoteDestination, pages: usize) -> (bool, Value, Option<&'static str>) { + match destination { + RemoteDestination::Default => (true, json!({ "kind": "default" }), None), + RemoteDestination::Named(name) => { + (false, json!({ "kind": "named", "name": name }), Some("The PDF opened, but the named destination was not applied.")) + } + RemoteDestination::Page { page, view } if page < pages => { + (true, json!({ "kind": "page", "page": page.saturating_add(1), "view": dest_view_value(view) }), None) + } + RemoteDestination::Page { page, view } => ( + false, + json!({ "kind": "page", "page": page.saturating_add(1), "view": dest_view_value(view) }), + Some("The PDF opened, but the link's page destination is out of range."), + ), + } +} + fn dest_view_value(view: DestView) -> Value { match view { DestView::Top => json!({ "kind": "top" }), diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index c6c200cece..3cc78278a9 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -688,7 +688,7 @@ pub fn tools() -> Vec { t("link_list", "List links", "Every link: page, 1-based index (for link_edit/link_delete), rect (points from the top-left of the page), and where it goes (url or to_page).") .ro() .with(schema(json!({ "doc": doc() }), &["doc"])), - t("link_open", "Open a linked PDF", "Follow a local GoToR link in PdfCraft: open the referenced PDF as a new document, respecting --root. page and index use link_list numbering. Named destinations are reported but not applied. Absolute file specifications require allow_absolute: true after reviewing the target; relative links need no opt-in.") + t("link_open", "Open a linked PDF", "Follow a local GoToR link in PdfCraft: open the referenced PDF as a new document, respecting --root. page and index use link_list numbering. Named destinations are reported but not applied. Absolute file specifications require allow_absolute: true after reviewing the target; relative links need no opt-in. A GoToE link opens the PDF embedded in this document that it names (a child target), from the document itself.") .with(schema( json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1 }, "index": { "type": "integer", "minimum": 1 }, "password": { "type": "string", "description": "Optional password for the linked PDF." }, "allow_absolute": { "type": "boolean", "description": "Explicitly allow an absolute local GoToR target (default false). Existing validation and --root confinement still apply." } }), &["doc", "page", "index"], diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index 6a5765b911..3db134f89c 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -5597,6 +5597,65 @@ fn a_launch_link_to_a_pdf_opens_it_like_a_remote_link() { assert_eq!(a.session().docs().len(), before, "nothing was opened or launched"); } +/// An embedded Go-To link (ISO 32000-2 §12.6.4.4) opens the PDF attached to the document, from +/// the document itself: no file of that name is read, inside the root or out of it. One to a +/// file that isn't attached, or isn't a PDF, opens nothing. +#[test] +fn an_embedded_go_to_link_opens_the_attached_pdf() { + let (_base, root) = sandbox("gotoe"); + // A file of the attachment's name next to the document, which must not be what opens. + std::fs::write(root.join("inner.pdf"), fixture(1)).unwrap(); + let embedded = fixture(3); + let stream = |dict: &str, data: &[u8]| { + let mut s = format!("<< {dict} /Length {} >>\nstream\n", data.len()).into_bytes(); + s.extend_from_slice(data); + s.extend_from_slice(b"\nendstream"); + s + }; + let objs: Vec> = vec![ + b"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles << /Names [(inner.pdf) 5 0 R (notes.txt) 6 0 R] >> >> >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /Annots [7 0 R 8 0 R 9 0 R] >>".to_vec(), + stream("/Type /EmbeddedFile", &embedded), + b"<< /Type /Filespec /F (inner.pdf) /UF (inner.pdf) /EF << /F 4 0 R >> >>".to_vec(), + b"<< /Type /Filespec /F (notes.txt) /EF << /F 10 0 R >> >>".to_vec(), + b"<< /Type /Annot /Subtype /Link /Rect [0 0 10 10] /A << /S /GoToE /T << /R /C /N (inner.pdf) >> /D [2 /Fit] >> >>".to_vec(), + b"<< /Type /Annot /Subtype /Link /Rect [0 20 10 30] /A << /S /GoToE /T << /R /C /N (missing.pdf) >> /D [0 /Fit] >> >>".to_vec(), + b"<< /Type /Annot /Subtype /Link /Rect [0 40 10 50] /A << /S /GoToE /T << /R /C /N (notes.txt) >> /D [0 /Fit] >> >>".to_vec(), + stream("/Type /EmbeddedFile", b"just some notes"), + ]; + let mut pdf = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(pdf.len()); + pdf.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes()); + pdf.extend_from_slice(o); + pdf.extend_from_slice(b"\nendobj\n"); + } + let xref = pdf.len(); + pdf.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offsets { + pdf.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + pdf.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + std::fs::write(root.join("outer.pdf"), pdf).unwrap(); + let mut a = auto(&root); + let source = ok(&mut a, "doc_open", json!({ "path": "outer.pdf" }))["doc"].as_u64().unwrap(); + let info = ok(&mut a, "doc_info", json!({ "doc": source })); + let link = &info["links"][0]["target"]; + assert_eq!((link["action"].as_str(), &link["embedded_file"]), (Some("GoToE"), &json!({ "name": "inner.pdf" })), "{info}"); + let opened = ok(&mut a, "link_open", json!({ "doc": source, "page": 1, "index": 1 })); + assert_eq!(opened["document"]["pages"], 3, "the attached PDF, not the file beside the document: {opened}"); + assert_eq!((opened["embedded_file"].as_str(), opened["destination_applied"].as_bool()), (Some("inner.pdf"), Some(true))); + assert_eq!(opened["destination"], json!({ "kind": "page", "page": 3, "view": { "kind": "fit" } }), "{opened}"); + let before = a.session().docs().len(); + for (index, why) in [(2, "not attached"), (3, "notes.txt is not a PDF")] { + let e = err(&mut a, "link_open", json!({ "doc": source, "page": 1, "index": index })); + assert!(matches!(&e, ToolError::Failed(m) if m.contains(why)), "{e}"); + } + assert_eq!(a.session().docs().len(), before, "nothing else was opened"); +} + #[test] fn local_gotor_link_open_refuses_directories_devices_and_non_pdf_targets() { let (_base, root) = sandbox("gotor-not-a-file"); diff --git a/crates/render/src/inspect/annotations.rs b/crates/render/src/inspect/annotations.rs index 603aa88110..dace729e3d 100644 --- a/crates/render/src/inspect/annotations.rs +++ b/crates/render/src/inspect/annotations.rs @@ -214,6 +214,7 @@ impl<'a> Inspector<'a> { Some("SetOCGState") => self.layer_state(a), Some("GoToR") => self.remote_go_to(a).unwrap_or_else(|| LinkTarget::Other("GoToR".into())), Some("Launch") => self.launch_pdf(a).unwrap_or_else(|| LinkTarget::Other("Launch".into())), + Some("GoToE") => self.embedded_go_to(a, text_budget).unwrap_or_else(|| LinkTarget::Other("GoToE".into())), Some(other) => LinkTarget::Other(other.to_string()), None => return None, } @@ -223,7 +224,15 @@ impl<'a> Inspector<'a> { fn remote_go_to(&self, action: &Dictionary) -> Option { let file = self.action_file(action)?; - let destination = match action.get(b"D") { + let destination = self.remote_destination(action)?; + Some(LinkTarget::RemoteGoTo { launch: false, file, destination, new_window: self.new_window(action) }) + } + + /// The `/D` of a remote or embedded Go-To: a destination in another document, so an + /// explicit one names its page by number (§12.3.2.2). No `/D` is that document's default + /// view; an unusable one is `None`. + fn remote_destination(&self, action: &Dictionary) -> Option { + Some(match action.get(b"D") { Err(_) => RemoteDestination::Default, Ok(o) => match self.resolve(o) { Object::Array(items) => { @@ -248,8 +257,54 @@ impl<'a> Inspector<'a> { } _ => return None, }, + }) + } + + /// An embedded Go-To action (§12.6.4.4). Only a child of this document is opened: a target + /// dictionary with `/R /C` and no further `/T`, naming the file by its `/N` key in the + /// EmbeddedFiles name tree, or, for a file attachment annotation, by `/P` (a page number, or + /// a named destination giving it) and `/A` (the annotation's index in `/Annots`, or its + /// `/NM`) (Table 205). The parent (`/R /P`), a nested path, or a target under another root + /// document (`/F`) is `None`: not followed. + fn embedded_go_to(&self, action: &Dictionary, text_budget: &mut usize) -> Option { + if action.has(b"F") { + return None; + } + let t = self.dict(action.get(b"T").ok()?)?; + if self.name(t, b"R").as_deref() != Some("C") || t.has(b"T") { + return None; + } + let source = match t.get(b"N") { + Ok(n) => { + let Object::String(bytes, _) = self.resolve(n) else { return None }; + // Converted as the EmbeddedFiles keys `DocInfo::attachments` lists are. + AttachmentSource::Document { key: spend(bytes, text_budget, text_string)? } + } + Err(_) => { + let page = match self.resolve(t.get(b"P").ok()?) { + Object::Integer(p) => usize::try_from(*p).ok()?, + named @ Object::String(..) => self.dest(named, 0)?.0, + _ => return None, + }; + let index = match self.resolve(t.get(b"A").ok()?) { + Object::Integer(i) => usize::try_from(*i).ok()?, + Object::String(nm, _) => self.annotation_named(page, nm)?, + _ => return None, + }; + AttachmentSource::Annotation { page, index } + } }; - Some(LinkTarget::RemoteGoTo { launch: false, file, destination, new_window: self.new_window(action) }) + Some(LinkTarget::EmbeddedGoTo { source, destination: self.remote_destination(action)?, new_window: self.new_window(action) }) + } + + /// The position in page `page`'s `/Annots` of the first annotation whose `/NM` is `nm`. + fn annotation_named(&self, page: usize, nm: &[u8]) -> Option { + let id = *self.page_ids.get(page)?; + let page = self.doc.get_dictionary(id).ok()?; + let Object::Array(annots) = self.resolve(page.get(b"Annots").ok()?) else { return None }; + annots.iter().position(|a| { + self.dict(a).and_then(|d| d.get(b"NM").ok()).is_some_and(|n| matches!(self.resolve(n), Object::String(b, _) if b.as_slice() == nm)) + }) } /// The non-empty local file an action's `/F` names (a string or a file specification), shared diff --git a/crates/render/src/inspect/model.rs b/crates/render/src/inspect/model.rs index 490897b60f..bebcea06ba 100644 --- a/crates/render/src/inspect/model.rs +++ b/crates/render/src/inspect/model.rs @@ -220,6 +220,15 @@ pub enum LinkTarget { destination: RemoteDestination, new_window: Option, }, + /// An embedded Go-To action (ISO 32000-2 §12.6.4.4, Tables 204–205) to a PDF embedded in + /// this document: the attachment its target dictionary names as a child (`/R /C`), by its + /// `/N` key in the EmbeddedFiles name tree or by its file attachment annotation (`/P`, `/A`), + /// and the destination `/D` in it. The caller opens it from this document's bytes. + EmbeddedGoTo { + source: AttachmentSource, + destination: RemoteDestination, + new_window: Option, + }, Other(String), } diff --git a/crates/render/src/inspect/tests.rs b/crates/render/src/inspect/tests.rs index a5bfec474d..ef97f77a57 100644 --- a/crates/render/src/inspect/tests.rs +++ b/crates/render/src/inspect/tests.rs @@ -1245,6 +1245,71 @@ fn launch_actions_that_name_a_pdf_open_it_like_a_remote_link() { ); } +/// Embedded Go-To actions (§12.6.4.4, Tables 204–205) to a child of this document are read +/// with the attachment they name; the parent, a nested path, another root document or a +/// malformed target stays an action that isn't followed. +#[test] +fn links_read_embedded_go_to_actions_to_attached_pdfs() { + let actions = [ + "<< /S /GoToE /T << /R /C /N (inner.pdf) >> /D [2 /FitH 100] /NewWindow true >>", + "<< /S /GoToE /T << /R /C /P 0 /A 1 >> >>", + "<< /S /GoToE /T << /R /C /P 0 /A (att-1) >> /D (chapter) >>", + "<< /S /GoToE /T << /R /C /P (here) /A 1 >> /D [0 /Fit] >>", + "<< /S /GoToE /T << /R /P >> /D [0 /Fit] >>", + "<< /S /GoToE /T << /R /P /N (inner.pdf) >> /D [0 /Fit] >>", + "<< /S /GoToE /T << /R /C /N (inner.pdf) /T << /R /C /N (deeper.pdf) >> >> /D [0 /Fit] >>", + "<< /S /GoToE /F (other.pdf) /T << /R /C /N (inner.pdf) >> /D [0 /Fit] >>", + "<< /S /GoToE /T << /R /C /N /inner.pdf >> /D [0 /Fit] >>", + "<< /S /GoToE /T << /R /C /P 0 /A (no-such-name) >> /D [0 /Fit] >>", + "<< /S /GoToE /T << /R /C /P -1 /A 1 >> /D [0 /Fit] >>", + "<< /S /GoToE /T << /R /C /N (inner.pdf) >> /D [/Fit] >>", + "<< /S /GoToE >>", + ]; + let mut pdf = String::from( + "%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R /Names << /Dests << /Names [(here) [3 0 R /Fit]] >> >> >> endobj\n\ + 2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >> endobj\n", + ); + let annots: Vec = (0..=actions.len()).map(|k| format!("{} 0 R", 30 + k)).collect(); + pdf.push_str(&format!("3 0 obj << /Type /Page /Parent 2 0 R /Annots [{}] >> endobj\n", annots.join(" "))); + // Index 0 is a link; index 1 the file attachment annotation, named att-1. + pdf.push_str(&format!("30 0 obj << /Type /Annot /Subtype /Link /Rect [0 0 10 10] /A {} >> endobj\n", actions[0])); + pdf.push_str("31 0 obj << /Type /Annot /Subtype /FileAttachment /Rect [0 0 10 10] /NM (att-1) >> endobj\n"); + for (k, a) in actions.iter().enumerate().skip(1) { + pdf.push_str(&format!("{} 0 obj << /Type /Annot /Subtype /Link /Rect [0 0 10 10] /A {a} >> endobj\n", 31 + k)); + } + pdf.push_str("trailer << /Root 1 0 R >>\n%%EOF"); + let info = inspect(Arc::new(pdf.into_bytes()), None).expect("opens"); + let targets: Vec<_> = info.links.iter().map(|l| l.target.clone()).collect(); + let annotation = AttachmentSource::Annotation { page: 0, index: 1 }; + let embedded = |source: &AttachmentSource, destination, new_window| LinkTarget::EmbeddedGoTo { source: source.clone(), destination, new_window }; + let other = || LinkTarget::Other("GoToE".into()); + assert_eq!( + targets, + [ + embedded( + &AttachmentSource::Document { key: "inner.pdf".into() }, + RemoteDestination::Page { page: 2, view: DestView::FitH { top: Some(100.0) } }, + Some(true) + ), + // No /D: the document's default view. + embedded(&annotation, RemoteDestination::Default, None), + // /A by the annotation's /NM; a named destination in the target. + embedded(&annotation, RemoteDestination::Named("chapter".into()), None), + // /P by a named destination of this document. + embedded(&annotation, RemoteDestination::Page { page: 0, view: DestView::Fit }, None), + other(), + other(), + other(), + other(), + other(), + other(), + other(), + other(), + other(), + ] + ); +} + #[test] fn links_read_bounded_local_remote_go_to_actions() { use DestView::{Fit, Xyz}; diff --git a/crates/ui-egui/src/app/links.rs b/crates/ui-egui/src/app/links.rs index 77f9519972..139d1db85e 100644 --- a/crates/ui-egui/src/app/links.rs +++ b/crates/ui-egui/src/app/links.rs @@ -65,6 +65,45 @@ impl PdfCraftApp { self.pending_remote_link = None; } + /// Follow a link's embedded Go-To action (ISO 32000-2 §12.6.4.4): open the PDF attached to + /// document `doc` at `source` in a new tab, as the Attachments panel's Open does (from the + /// document's own bytes: no file is read or written), then go to `destination` in it. A + /// file that isn't attached there, or isn't a PDF, opens nothing. + pub(crate) fn open_embedded_link( + &mut self, + doc: DocId, + source: pdfcraft_render::AttachmentSource, + destination: pdfcraft_render::RemoteDestination, + ) { + let Some(d) = self.session.get(doc) else { return }; + let Some(att) = d.info.attachments.iter().find(|a| a.source == source).cloned() else { + self.notify_fmt("This PDF uses the unsupported {s} action.", &[("s", "GoToE")]); + return; + }; + let bytes = match pdfcraft_render::attachment_data(&d.bytes, d.password.as_deref(), &att) { + Ok(bytes) => bytes, + Err(e) => { + self.notify_fmt("Couldn't read {name}: {e}", &[("name", &att.name), ("e", &e.to_string())]); + return; + } + }; + // "Embedded go-to actions work only for files of Type PDF" (§12.6.4.4). Checked here, as + // the Attachments panel's Open would turn a picture or text file into a new PDF. + if !looks_like_pdf(&bytes) { + self.notify_fmt("{name} isn't a PDF, so the link can't open it.", &[("name", &att.name)]); + return; + } + if let Err(e) = self.open_bytes(&crate::files::attachment_file_name(&att.name), None, bytes) { + self.notify_fmt("Couldn't open {name}: {e}", &[("name", &att.name), ("e", &e.to_string())]); + return; + } + // An encrypted attachment waits for its password; the destination waits with it. + match self.password_prompt.as_mut() { + Some(prompt) => prompt.after_open = Some(destination), + None => self.apply_remote_destination(destination), + } + } + pub(super) fn apply_remote_destination(&mut self, destination: pdfcraft_render::RemoteDestination) { let Some(index) = self.views.len().checked_sub(1) else { return }; let Some(doc) = self.session.get(self.views[index].id) else { return }; @@ -123,3 +162,9 @@ impl PdfCraftApp { } } } + +/// Whether `bytes` are a PDF file: the `%PDF-` header (ISO 32000-2 §7.5.2) within their first +/// 1024 bytes. +fn looks_like_pdf(bytes: &[u8]) -> bool { + bytes.get(..bytes.len().min(1024)).is_some_and(|head| head.windows(5).any(|w| w == b"%PDF-")) +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 8b280ba75d..233bb55851 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1906,6 +1906,12 @@ fn link_hit(info: &DocInfo, xf: &PageXform, page: usize, p: Pos2) -> Option u.clone(), LinkTarget::SetLayers { .. } => tl!("Set layer visibility").to_string(), LinkTarget::RemoteGoTo { file, .. } => file.clone(), + // The attachment's name, as the Attachments panel lists it. + LinkTarget::EmbeddedGoTo { source, .. } => info + .attachments + .iter() + .find(|a| a.source == *source) + .map_or_else(|| crate::i18n::fmt(tl!("{s} action"), &[("s", "GoToE")]), |a| a.name.clone()), LinkTarget::Other(s) => crate::i18n::fmt(tl!("{s} action"), &[("s", s)]), }; let owner = crate::page_router::Owner::Link { index }; @@ -2774,13 +2780,9 @@ fn schedule_presentation_turn(ui: &egui::Ui, view: &mut DocView, click: Option, -) -> Option<(pdfcraft_engine::DocId, String, pdfcraft_render::RemoteDestination)> { +/// Follows the link that was clicked. A link to another file, or to a PDF attached to this one, +/// comes back, to be opened once the document is no longer borrowed. +fn follow_link(app: &mut PdfCraftApp, index: usize, target: Option) -> Option { let view_id = app.views[index].id; match target? { LinkTarget::Page(p, dest) => { @@ -2791,7 +2793,8 @@ fn follow_link( } LinkTarget::Uri(u) => app.request_document_url(&u, crate::LinkOrigin::Link), LinkTarget::SetLayers { changes, preserve_rb } => set_layers(app, index, &changes, preserve_rb), - LinkTarget::RemoteGoTo { file, destination, .. } => return Some((view_id, file, destination)), + LinkTarget::RemoteGoTo { file, destination, .. } => return Some(LinkOpen::Remote(view_id, file, destination)), + LinkTarget::EmbeddedGoTo { source, destination, .. } => return Some(LinkOpen::Embedded(view_id, source, destination)), LinkTarget::Other(s) => app.notify_fmt("This PDF uses the unsupported {s} action.", &[("s", &s)]), } None @@ -3320,7 +3323,7 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) { None => {} } schedule_presentation_turn(ui, view, present, clicked_link.is_some()); - let remote_open = follow_link(app, index, clicked_link); + let link_open = follow_link(app, index, clicked_link); if tool == QuickTool::Crop && cropped { tool = QuickTool::Select; } @@ -3338,7 +3341,7 @@ pub fn document_area(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui) { open_table, form_notice, copy_selected, - remote_open, + link_open, form, generation, avail, @@ -3359,7 +3362,7 @@ struct FrameRequests { open_table: Option<(usize, [f64; 4])>, form_notice: Option, copy_selected: bool, - remote_open: Option<(pdfcraft_engine::DocId, String, pdfcraft_render::RemoteDestination)>, + link_open: Option, form: Arc>, generation: u64, avail: Rect, @@ -3379,7 +3382,7 @@ fn apply_frame_requests(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui, open_table, form_notice, copy_selected, - remote_open, + link_open, form, generation, avail, @@ -3481,11 +3484,21 @@ fn apply_frame_requests(app: &mut PdfCraftApp, index: usize, ui: &mut egui::Ui, if app.mode != crate::Mode::Read && !app.full_screen { quick_bar(app, avail, ui); } - if let Some((source, file, destination)) = remote_open { - app.open_remote_link(source, file, destination); + match link_open { + Some(LinkOpen::Remote(source, file, destination)) => app.open_remote_link(source, file, destination), + Some(LinkOpen::Embedded(doc, source, destination)) => app.open_embedded_link(doc, source, destination), + None => {} } } +/// A clicked link that opens another document once the frame no longer borrows this one. +enum LinkOpen { + /// A GoToR or Launch link: the document it is in, the file, and where in it to go. + Remote(pdfcraft_engine::DocId, String, pdfcraft_render::RemoteDestination), + /// A GoToE link: the document it is in, its attachment, and where in it to go. + Embedded(pdfcraft_engine::DocId, pdfcraft_render::AttachmentSource, pdfcraft_render::RemoteDestination), +} + /// The prepare-mode field menu's choices. enum FieldMenu { Properties, diff --git a/crates/ui-egui/tests/it/embedded_links.rs b/crates/ui-egui/tests/it/embedded_links.rs new file mode 100644 index 0000000000..c289933fb0 --- /dev/null +++ b/crates/ui-egui/tests/it/embedded_links.rs @@ -0,0 +1,152 @@ +//! A link's embedded Go-To action (GoToE, ISO 32000-2 §12.6.4.4) opens the PDF attached to the +//! document in a new tab, as the Attachments panel's Open does, and goes to its destination. + +use egui_kittest::Harness; +use pdfcraft_ui_egui::PdfCraftApp; + +/// A PDF of `objs` (object 1 the catalog), with a cross-reference table. +fn write_pdf(objs: &[Vec]) -> Vec { + let mut out = b"%PDF-1.7\n".to_vec(); + let mut offs = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offs.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes()); + out.extend_from_slice(o); + out.extend_from_slice(b"\nendobj\n"); + } + let x = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for o in offs { + out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{x}\n%%EOF\n", objs.len() + 1).as_bytes()); + out +} + +fn stream(dict: &str, data: &[u8]) -> Vec { + let mut s = format!("<< {dict} /Length {} >>\nstream\n", data.len()).into_bytes(); + s.extend_from_slice(data); + s.extend_from_slice(b"\nendstream"); + s +} + +/// A three-page PDF to embed. +fn inner() -> Vec { + write_pdf(&[ + b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 /MediaBox [0 0 200 300] >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R >>".to_vec(), + ]) +} + +/// Link rows, by the y (PDF user space, 300 × 400 page) of their middle. +const TO_PAGE_3: f32 = 375.0; +const PARENT: f32 = 325.0; +const MISSING: f32 = 275.0; +const NOT_A_PDF: f32 = 225.0; +const BY_ANNOTATION: f32 = 175.0; + +/// One page with `inner.pdf` and `notes.txt` in the EmbeddedFiles name tree, a file attachment +/// annotation (index 0, `/NM (att-1)`) holding `inner.pdf` too, and a GoToE link per case. +fn fixture() -> Vec { + let links = [ + (TO_PAGE_3, "<< /S /GoToE /T << /R /C /N (inner.pdf) >> /D [2 /Fit] /NewWindow true >>"), + (PARENT, "<< /S /GoToE /T << /R /P >> /D [0 /Fit] >>"), + (MISSING, "<< /S /GoToE /T << /R /C /N (missing.pdf) >> /D [0 /Fit] >>"), + (NOT_A_PDF, "<< /S /GoToE /T << /R /C /N (notes.txt) >> /D [0 /Fit] >>"), + (BY_ANNOTATION, "<< /S /GoToE /T << /R /C /P 0 /A (att-1) >> /D [1 /Fit] >>"), + ]; + let first_link = 9; + let annots: Vec = std::iter::once("8 0 R".to_string()).chain((0..links.len()).map(|k| format!("{} 0 R", first_link + k))).collect(); + let mut objs = vec![ + b"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles << /Names [(inner.pdf) 6 0 R (notes.txt) 7 0 R] >> >> >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >>".to_vec(), + format!("<< /Type /Page /Parent 2 0 R /Annots [{}] >>", annots.join(" ")).into_bytes(), + stream("/Type /EmbeddedFile /Subtype /application#2Fpdf", &inner()), + stream("/Type /EmbeddedFile /Subtype /text#2Fplain", b"just some notes"), + b"<< /Type /Filespec /F (inner.pdf) /UF (inner.pdf) /EF << /F 4 0 R >> >>".to_vec(), + b"<< /Type /Filespec /F (notes.txt) /UF (notes.txt) /EF << /F 5 0 R >> >>".to_vec(), + b"<< /Type /Annot /Subtype /FileAttachment /Rect [270 10 290 30] /NM (att-1) /FS << /Type /Filespec /F (inner.pdf) /UF (inner.pdf) /EF << /F 4 0 R >> >> >>".to_vec(), + ]; + objs.extend( + links + .iter() + .map(|(y, a)| format!("<< /Type /Annot /Subtype /Link /Rect [20 {} 280 {}] /Border [0 0 0] /A {a} >>", y - 10.0, y + 10.0).into_bytes()), + ); + write_pdf(&objs) +} + +fn harness() -> Harness<'static, PdfCraftApp> { + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| { + let mut app = PdfCraftApp::new(); + app.set_option("language", "en").unwrap(); + app.open_bytes("outer.pdf", None, fixture()).unwrap(); + app.set_option("left", "closed").unwrap(); + app.set_option("panel", "none").unwrap(); + app.set_option("zoom", "100").unwrap(); + app + }); + h.run_steps(8); + h +} + +/// Click the link at height `y` on page 1 of the first tab. +fn click(h: &mut Harness<'static, PdfCraftApp>, y: f32) { + let r = h.state().views[0].page_screen_rect(0).expect("page 1 on screen"); + let k = r.width() / 300.0; + let p = r.min + egui::vec2(150.0 * k, (400.0 - y) * k); + h.hover_at(p); + h.run_steps(1); + h.drag_at(p); + h.run_steps(1); + h.drop_at(p); + h.run_steps(4); +} + +fn toast(h: &Harness<'static, PdfCraftApp>) -> Option { + h.state().toast.clone().map(|t| t.0) +} + +fn tab_name(h: &Harness<'static, PdfCraftApp>, i: usize) -> Option { + let s = h.state(); + s.views.get(i).and_then(|v| s.session.get(v.id)).map(|d| d.name.clone()) +} + +/// `/R /C /N`: the file in the EmbeddedFiles name tree opens in a new tab at `/D`. +#[test] +fn an_embedded_go_to_link_opens_the_attached_pdf_at_its_destination() { + let mut h = harness(); + click(&mut h, TO_PAGE_3); + assert_eq!(h.state().views.len(), 2, "{:?}", toast(&h)); + assert_eq!(h.state().active, Some(1)); + assert_eq!(tab_name(&h, 1).as_deref(), Some("inner.pdf")); + assert_eq!(h.state().session.get(h.state().views[1].id).unwrap().info.pages.len(), 3); + assert_eq!(h.state().views[1].current, 2, "the destination's page"); + assert_eq!(h.state().session.get(h.state().views[1].id).unwrap().path, None, "opened from the document, not from a file"); +} + +/// `/R /C /P /A`: the file of a file attachment annotation, found by its `/NM`. +#[test] +fn an_embedded_go_to_link_opens_a_file_attachment_annotations_pdf() { + let mut h = harness(); + click(&mut h, BY_ANNOTATION); + assert_eq!(h.state().views.len(), 2, "{:?}", toast(&h)); + assert_eq!(h.state().views[1].current, 1); +} + +/// The parent, a file that isn't attached, and a file that isn't a PDF open nothing and say so. +#[test] +fn embedded_go_to_links_that_cannot_be_followed_open_nothing() { + for (y, says) in [ + (PARENT, "This PDF uses the unsupported GoToE action."), + (MISSING, "This PDF uses the unsupported GoToE action."), + (NOT_A_PDF, "notes.txt isn't a PDF, so the link can't open it."), + ] { + let mut h = harness(); + click(&mut h, y); + assert_eq!(h.state().views.len(), 1, "nothing opened for the link at {y}"); + assert_eq!(toast(&h).as_deref(), Some(says)); + } +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index a5c3192358..5da75687cf 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -41,6 +41,7 @@ mod dialog_chrome; mod document_links; mod editing; mod editor_taps; +mod embedded_links; mod export; mod fill_sign; mod folders; diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 0b6f658dd6..468c2b3d12 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -1190,8 +1190,8 @@ milestone = "M3" status = "shipped" commands = [] tools = ["link_open"] -evidence = ["crates/ui-egui/tests/it/view.rs::clicking_a_link_goes_to_its_destination", "crates/ui-egui/tests/it/view.rs::link_destinations_scroll_to_their_position", "crates/ui-egui/tests/it/view.rs::a_link_without_a_position_keeps_the_place_on_the_next_page", "crates/ui-egui/src/canvas/tests.rs::a_null_xyz_coordinate_keeps_the_readers_place_on_the_new_page", "crates/render/src/inspect/tests.rs::bookmarks_and_links_keep_their_destination_view", "crates/render/src/inspect/tests.rs::links_read_bounded_local_remote_go_to_actions", "crates/automation/tests/it/automation.rs::local_gotor_link_open_applies_destinations_and_honors_root", "crates/ui-egui/tests/it/document_links.rs::a_local_gotor_link_opens_in_a_tab_and_applies_its_destination", "crates/ui-egui/tests/it/document_links.rs::an_absolute_gotor_waits_for_consent_and_keeps_its_destination_across_tabs", "crates/ui-egui/tests/it/document_links.rs::cancelling_an_absolute_gotor_by_button_escape_or_dismissal_changes_nothing", "crates/automation/tests/it/automation.rs::absolute_gotor_consent_does_not_bypass_validation_or_passwords", "crates/render/src/inspect/tests.rs::launch_actions_that_name_a_pdf_open_it_like_a_remote_link", "crates/automation/tests/it/automation.rs::a_launch_link_to_a_pdf_opens_it_like_a_remote_link"] -notes = "GoTo and URI links plus local-PDF GoToR links: source-relative or local absolute /F paths, /UF preferred in file-spec dictionaries, explicit numeric page/view destinations, and internal tabs. Absolute local GoToR targets require desktop Allow/Cancel confirmation or an explicit allow_absolute opt-in in link_open; relative links open normally. link_open honors --root. Named remote destinations open at default view with a warning; /NewWindow is a tab hint. A Launch action whose /F names a .pdf file (and has no /Win launch parameters) opens that PDF the same way, backslash separators read as / (#4168); URL/network file systems, GoToE, other Launch actions and other actions are not executed. Same-document destinations retain their supported /XYZ, /Fit, /FitH, /FitV and /FitR views; /FitB* is read as whole-page fit. A null /XYZ left or top keeps the reader's place, as ISO 32000-2 §12.3.2.2 says and Acrobat Reader was observed to do (synthetic fixture): the user-space point at the window's top-left stays there on the target page at the same zoom, along each axis the page overflows; CAD exports (WSCAD) write every cross-reference this way. Null /FitH top and /FitV left still go to the page edge." +evidence = ["crates/ui-egui/tests/it/view.rs::clicking_a_link_goes_to_its_destination", "crates/ui-egui/tests/it/view.rs::link_destinations_scroll_to_their_position", "crates/ui-egui/tests/it/view.rs::a_link_without_a_position_keeps_the_place_on_the_next_page", "crates/ui-egui/src/canvas/tests.rs::a_null_xyz_coordinate_keeps_the_readers_place_on_the_new_page", "crates/render/src/inspect/tests.rs::bookmarks_and_links_keep_their_destination_view", "crates/render/src/inspect/tests.rs::links_read_bounded_local_remote_go_to_actions", "crates/automation/tests/it/automation.rs::local_gotor_link_open_applies_destinations_and_honors_root", "crates/ui-egui/tests/it/document_links.rs::a_local_gotor_link_opens_in_a_tab_and_applies_its_destination", "crates/ui-egui/tests/it/document_links.rs::an_absolute_gotor_waits_for_consent_and_keeps_its_destination_across_tabs", "crates/ui-egui/tests/it/document_links.rs::cancelling_an_absolute_gotor_by_button_escape_or_dismissal_changes_nothing", "crates/automation/tests/it/automation.rs::absolute_gotor_consent_does_not_bypass_validation_or_passwords", "crates/render/src/inspect/tests.rs::launch_actions_that_name_a_pdf_open_it_like_a_remote_link", "crates/automation/tests/it/automation.rs::a_launch_link_to_a_pdf_opens_it_like_a_remote_link", "crates/render/src/inspect/tests.rs::links_read_embedded_go_to_actions_to_attached_pdfs", "crates/ui-egui/tests/it/embedded_links.rs::an_embedded_go_to_link_opens_the_attached_pdf_at_its_destination", "crates/ui-egui/tests/it/embedded_links.rs::an_embedded_go_to_link_opens_a_file_attachment_annotations_pdf", "crates/ui-egui/tests/it/embedded_links.rs::embedded_go_to_links_that_cannot_be_followed_open_nothing", "crates/automation/tests/it/automation.rs::an_embedded_go_to_link_opens_the_attached_pdf"] +notes = "GoTo and URI links plus local-PDF GoToR links: source-relative or local absolute /F paths, /UF preferred in file-spec dictionaries, explicit numeric page/view destinations, and internal tabs. Absolute local GoToR targets require desktop Allow/Cancel confirmation or an explicit allow_absolute opt-in in link_open; relative links open normally. link_open honors --root. Named remote destinations open at default view with a warning; /NewWindow is a tab hint. A Launch action whose /F names a .pdf file (and has no /Win launch parameters) opens that PDF the same way, backslash separators read as / (#4168); A GoToE link (ISO 32000-2 §12.6.4.4) to a PDF embedded in the document (a child target, /R /C, by its EmbeddedFiles /N key or its file attachment annotation /P and /A, index or /NM) opens it in a new tab from the document's own bytes, as the Attachments panel does, at its page destination (named destinations open at the default view with a warning); link_open does the same headlessly. GoToE to the parent (/R /P), through nested target dictionaries, under another root document (/F), to a file that isn't attached or to a non-PDF attachment is not followed, with a notice. URL/network file systems, other Launch actions and other actions are not executed. Same-document destinations retain their supported /XYZ, /Fit, /FitH, /FitV and /FitR views; /FitB* is read as whole-page fit. A null /XYZ left or top keeps the reader's place, as ISO 32000-2 §12.3.2.2 says and Acrobat Reader was observed to do (synthetic fixture): the user-space point at the window's top-left stays there on the target page at the same zoom, along each axis the page overflows; CAD exports (WSCAD) write every cross-reference this way. Null /FitH top and /FitV left still go to the page edge." [[feature]] id = "view.annotation-hover" From a02bf747fd12243a7611c1196e6e5a46c6eedca2 Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Sat, 31 Oct 2026 16:14:59 +0800 Subject: [PATCH 08/30] M3: GoToE targets look up /NM once per page, and one %PDF- check serves both callers - A GoToE target naming its file attachment annotation by /NM scanned the page's /Annots for every link: O(links x annotations). The inspector now builds each page's /NM index once, on first use, keeping the first annotation with a repeated name as the scan did. - The UI and link_open each had their own "%PDF- within the first 1024 bytes" check (ISO 32000-2 7.5.2; GoToE opens only PDFs, 12.6.4.4). pdfcraft_render::looks_like_pdf, next to attachment_data, is now the one both call, so they cannot disagree. Test: embedded_go_to_links_by_annotation_name_read_the_page_once (400 named attachments, 400 GoToE links) stays under 16,000 object reads; with the per-link scan restored it reads 83,410. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Pq7HyCfwzyRXj4VfQAVVdv --- crates/automation/src/links.rs | 2 +- crates/render/src/inspect.rs | 2 +- crates/render/src/inspect/annotations.rs | 24 ++++++++++---- crates/render/src/inspect/core.rs | 8 ++++- crates/render/src/inspect/resources.rs | 7 ++++ crates/render/src/inspect/tests.rs | 41 ++++++++++++++++++++++++ crates/render/src/lib.rs | 3 +- crates/ui-egui/src/app/links.rs | 8 +---- 8 files changed, 77 insertions(+), 18 deletions(-) diff --git a/crates/automation/src/links.rs b/crates/automation/src/links.rs index 65124bd12d..c8d83a7236 100644 --- a/crates/automation/src/links.rs +++ b/crates/automation/src/links.rs @@ -179,7 +179,7 @@ impl Automation { (att.name.clone(), bytes) }; // "Embedded go-to actions work only for files of Type PDF" (§12.6.4.4). - if !bytes.get(..bytes.len().min(1024)).is_some_and(|head| head.windows(5).any(|w| w == b"%PDF-")) { + if !pdfcraft_render::looks_like_pdf(&bytes) { return Err(failed(format!("{name} is not a PDF, so the GoToE link can't open it"))); } let id = self.session.open(name.clone(), None, std::sync::Arc::new(bytes), a.opt_str("password")?).map_err(failed)?; diff --git a/crates/render/src/inspect.rs b/crates/render/src/inspect.rs index 0cf287b3f1..8807fdbdc7 100644 --- a/crates/render/src/inspect.rs +++ b/crates/render/src/inspect.rs @@ -41,7 +41,7 @@ pub use model::{ }; #[cfg(test)] use navigation::{OUTLINE_DEPTH, OUTLINE_WINDOW}; -pub use resources::attachment_data; +pub use resources::{attachment_data, looks_like_pdf}; #[cfg(test)] use resources::{xfa_config_dynamic_render, xfa_packet_text}; diff --git a/crates/render/src/inspect/annotations.rs b/crates/render/src/inspect/annotations.rs index dace729e3d..394d637687 100644 --- a/crates/render/src/inspect/annotations.rs +++ b/crates/render/src/inspect/annotations.rs @@ -1,7 +1,7 @@ use super::core::{limited_pdf_string, pretty_date, spend}; use super::model::{Annotation, AttachmentSource, DestView, Field, FieldKind, LayerOp, Link, LinkTarget, RemoteDestination, link_replies}; use super::navigation::text_string; -use super::{Dictionary, DocInfo, Entry, HashMap, HashSet, Inspector, Object, ObjectId}; +use super::{Dictionary, DocInfo, Entry, HashMap, HashSet, Inspector, Object, ObjectId, OnceCell}; /// At most this many `/State` entries of a set-layer-visibility action are read. const MAX_LAYER_STATE: usize = 1024; @@ -299,12 +299,22 @@ impl<'a> Inspector<'a> { /// The position in page `page`'s `/Annots` of the first annotation whose `/NM` is `nm`. fn annotation_named(&self, page: usize, nm: &[u8]) -> Option { - let id = *self.page_ids.get(page)?; - let page = self.doc.get_dictionary(id).ok()?; - let Object::Array(annots) = self.resolve(page.get(b"Annots").ok()?) else { return None }; - annots.iter().position(|a| { - self.dict(a).and_then(|d| d.get(b"NM").ok()).is_some_and(|n| matches!(self.resolve(n), Object::String(b, _) if b.as_slice() == nm)) - }) + let pages = self.annotation_names.get_or_init(|| self.page_ids.iter().map(|_| OnceCell::new()).collect()); + pages.get(page)?.get_or_init(|| self.annotation_names_on(page)).get(nm).copied() + } + + /// Each `/NM` on page `page`, with the position in its `/Annots` of the first annotation + /// that has it. + fn annotation_names_on(&self, page: usize) -> super::core::AnnotationNames { + let mut names = HashMap::new(); + let Some(page) = self.page_ids.get(page).and_then(|id| self.doc.get_dictionary(*id).ok()) else { return names }; + let Some(Object::Array(annots)) = page.get(b"Annots").ok().map(|a| self.resolve(a)) else { return names }; + for (i, a) in annots.iter().enumerate() { + if let Some(Object::String(nm, _)) = self.dict(a).and_then(|d| d.get(b"NM").ok()).map(|n| self.resolve(n)) { + names.entry(nm.clone()).or_insert(i); + } + } + names } /// The non-empty local file an action's `/F` names (a string or a file specification), shared diff --git a/crates/render/src/inspect/core.rs b/crates/render/src/inspect/core.rs index c190dc565b..d7c1145528 100644 --- a/crates/render/src/inspect/core.rs +++ b/crates/render/src/inspect/core.rs @@ -133,6 +133,9 @@ pub(super) fn inspect_structure(info: &mut DocInfo, fill: impl FnOnce(&mut DocIn } } +/// One page's annotations by `/NM`: the position in `/Annots` of the first one with each name. +pub(super) type AnnotationNames = HashMap, usize>; + pub(super) struct Inspector<'a> { pub(super) doc: &'a dyn Structure, pub(super) page_ids: Vec, @@ -144,13 +147,16 @@ pub(super) struct Inspector<'a> { /// has no `/P`. Searching every page's `/Annots` for each such field was O(fields × /// annotations): a second on a form of 8,000 fields. pub(super) annotation_pages: OnceCell>, + /// Per page, the position in `/Annots` of the first annotation with each `/NM`, built when a + /// GoToE target names one. Scanning `/Annots` for each link was O(links × annotations). + pub(super) annotation_names: OnceCell>>, } impl<'a> Inspector<'a> { pub(super) fn new(doc: &'a dyn Structure) -> Self { let page_ids = doc.page_ids(); let page_index = page_ids.iter().copied().enumerate().map(|(index, id)| (id, index)).collect(); - let mut me = Self { doc, page_ids, page_index, named: HashMap::new(), annotation_pages: OnceCell::new() }; + let mut me = Self { doc, page_ids, page_index, named: HashMap::new(), annotation_pages: OnceCell::new(), annotation_names: OnceCell::new() }; let mut named = HashMap::new(); if let Some(tree) = doc.catalog().ok().and_then(|c| c.get(b"Names").ok()).and_then(|o| me.dict(o)).and_then(|n| n.get(b"Dests").ok()).and_then(|o| me.dict(o)) diff --git a/crates/render/src/inspect/resources.rs b/crates/render/src/inspect/resources.rs index 0895c64f8a..39a20b691c 100644 --- a/crates/render/src/inspect/resources.rs +++ b/crates/render/src/inspect/resources.rs @@ -231,6 +231,13 @@ impl<'a> Inspector<'a> { } } +/// Whether `bytes` (an attachment's, from [`attachment_data`]) are a PDF file: the `%PDF-` +/// header (ISO 32000-2 §7.5.2) within their first 1024 bytes. Embedded go-to actions open only +/// these (§12.6.4.4). +pub fn looks_like_pdf(bytes: &[u8]) -> bool { + bytes.get(..bytes.len().min(1024)).is_some_and(|head| head.windows(5).any(|w| w == b"%PDF-")) +} + /// Fetch an attachment's bytes (decoded). Capped at 1 GiB to defuse decompression bombs. pub fn attachment_data(bytes: &[u8], password: Option<&str>, att: &Attachment) -> Result, String> { let run = || -> Result, String> { diff --git a/crates/render/src/inspect/tests.rs b/crates/render/src/inspect/tests.rs index ef97f77a57..d3da02548b 100644 --- a/crates/render/src/inspect/tests.rs +++ b/crates/render/src/inspect/tests.rs @@ -1310,6 +1310,47 @@ fn links_read_embedded_go_to_actions_to_attached_pdfs() { ); } +/// Many GoToE links naming a file attachment annotation by `/NM` read the page's annotations +/// once, not once per link, and a repeated `/NM` is the first annotation that has it. +#[test] +fn embedded_go_to_links_by_annotation_name_read_the_page_once() { + const N: usize = 400; + let att = |k: usize| 10 + k; + let link = |k: usize| 10 + N + k; + let mut pdf = + String::from("%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n"); + let annots: Vec = (0..N).map(att).chain((0..N).map(link)).map(|o| format!("{o} 0 R")).collect(); + pdf += &format!("3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Annots [{}] >> endobj\n", annots.join(" ")); + for k in 0..N { + // The last two attachments share a name: the first of them is the one named. + let name = if k == N - 1 { N - 2 } else { k }; + pdf += &format!("{} 0 obj << /Type /Annot /Subtype /FileAttachment /Rect [0 0 1 1] /NM (a{name}) >> endobj\n", att(k)); + } + for k in 0..N { + pdf += + &format!("{} 0 obj << /Type /Annot /Subtype /Link /Rect [0 0 1 1] /A << /S /GoToE /T << /R /C /P 0 /A (a{k}) >> >> >> endobj\n", link(k)); + } + pdf += "trailer << /Root 1 0 R >>\n%%EOF"; + let doc = Document::load_mem(pdf.as_bytes()).expect("loads"); + let counting = CountingReads { doc: &doc, reads: std::cell::Cell::new(0) }; + let page = PageInfo { width: 200.0, height: 200.0, crop: [0.0, 0.0, 200.0, 200.0], rotation: 0, label: String::new() }; + let mut info = DocInfo { pages: vec![page], ..Default::default() }; + Inspector::new(&counting).fill(&mut info); + let indexes: Vec> = info + .links + .iter() + .map(|l| match &l.target { + LinkTarget::EmbeddedGoTo { source: AttachmentSource::Annotation { page: 0, index }, .. } => Some(*index), + _ => None, + }) + .collect(); + let want: Vec> = (0..N).map(|k| (k < N - 1).then_some(k)).collect(); + assert_eq!(indexes, want); + // A handful of reads per annotation; scanning `/Annots` for each link read about 80,000. + let reads = counting.reads.get(); + assert!(reads < 20 * 2 * N, "{reads} object reads"); +} + #[test] fn links_read_bounded_local_remote_go_to_actions() { use DestView::{Fit, Xyz}; diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 6f9a3ac319..9bba9e4f9c 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -19,7 +19,8 @@ pub mod transition; pub use inspect::{ Annotation, Attachment, AttachmentSource, DestView, DocInfo, Field, FieldKind, FontInfo, Layer, LayerOp, Link, LinkTarget, OutlineItem, PageInfo, - PageTransition, RemoteDestination, TransitionStyle, Xfa, attachment_data, check_pages, inspect, link_replies, pretty_date, thread_tops, + PageTransition, RemoteDestination, TransitionStyle, Xfa, attachment_data, check_pages, inspect, link_replies, looks_like_pdf, pretty_date, + thread_tops, }; pub use pixels::Pixels; pub use raster::{ diff --git a/crates/ui-egui/src/app/links.rs b/crates/ui-egui/src/app/links.rs index 139d1db85e..c1da5fb441 100644 --- a/crates/ui-egui/src/app/links.rs +++ b/crates/ui-egui/src/app/links.rs @@ -89,7 +89,7 @@ impl PdfCraftApp { }; // "Embedded go-to actions work only for files of Type PDF" (§12.6.4.4). Checked here, as // the Attachments panel's Open would turn a picture or text file into a new PDF. - if !looks_like_pdf(&bytes) { + if !pdfcraft_render::looks_like_pdf(&bytes) { self.notify_fmt("{name} isn't a PDF, so the link can't open it.", &[("name", &att.name)]); return; } @@ -162,9 +162,3 @@ impl PdfCraftApp { } } } - -/// Whether `bytes` are a PDF file: the `%PDF-` header (ISO 32000-2 §7.5.2) within their first -/// 1024 bytes. -fn looks_like_pdf(bytes: &[u8]) -> bool { - bytes.get(..bytes.len().min(1024)).is_some_and(|head| head.windows(5).any(|w| w == b"%PDF-")) -} From 3ab3dde44892a5cb0d5dd48b15600643b87f6678 Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Sat, 31 Oct 2026 16:39:30 +0800 Subject: [PATCH 09/30] M3: the GoToE /NM indexes share a byte budget, and a long /NM is scanned for Each page's /NM index copied every name it held. One /Annots array or one long name that many pages share was copied and hashed again for every page a GoToE target named, with no limit. Names over 1 KiB are no longer indexed: a target naming one is found by scanning the page. All the indexes together spend at most 16 MiB of name bytes (with a slot per entry); a page that does not fit what is left keeps no index and is scanned for each name instead. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Pq7HyCfwzyRXj4VfQAVVdv --- crates/render/src/inspect/annotations.rs | 56 +++++++++++++++--- crates/render/src/inspect/core.rs | 21 +++++-- crates/render/src/inspect/tests.rs | 72 ++++++++++++++++++++++++ 3 files changed, 136 insertions(+), 13 deletions(-) diff --git a/crates/render/src/inspect/annotations.rs b/crates/render/src/inspect/annotations.rs index 394d637687..39ac45ab0f 100644 --- a/crates/render/src/inspect/annotations.rs +++ b/crates/render/src/inspect/annotations.rs @@ -22,6 +22,14 @@ pub(super) const MAX_ANNOTATION_BYTES: usize = 64 << 20; /// key does not fit is not listed. pub(super) const MAX_LINK_ATTACHMENT_TEXT_BYTES: usize = 16 << 20; +/// `/NM` bytes, with a slot per entry, that the per-page annotation-name indexes for GoToE targets +/// hash in all. One `/Annots` array or one long name many pages share would otherwise be hashed +/// again for each page; past it a page is scanned for each name instead. +pub(super) const MAX_ANNOTATION_NAME_INDEX_BYTES: usize = 16 << 20; + +/// A longer `/NM` is not indexed: it is scanned for. Real names are short identifiers. +const MAX_INDEXED_ANNOTATION_NAME_BYTES: usize = 1024; + /// The bytes a listed annotation keeps. pub(super) fn retained(a: &Annotation) -> usize { let text = [&a.author, &a.contents, &a.modified, &a.name, &a.in_reply_to, &a.state, &a.intent]; @@ -300,21 +308,51 @@ impl<'a> Inspector<'a> { /// The position in page `page`'s `/Annots` of the first annotation whose `/NM` is `nm`. fn annotation_named(&self, page: usize, nm: &[u8]) -> Option { let pages = self.annotation_names.get_or_init(|| self.page_ids.iter().map(|_| OnceCell::new()).collect()); - pages.get(page)?.get_or_init(|| self.annotation_names_on(page)).get(nm).copied() + let names = pages.get(page)?.get_or_init(|| self.annotation_names_on(page)); + match names { + // A name longer than an indexed one is not in the index: scanned for. + Some(names) if nm.len() <= MAX_INDEXED_ANNOTATION_NAME_BYTES => names.get(nm).copied(), + _ => self.annotations_on(page)?.iter().position(|a| self.annotation_name(a) == Some(nm)), + } } - /// Each `/NM` on page `page`, with the position in its `/Annots` of the first annotation - /// that has it. + /// Each `/NM` on page `page` up to [`MAX_INDEXED_ANNOTATION_NAME_BYTES`] long, with the + /// position in its `/Annots` of the first annotation that has it, spent from + /// `annotation_name_budget`. `None` once the budget does not cover the page. fn annotation_names_on(&self, page: usize) -> super::core::AnnotationNames { let mut names = HashMap::new(); - let Some(page) = self.page_ids.get(page).and_then(|id| self.doc.get_dictionary(*id).ok()) else { return names }; - let Some(Object::Array(annots)) = page.get(b"Annots").ok().map(|a| self.resolve(a)) else { return names }; + let Some(annots) = self.annotations_on(page) else { return Some(names) }; + let mut budget = self.annotation_name_budget.get(); for (i, a) in annots.iter().enumerate() { - if let Some(Object::String(nm, _)) = self.dict(a).and_then(|d| d.get(b"NM").ok()).map(|n| self.resolve(n)) { - names.entry(nm.clone()).or_insert(i); - } + let Some(nm) = self.annotation_name(a).filter(|nm| nm.len() <= MAX_INDEXED_ANNOTATION_NAME_BYTES) else { continue }; + // Each entry costs its name and its slot, so many short names are bounded too. + let Some(left) = budget.checked_sub(nm.len().saturating_add(std::mem::size_of::<(Vec, usize)>())) else { + // What the page used so far is spent; nothing of it is kept. + self.annotation_name_budget.set(budget); + return None; + }; + budget = left; + names.entry(nm.to_vec()).or_insert(i); + } + self.annotation_name_budget.set(budget); + Some(names) + } + + /// Page `page`'s `/Annots`. + fn annotations_on(&self, page: usize) -> Option<&'a [Object]> { + let page = self.doc.get_dictionary(*self.page_ids.get(page)?).ok()?; + match self.resolve(page.get(b"Annots").ok()?) { + Object::Array(annots) => Some(annots), + _ => None, + } + } + + /// An annotation's `/NM` string bytes. + fn annotation_name(&self, a: &'a Object) -> Option<&'a [u8]> { + match self.resolve(self.dict(a)?.get(b"NM").ok()?) { + Object::String(nm, _) => Some(nm), + _ => None, } - names } /// The non-empty local file an action's `/F` names (a string or a file specification), shared diff --git a/crates/render/src/inspect/core.rs b/crates/render/src/inspect/core.rs index d7c1145528..bf69c19a04 100644 --- a/crates/render/src/inspect/core.rs +++ b/crates/render/src/inspect/core.rs @@ -1,10 +1,11 @@ -use super::annotations::MAX_LINK_ATTACHMENT_TEXT_BYTES; +use super::annotations::{MAX_ANNOTATION_NAME_INDEX_BYTES, MAX_LINK_ATTACHMENT_TEXT_BYTES}; use super::model::{AttachmentSource, PageInfo, Xfa}; use super::navigation::text_string; use super::{ Arc, AssertUnwindSafe, DecryptionError, Dictionary, DocInfo, Document, HashMap, HashSet, LazyStructure, LoadOptions, LoadPdfError, Object, ObjectId, OnceCell, OpenError, Pdf, Structure, catch_unwind, }; +use std::cell::Cell; /// lopdf decodes object and cross-reference streams while it loads, with no limit unless one is /// set: a few hundred bytes of nested FlateDecode then inflate to gigabytes. Real object and @@ -133,8 +134,10 @@ pub(super) fn inspect_structure(info: &mut DocInfo, fill: impl FnOnce(&mut DocIn } } -/// One page's annotations by `/NM`: the position in `/Annots` of the first one with each name. -pub(super) type AnnotationNames = HashMap, usize>; +/// The names are copies (borrowing them would make `Inspector` invariant in its lifetime), each +/// short, and all of them within [`MAX_ANNOTATION_NAME_INDEX_BYTES`]. `None` when the page's names +/// did not fit what was left of it: that page is scanned for each name instead. +pub(super) type AnnotationNames = Option, usize>>; pub(super) struct Inspector<'a> { pub(super) doc: &'a dyn Structure, @@ -150,13 +153,23 @@ pub(super) struct Inspector<'a> { /// Per page, the position in `/Annots` of the first annotation with each `/NM`, built when a /// GoToE target names one. Scanning `/Annots` for each link was O(links × annotations). pub(super) annotation_names: OnceCell>>, + /// What is left of [`MAX_ANNOTATION_NAME_INDEX_BYTES`] for `annotation_names`. + pub(super) annotation_name_budget: Cell, } impl<'a> Inspector<'a> { pub(super) fn new(doc: &'a dyn Structure) -> Self { let page_ids = doc.page_ids(); let page_index = page_ids.iter().copied().enumerate().map(|(index, id)| (id, index)).collect(); - let mut me = Self { doc, page_ids, page_index, named: HashMap::new(), annotation_pages: OnceCell::new(), annotation_names: OnceCell::new() }; + let mut me = Self { + doc, + page_ids, + page_index, + named: HashMap::new(), + annotation_pages: OnceCell::new(), + annotation_names: OnceCell::new(), + annotation_name_budget: Cell::new(MAX_ANNOTATION_NAME_INDEX_BYTES), + }; let mut named = HashMap::new(); if let Some(tree) = doc.catalog().ok().and_then(|c| c.get(b"Names").ok()).and_then(|o| me.dict(o)).and_then(|n| n.get(b"Dests").ok()).and_then(|o| me.dict(o)) diff --git a/crates/render/src/inspect/tests.rs b/crates/render/src/inspect/tests.rs index d3da02548b..a2fd612018 100644 --- a/crates/render/src/inspect/tests.rs +++ b/crates/render/src/inspect/tests.rs @@ -1351,6 +1351,78 @@ fn embedded_go_to_links_by_annotation_name_read_the_page_once() { assert!(reads < 20 * 2 * N, "{reads} object reads"); } +/// The `/NM` indexes for GoToE targets stay within `MAX_ANNOTATION_NAME_INDEX_BYTES` when many +/// pages share one `/Annots` array holding one very long name and many short ones, and every +/// target still resolves: the long name and the pages past the budget are scanned instead. +#[test] +fn embedded_go_to_annotation_name_indexes_share_a_byte_budget() { + use super::annotations::MAX_ANNOTATION_NAME_INDEX_BYTES; + const PAGES: usize = 32; + const SHORT: usize = 1100; + let page = |k: usize| 100 + k; + let short = |j: usize| 1000 + j; + let link = |k: usize, which: usize| 10_000 + 2 * k + which; + let links_page = page(PAGES); + let kids: Vec = (0..=PAGES).map(|k| format!("{} 0 R", page(k))).collect(); + let mut pdf = format!( + "%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Kids [{}] /Count {} >> endobj\n", + kids.join(" "), + PAGES + 1 + ); + let shared: Vec = std::iter::once(6).chain((0..SHORT).map(short)).map(|o| format!("{o} 0 R")).collect(); + pdf += &format!("4 0 obj [{}] endobj\n", shared.join(" ")); + // One name of a mebibyte, which every page's index would otherwise hash. + pdf += &format!("7 0 obj ({}) endobj\n", "x".repeat(1 << 20)); + pdf += "6 0 obj << /Type /Annot /Subtype /FileAttachment /Rect [0 0 1 1] /NM 7 0 R >> endobj\n"; + for j in 0..SHORT { + pdf += &format!("{} 0 obj << /Type /Annot /Subtype /FileAttachment /Rect [0 0 1 1] /NM (n{j:0>999}) >> endobj\n", short(j)); + } + for k in 0..PAGES { + pdf += &format!("{} 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Annots 4 0 R >> endobj\n", page(k)); + } + let links: Vec = (0..PAGES).flat_map(|k| [link(k, 0), link(k, 1)]).map(|o| format!("{o} 0 R")).collect(); + pdf += &format!("{links_page} 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Annots [{}] >> endobj\n", links.join(" ")); + let target = |k: usize| (k * 37) % SHORT; + for k in 0..PAGES { + let action = |a: String| format!("<< /S /GoToE /T << /R /C /P {k} /A {a} >> /D [0 /Fit] >>"); + pdf += &format!("{} 0 obj << /Type /Annot /Subtype /Link /Rect [0 0 1 1] /A {} >> endobj\n", link(k, 0), action("7 0 R".into())); + pdf += &format!( + "{} 0 obj << /Type /Annot /Subtype /Link /Rect [0 0 1 1] /A {} >> endobj\n", + link(k, 1), + action(format!("(n{:0>999})", target(k))) + ); + } + pdf += "trailer << /Root 1 0 R >>\n%%EOF"; + let doc = Document::load_mem(pdf.as_bytes()).expect("loads"); + let blank = PageInfo { width: 200.0, height: 200.0, crop: [0.0, 0.0, 200.0, 200.0], rotation: 0, label: String::new() }; + let mut info = DocInfo { pages: vec![blank; PAGES + 1], ..Default::default() }; + let inspector = Inspector::new(&doc); + inspector.fill(&mut info); + let indexes: Vec<(usize, usize)> = info + .links + .iter() + .filter_map(|l| match &l.target { + LinkTarget::EmbeddedGoTo { source: AttachmentSource::Annotation { page, index }, .. } => Some((*page, *index)), + _ => None, + }) + .collect(); + let want: Vec<(usize, usize)> = (0..PAGES).flat_map(|k| [(k, 0), (k, 1 + target(k))]).collect(); + assert_eq!(indexes, want); + let indexed: Vec = inspector + .annotation_names + .get() + .into_iter() + .flatten() + .filter_map(|page| page.get().cloned().flatten()) + .flat_map(|names| names.into_keys()) + .map(|name| name.len()) + .collect(); + let total: usize = indexed.iter().sum(); + assert!(total > 0 && total <= MAX_ANNOTATION_NAME_INDEX_BYTES, "{total} name bytes indexed"); + // The mebibyte name is scanned for, never copied into an index. + assert!(indexed.iter().all(|&len| len < 1 << 20), "the long name was indexed"); +} + #[test] fn links_read_bounded_local_remote_go_to_actions() { use DestView::{Fit, Xyz}; From 205c7868eef6b1d3bd1a50eb5da22daf7464251e Mon Sep 17 00:00:00 2001 From: Muhammad Saad Date: Sun, 18 Oct 2026 23:52:07 +0400 Subject: [PATCH 10/30] M10: put image pages on a chosen paper size (#3273) A photo becomes a page as large as its pixels, so a 4000 x 3000 phone picture with no stored resolution gives a 4000 x 3000 pt page, about 1.41 x 1.06 m, and a set of photos of different pixel sizes gives pages of several sizes, none of them paper. doc_create (from: images) and doc_create_multiple (both modes) now take page_size: a paper name, resolved against the table pdfcraft-print already owns, or [width, height] in points. The image is scaled to fit, centred, and the sheet is turned to match its orientation unless page_turn is false. A square image never turns the sheet. ImagePage::Image keeps the old behaviour and is the default, so every existing caller writes the same file as before. The paper-name match moves out of doc_print into printing::paper_named, so Create and Print answer the same names rather than growing a second list. doc_combine converts its sources inside combine_unlocked_reporting and combine_grouped_reporting, so it would need those signatures changed; it is left for a follow-up and the parity note says so. --- crates/automation/src/assemble.rs | 26 ++++++- crates/automation/src/printing.rs | 5 +- crates/automation/src/tools.rs | 8 ++- crates/automation/tests/it/automation.rs | 60 ++++++++++++++++ crates/create/src/lib.rs | 58 +++++++++++++++- crates/create/src/tests.rs | 87 ++++++++++++++++++++++++ crates/engine/src/lib.rs | 2 +- crates/engine/src/session.rs | 2 +- crates/engine/src/session/files.rs | 27 ++++++-- parity/acrobat-features.toml | 4 +- 10 files changed, 263 insertions(+), 16 deletions(-) diff --git a/crates/automation/src/assemble.rs b/crates/automation/src/assemble.rs index deb2efa18a..6e9af489c1 100644 --- a/crates/automation/src/assemble.rs +++ b/crates/automation/src/assemble.rs @@ -4,6 +4,23 @@ use super::paths::{child, read_input, read_input_bytes, unused, write_atomic}; use super::{Arc, Automation, CombineSource, Edit, Path, PathBuf, Value, json}; impl Automation { + /// The sheet image pages go on: `page_size` as a paper name ("A4", "Letter", "ARCH C") or + /// `[width, height]` in points, with the image scaled to fit and centred. Absent, each page + /// is the size of its own image, which is what a phone photo's pixels give. + fn image_page(a: &Args) -> Result { + let turn = a.opt_bool("page_turn")?.unwrap_or(true); + let bad = || ToolError::InvalidArgs("page_size must be a paper name or [width, height] in points".into()); + match a.get("page_size") { + None | Some(Value::Null) => Ok(pdfcraft_engine::ImagePage::Image), + Some(Value::String(s)) => Ok(pdfcraft_engine::ImagePage::fixed(super::printing::paper_named(Some(s))?.1, turn)), + Some(Value::Array(v)) if v.len() == 2 => { + let side = |i: usize| v.get(i).and_then(Value::as_f64).ok_or_else(bad); + Ok(pdfcraft_engine::ImagePage::fixed((side(0)?, side(1)?), turn)) + } + Some(_) => Err(bad()), + } + } + pub(crate) fn doc_create(&mut self, a: &Args) -> Result { let (name, bytes) = match a.str("from")? { "blank" => { @@ -24,7 +41,7 @@ impl Automation { } else { "Images.pdf".into() }; - (name, self.session.create_from_images_with_resolution(&images, resolution).map_err(failed)?) + (name, self.session.create_from_images_with(&images, resolution, Self::image_page(a)?).map_err(failed)?) } "text" => { let (title, text) = match (a.opt_str("text")?, a.opt_str("path")?) { @@ -200,11 +217,12 @@ impl Automation { Some(_) => return Err(ToolError::InvalidArgs("pages must list a range (or null) for each path".into())), }; // Each file is read, converted and copied in turn, so a long list holds one file at a time. + let page = Self::image_page(a)?; let sources = paths.into_iter().zip(ranges).map(|(p, range)| -> std::result::Result { let path = self.resolve(p, false)?; let bytes = read_input(&path)?; let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); - let (_, pdf) = self.session.convert_to_pdf(&name, &Arc::new(bytes)).map_err(failed)?; + let (_, pdf) = self.session.convert_to_pdf_with(&name, &Arc::new(bytes), page).map_err(failed)?; let title = path.file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); Ok((title, pdf, range)) }); @@ -215,6 +233,8 @@ impl Automation { /// One PDF per file, written into `out_dir`; a file that fails doesn't stop the others. fn create_separate(&mut self, a: &Args, paths: &[&str]) -> Result { let dir = self.resolve(a.str("out_dir").map_err(|_| ToolError::InvalidArgs("mode \"separate\" needs out_dir".into()))?, true)?; + // Checked before the folder is made, so a bad page_size leaves nothing behind. + let page = Self::image_page(a)?; std::fs::create_dir_all(&dir).map_err(|e| failed(format!("{}: {e}", dir.display())))?; let mut out = Vec::new(); for &p in paths { @@ -222,7 +242,7 @@ impl Automation { let bytes = read_input_bytes(&src).map_err(|e| format!("{}: {e}", src.display()))?; let name = src.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); let stem = src.file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "document".into()); - let (kind, pdf) = self.session.convert_to_pdf(&name, &Arc::new(bytes)).map_err(|e| e.to_string())?; + let (kind, pdf) = self.session.convert_to_pdf_with(&name, &Arc::new(bytes), page).map_err(|e| e.to_string())?; Ok((kind, stem, pdf)) }); out.push(match converted { diff --git a/crates/automation/src/printing.rs b/crates/automation/src/printing.rs index 9a1c1a6b7c..382a919a9d 100644 --- a/crates/automation/src/printing.rs +++ b/crates/automation/src/printing.rs @@ -39,7 +39,10 @@ fn bad(m: impl Into) -> ToolError { /// `doc_print`'s `paper`, by its name or a short form ("Letter", "ARCH D"), as its `PAPERS` /// index and size; US Letter when none is given. -fn paper_named(name: Option<&str>) -> Result<(usize, (f64, f64))> { +/// +/// `pub(crate)` so Create answers the same names as Print: `doc_create` takes a `page_size` that +/// may be a paper name, and a second copy of this table would drift from this one. +pub(crate) fn paper_named(name: Option<&str>) -> Result<(usize, (f64, f64))> { let mut papers = PAPERS.iter().enumerate(); let found = match name { None => papers.next(), diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index c6c200cece..3d70705da9 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -260,12 +260,13 @@ pub fn tools() -> Vec { "passwords": { "type": "array", "items": { "type": ["string", "null"] } }, "groups": { "type": "array", "items": { "type": ["integer", "null"], "minimum": 0 } }, "field_conflicts": { "type": "string", "enum": ["rename", "merge"] }, + "out": save_out, "open": open, }), &["paths"], )), - t("doc_create_multiple", "Create PDF from multiple files", "Convert several files (PDFs, PNG/JPEG/JPEG 2000/TIFF/GIF/BMP images, .txt files) to PDF in one run. mode \"combine\" (default) joins them, in order, into one PDF with a bookmark per file; pages optionally chooses each file's pages, in step with paths (a range such as \"1-3, 6\" or null). mode \"separate\" writes one PDF per file into out_dir (files that are already PDFs are skipped; existing files are never overwritten) and reports each file's result.") + t("doc_create_multiple", "Create PDF from multiple files", "Convert several files (PDFs, PNG/JPEG/JPEG 2000/TIFF/GIF/BMP images, .txt files) to PDF in one run; page_size puts each image on a sheet of one size instead of a page as large as the image. mode \"combine\" (default) joins them, in order, into one PDF with a bookmark per file; pages optionally chooses each file's pages, in step with paths (a range such as \"1-3, 6\" or null). mode \"separate\" writes one PDF per file into out_dir (files that are already PDFs are skipped; existing files are never overwritten) and reports each file's result.") .cmd("create.multiple") .with(schema( json!({ @@ -275,6 +276,8 @@ pub fn tools() -> Vec { "out": save_out.clone(), "open": open.clone(), "out_dir": { "type": "string", "description": "Folder for mode \"separate\"." }, + "page_size": { "type": ["string", "array"], "items": { "type": "number", "minimum": 3 }, "minItems": 2, "maxItems": 2, "description": "For image files: put each image on a sheet of this size instead of a page as large as the image. A paper name (A4, Letter, Legal, Tabloid, A0-A6, ARCH A-E, ANSI C-E) or [width, height] in points; the image is scaled to fit and centred." }, + "page_turn": { "type": "boolean", "description": "With page_size: turn the sheet to match each image's orientation, so a landscape photo gets a landscape page (default true)." }, }), &["paths"], )), @@ -1337,6 +1340,9 @@ pub fn tools() -> Vec { "width": { "type": "number", "minimum": 3 }, "height": { "type": "number", "minimum": 3 }, "name": { "type": "string", "description": "Name for the new document (default derived from the source)." }, + "page_size": { "type": ["string", "array"], "items": { "type": "number", "minimum": 3 }, "minItems": 2, "maxItems": 2, "description": "For image files: put each image on a sheet of this size instead of a page as large as the image. A paper name (A4, Letter, Legal, Tabloid, A0-A6, ARCH A-E, ANSI C-E) or [width, height] in points; the image is scaled to fit and centred." }, + "page_turn": { "type": "boolean", "description": "With page_size: turn the sheet to match each image's orientation, so a landscape photo gets a landscape page (default true)." }, + }), &["from"], )), diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index 6a5765b911..8f6394715a 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -9414,6 +9414,66 @@ fn text_box_and_callout_fill_and_border_through_tools() { } } +/// #3273: images became pages as large as their pixels, so a set of photos gave pages of several +/// sizes and none of them paper. `page_size` puts them all on one sheet, scaled to fit. +#[test] +fn image_pages_go_on_a_chosen_paper_size_through_every_create_tool() { + let dir = workdir("image-page-size"); + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap(); + // Two pictures of different shapes, from the fixture's own pages. + ok(&mut a, "doc_export_images", json!({ "doc": doc, "folder": "src", "dpi": 18, "pages": [1, 2] })); + let shots = ["src/a_page_1.png", "src/a_page_2.png"]; + let size = |a: &mut Automation, d: u64, page: usize| -> (f64, f64) { + let p = &ok(a, "doc_info", json!({ "doc": d }))["pages"][page]; + (p["width"].as_f64().unwrap(), p["height"].as_f64().unwrap()) + }; + const A4: (f64, f64) = (595.28, 841.89); + let close = |got: (f64, f64), want: (f64, f64)| (got.0 - want.0).abs() < 0.01 && (got.1 - want.1).abs() < 0.01; + + // Without it, pages follow the pixels, as they always have. + let plain = ok(&mut a, "doc_create", json!({ "from": "images", "paths": shots }))["doc"].as_u64().unwrap(); + assert!(!close(size(&mut a, plain, 0), A4), "the default is unchanged: {:?}", size(&mut a, plain, 0)); + + // doc_create: a paper name, with the sheet turned to each image by default. + let named = ok(&mut a, "doc_create", json!({ "from": "images", "paths": shots, "page_size": "A4" }))["doc"].as_u64().unwrap(); + for page in 0..2 { + let got = size(&mut a, named, page); + assert!(close(got, A4) || close(got, (A4.1, A4.0)), "page {page} is an A4 sheet either way up: {got:?}"); + } + // page_turn: false pins the orientation, so every page is portrait A4. + let pinned = + ok(&mut a, "doc_create", json!({ "from": "images", "paths": shots, "page_size": "A4", "page_turn": false }))["doc"].as_u64().unwrap(); + for page in 0..2 { + assert!(close(size(&mut a, pinned, page), A4), "page {page}: {:?}", size(&mut a, pinned, page)); + } + // An explicit size in points works too, and the names Print accepts are accepted here. + let explicit = + ok(&mut a, "doc_create", json!({ "from": "images", "paths": shots, "page_size": [300, 300], "page_turn": false }))["doc"].as_u64().unwrap(); + assert!(close(size(&mut a, explicit, 0), (300.0, 300.0))); + let letter = + ok(&mut a, "doc_create", json!({ "from": "images", "paths": shots, "page_size": "Letter", "page_turn": false }))["doc"].as_u64().unwrap(); + assert!(close(size(&mut a, letter, 0), (612.0, 792.0))); + + // doc_create_multiple takes it as well. + ok(&mut a, "doc_create_multiple", json!({ "paths": shots, "page_size": "A4", "page_turn": false, "out": "multiple.pdf" })); + let multiple = ok(&mut a, "doc_open", json!({ "path": "multiple.pdf" }))["doc"].as_u64().unwrap(); + assert!(close(size(&mut a, multiple, 0), A4) && close(size(&mut a, multiple, 1), A4)); + + // mode "separate" writes one PDF per image, each on the sheet. + ok(&mut a, "doc_create_multiple", json!({ "paths": shots, "mode": "separate", "out_dir": "out", "page_size": "A4", "page_turn": false })); + let one = ok(&mut a, "doc_open", json!({ "path": "out/a_page_1.pdf" }))["doc"].as_u64().unwrap(); + assert!(close(size(&mut a, one, 0), A4)); + + // A size that is not a paper name or a pair of points is refused, on every tool. + for bad in [json!("A9"), json!([300]), json!(["a", "b"]), json!(5), json!({})] { + assert!( + matches!(a.call("doc_create", &json!({ "from": "images", "paths": shots, "page_size": bad })), Err(ToolError::InvalidArgs(_))), + "{bad} should be refused" + ); + } +} + /// Three paragraphs: Alpha (two rows), Bravo (one row) and Charlie (two rows), at the leading /// of #2516. Alpha's last baseline is 35.6 pt above Bravo's; moving Alpha down 21.2 pt leaves /// 14.4 pt, Alpha's own leading, so the next read groups the two as one paragraph. diff --git a/crates/create/src/lib.rs b/crates/create/src/lib.rs index 36b52d4211..ed978de807 100644 --- a/crates/create/src/lib.rs +++ b/crates/create/src/lib.rs @@ -659,6 +659,53 @@ pub enum ImageResolution { Dpi(f64), } +/// How the page an image is placed on is sized. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub enum ImagePage { + /// The page is the image's own size at its resolution, so a page is as large as its photo + /// (a 4000 × 3000 phone picture with no stored resolution gives a 4000 × 3000 pt page). + #[default] + Image, + /// Every page is this size in points, with the image scaled to fit inside it and centred, + /// so a set of photos of different pixel sizes gives one paper size throughout. + Fixed { + width: f64, + height: f64, + /// Turn the sheet to match each image, so a landscape photo gets a landscape page + /// instead of being shrunk into a portrait one. + turn: bool, + }, +} + +impl ImagePage { + /// A4, Letter and the rest are resolved by the caller: the paper table lives in + /// `pdfcraft-print`, which is this crate's own layer, so names are parsed above both. + pub fn fixed(size: (f64, f64), turn: bool) -> Self { + Self::Fixed { width: size.0, height: size.1, turn } + } + + fn check(self) -> Result<(), CreateError> { + let Self::Fixed { width, height, .. } = self else { return Ok(()) }; + if !(width.is_finite() && height.is_finite() && (3.0..=MAX_SIDE).contains(&width) && (3.0..=MAX_SIDE).contains(&height)) { + return Err(CreateError::Invalid(format!("the page must be between 3 and {MAX_SIDE} points on each side"))); + } + Ok(()) + } + + /// The page `(width, height)` for an image of `(w, h)` points, and where to draw it: + /// `(scaled width, scaled height, x, y)`. + fn place(self, w: f64, h: f64) -> ((f64, f64), (f64, f64, f64, f64)) { + let Self::Fixed { width, height, turn } = self else { return ((w, h), (w, h, 0.0, 0.0)) }; + // A square image keeps the page as given; only a clear difference turns the sheet. + let (pw, ph) = if turn && (w > h) != (width > height) && w != h { (height, width) } else { (width, height) }; + // `w` and `h` come from a decoded image, so both are above zero; `max` keeps the + // division defined even if a future decoder ever reports an empty one. + let k = (pw / w.max(f64::MIN_POSITIVE)).min(ph / h.max(f64::MIN_POSITIVE)).min(MAX_SIDE); + let (dw, dh) = (w * k, h * k); + ((pw, ph), (dw, dh, (pw - dw) / 2.0, (ph - dh) / 2.0)) + } +} + /// One page per image, each the size of its image at the image's resolution. pub fn from_images(images: &[(String, Vec)]) -> Result { from_images_with_resolution(images, ImageResolution::Embedded) @@ -666,11 +713,17 @@ pub fn from_images(images: &[(String, Vec)]) -> Result)], resolution: ImageResolution) -> Result { + from_images_with(images, resolution, ImagePage::Image) +} + +/// Create image pages at a resolution, each on a page of its own size or on a fixed sheet. +pub fn from_images_with(images: &[(String, Vec)], resolution: ImageResolution, page: ImagePage) -> Result { if let ImageResolution::Dpi(dpi) = resolution && (!dpi.is_finite() || !(1.0..=1200.0).contains(&dpi)) { return Err(CreateError::Invalid("image DPI must be finite and between 1 and 1200".into())); } + page.check()?; if images.is_empty() { return Err(CreateError::Invalid("no images".into())); } @@ -686,13 +739,14 @@ pub fn from_images_with_resolution(images: &[(String, Vec)], resolution: Ima let k = (MAX_SIDE / w.max(h)).min(1.0); w *= k; h *= k; + let ((pw, ph), (dw, dh, x, y)) = page.place(w, h); let xr = add_image(&mut doc, img, &mut profiles); let mut xobj = Dict::new(); xobj.set(b"Im0".to_vec(), Object::Ref(xr)); let mut res = Dict::new(); res.set(b"XObject".to_vec(), Object::Dict(xobj)); - let content = format!("q {w:.3} 0 0 {h:.3} 0 0 cm /Im0 Do Q\n").into_bytes(); - add_page(&mut doc, w, h, res, Some(content))?; + let content = format!("q {dw:.3} 0 0 {dh:.3} {x:.3} {y:.3} cm /Im0 Do Q\n").into_bytes(); + add_page(&mut doc, pw, ph, res, Some(content))?; } if let Some((name, _)) = images.first() { set_title(&mut doc, name.rsplit_once('.').map_or(name.as_str(), |(s, _)| s)); diff --git a/crates/create/src/tests.rs b/crates/create/src/tests.rs index 03c93d4a51..260713763d 100644 --- a/crates/create/src/tests.rs +++ b/crates/create/src/tests.rs @@ -2209,3 +2209,90 @@ fn jbig2_globals_are_decoded_within_a_limit_of_their_own() { assert!(why.starts_with("the JBIG2 globals can't be read") && why.contains(&format!("limit of {LIMIT} bytes")), "{why}"); } } + +/// A4 in points, as `pdfcraft-print`'s paper table has it (the tools resolve the name there). +const A4: (f64, f64) = (595.28, 841.89); + +#[test] +fn a_fixed_page_scales_the_image_to_fit_and_centres_it() { + // 4 x 2 points at 72 dpi: wider than A4's proportions, so the width is the limit. + let fit = ImagePage::fixed(A4, false); + let ((pw, ph), (dw, dh, x, y)) = fit.place(4.0, 2.0); + assert_eq!((pw, ph), A4, "the sheet keeps the size it was given"); + assert!((dw - A4.0).abs() < 1e-9, "the wide side fills the page: {dw}"); + assert!((dh - A4.0 / 2.0).abs() < 1e-9, "and the aspect ratio is kept: {dh}"); + assert!(x.abs() < 1e-9 && (y - (A4.1 - dh) / 2.0).abs() < 1e-9, "centred: {x}, {y}"); + // Nothing is ever cropped or stretched. + assert!(dw <= pw + 1e-9 && dh <= ph + 1e-9); + assert!((dw / dh - 2.0).abs() < 1e-9, "aspect ratio kept"); + + // A tall image on the same sheet is limited by the height instead. + let (_, (dw, dh, x, y)) = fit.place(2.0, 4.0); + assert!((dh - A4.1).abs() < 1e-9 && (dw - A4.1 / 2.0).abs() < 1e-9, "{dw} x {dh}"); + assert!(y.abs() < 1e-9 && (x - (A4.0 - dw) / 2.0).abs() < 1e-9); + + // An image smaller than the sheet is enlarged to fit it, not left in a corner. + let (_, (dw, dh, ..)) = fit.place(10.0, 10.0); + assert!((dw - A4.0).abs() < 1e-9 && (dh - A4.0).abs() < 1e-9, "a square fills the narrow side"); +} + +#[test] +fn turning_the_sheet_follows_the_image_but_leaves_a_square_alone() { + let turn = ImagePage::fixed(A4, true); + // A landscape image turns a portrait sheet; a portrait one leaves it. + assert_eq!(turn.place(4.0, 2.0).0, (A4.1, A4.0), "landscape photo, landscape sheet"); + assert_eq!(turn.place(2.0, 4.0).0, A4, "portrait photo, portrait sheet"); + // A landscape sheet turns the other way for a portrait image. + let landscape = ImagePage::fixed((A4.1, A4.0), true); + assert_eq!(landscape.place(2.0, 4.0).0, A4); + // A square image is neither, so the sheet is left as asked for. + assert_eq!(turn.place(5.0, 5.0).0, A4, "a square never turns the sheet"); + // Without turning, the sheet is whatever it was given. + assert_eq!(ImagePage::fixed(A4, false).place(4.0, 2.0).0, A4); +} + +#[test] +fn image_pages_sized_by_the_image_are_unchanged() { + // The default must still put the page exactly on the image, at the origin. + assert_eq!(ImagePage::Image.place(4.0, 2.0), ((4.0, 2.0), (4.0, 2.0, 0.0, 0.0))); + assert_eq!(ImagePage::default(), ImagePage::Image); + let images = [("photo.png".into(), png_bytes(true)), ("scan.jpg".into(), jpeg_bytes())]; + let by_image = from_images_with(&images, ImageResolution::Embedded, ImagePage::Image).unwrap(); + assert_eq!(reopen(&by_image).bytes(), reopen(&from_images(&images).unwrap()).bytes(), "the same file as before"); +} + +#[test] +fn a_set_of_differently_shaped_images_lands_on_one_paper_size() { + // #3273: a 4 x 2 and a 3 x 2 image gave pages of two different sizes, neither of them paper. + let images = [("photo.png".into(), png_bytes(true)), ("scan.jpg".into(), jpeg_bytes())]; + let doc = reopen(&from_images_with(&images, ImageResolution::Embedded, ImagePage::fixed(A4, false)).unwrap()); + let p = pages(&doc); + assert_eq!(p.len(), 2); + for d in &p { + let m = media(d); + assert!((m[2] - A4.0).abs() < 0.001 && (m[3] - A4.1).abs() < 0.001, "every page is A4: {m:?}"); + } + // The image is drawn scaled and centred, not at the page's origin. + let c = doc.resolve(p[0].get(b"Contents").unwrap()); + let Object::Stream(s) = &*c else { panic!("expected a content stream") }; + let text = String::from_utf8_lossy(&s.decoded().unwrap()).into_owned(); + assert!(text.contains("595.280 0 0 297.640 0.000 272.125 cm"), "scaled to the width and centred: {text}"); + + // Turning gives the landscape images landscape sheets instead. + let doc = reopen(&from_images_with(&images, ImageResolution::Embedded, ImagePage::fixed(A4, true)).unwrap()); + for d in pages(&doc).iter() { + let m = media(d); + assert!((m[2] - A4.1).abs() < 0.001 && (m[3] - A4.0).abs() < 0.001, "turned for a wide image: {m:?}"); + } +} + +#[test] +fn an_unusable_page_size_is_refused_and_nothing_is_written() { + let images = [("photo.png".into(), png_bytes(true))]; + for size in [(0.0, 100.0), (100.0, 0.0), (2.9, 100.0), (f64::NAN, 100.0), (100.0, f64::INFINITY), (20_000.0, 100.0), (-5.0, 100.0)] { + let page = ImagePage::fixed(size, true); + assert!(matches!(from_images_with(&images, ImageResolution::Embedded, page), Err(CreateError::Invalid(_))), "{size:?}"); + } + // The largest page PDF allows is fine. + assert!(from_images_with(&images, ImageResolution::Embedded, ImagePage::fixed((14_400.0, 14_400.0), true)).is_ok()); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 0b49cfd4e1..fe2268bc95 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -77,7 +77,7 @@ pub use pdfcraft_organize::check_custom_key; pub use pdfcraft_organize::view::{InitialView, Layout as InitialLayout, Magnification, Navigation}; pub use pdfcraft_cos::Algorithm; -pub use pdfcraft_create::{CONVERTIBLE, CreateError, ImageResolution, SourceKind, decode_text, source_kind}; +pub use pdfcraft_create::{CONVERTIBLE, CreateError, ImagePage, ImageResolution, SourceKind, decode_text, source_kind}; pub use pdfcraft_edit::added::{ CHAR_SPACING_LIMIT as ADDED_CHAR_SPACING_LIMIT, paste_place as added_paste_place, paste_rect as added_paste_rect, text_rect as added_text_rect, text_width as added_text_width, diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 9a4cb04dac..4bc642a3a3 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -10,7 +10,7 @@ use crate::check_refresh_panic; use crate::edit::{EditCtx, check_permission, run_edit}; use crate::history::{Keys, MAX_UNDO, Scope, keys_after, scope_of, uses_scripts}; use crate::{ - BookmarkPage, BookmarkRow, CombineSource, Combined, DataFormat, DocId, Document, Edit, EditError, Hidden, ImageResolution, + BookmarkPage, BookmarkRow, CombineSource, Combined, DataFormat, DocId, Document, Edit, EditError, Hidden, ImagePage, ImageResolution, LOW_RESOLUTION_PRINT_DPI, Label, ObjectKind, OptimizeReport, RecoverySnapshot, SignOptions, SourceKind, SplitPart, SummarySort, TrustStore, XFA_REMOVED_PREFIX, XFA_SCRIPTS_OFF, apply_layer_state, comment_list, comment_summary, decode_text, display_bytes, display_config, guard, info_fields, js, local_utc_offset, note_warnings, open_source, open_source_with, optimize, outline_rows, parse_ymd, print, print_raster, diff --git a/crates/engine/src/session/files.rs b/crates/engine/src/session/files.rs index 34d75e5c82..9c90f84fa3 100644 --- a/crates/engine/src/session/files.rs +++ b/crates/engine/src/session/files.rs @@ -1,7 +1,7 @@ use super::{ - Arc, CombineSource, Combined, DataFormat, DocId, EditError, Hidden, ImageResolution, LOW_RESOLUTION_PRINT_DPI, OptimizeReport, SaveOptions, - Session, SourceKind, SplitPart, decode_text, guard, open_source, open_source_with, optimize, print, print_raster, set_default_layer_state, - source_kind, writable, write_full, + Arc, CombineSource, Combined, DataFormat, DocId, EditError, Hidden, ImagePage, ImageResolution, LOW_RESOLUTION_PRINT_DPI, OptimizeReport, + SaveOptions, Session, SourceKind, SplitPart, decode_text, guard, open_source, open_source_with, optimize, print, print_raster, + set_default_layer_state, source_kind, writable, write_full, }; impl Session { @@ -22,7 +22,18 @@ impl Session { /// Create image pages at embedded resolution or a fixed dpi, without resampling. pub fn create_from_images_with_resolution(&self, images: &[(String, Vec)], resolution: ImageResolution) -> Result>, EditError> { - self.write_new(&pdfcraft_create::from_images_with_resolution(images, resolution)?) + self.create_from_images_with(images, resolution, ImagePage::Image) + } + + /// Create image pages at a resolution, each on its own size or on one fixed sheet (scaled to + /// fit and centred). Pixels are never resampled either way. + pub fn create_from_images_with( + &self, + images: &[(String, Vec)], + resolution: ImageResolution, + page: ImagePage, + ) -> Result>, EditError> { + self.write_new(&pdfcraft_create::from_images_with(images, resolution, page)?) } /// A new document from plain text (US Letter, 11 pt Helvetica). Text Helvetica can't draw is @@ -42,6 +53,12 @@ impl Session { /// Convert a file Create understands (an image or plain text) to PDF bytes; a PDF is checked /// (it must open and allow copying pages) and returned as it is. pub fn convert_to_pdf(&self, name: &str, bytes: &Arc>) -> Result<(SourceKind, Arc>), EditError> { + self.convert_to_pdf_with(name, bytes, ImagePage::Image) + } + + /// [`Self::convert_to_pdf`], putting an image source on `page`. A PDF or text source is + /// unaffected: only an image is laid onto a sheet of a chosen size. + pub fn convert_to_pdf_with(&self, name: &str, bytes: &Arc>, page: ImagePage) -> Result<(SourceKind, Arc>), EditError> { let Some(kind) = source_kind(name, bytes) else { return Err(EditError::Source(format!("{name}: this file type can't be converted; use a PDF, an image or a .txt file"))); }; @@ -49,7 +66,7 @@ impl Session { // Image decoders read untrusted bytes: a panic in one must not take the app down. let created = guard(|| match kind { SourceKind::Pdf => open_source(name, bytes).map(|_| bytes.clone()), - SourceKind::Image => self.create_from_images(&[(name.to_string(), bytes.to_vec())]), + SourceKind::Image => self.create_from_images_with(&[(name.to_string(), bytes.to_vec())], ImageResolution::Embedded, page), SourceKind::Text => self.create_from_text(title, &decode_text(bytes)), }) .map_err(|_| EditError::Source(format!("{name}: the file could not be read")))?; diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 0b6f658dd6..63e2c6367d 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -6896,8 +6896,8 @@ milestone = "M10" status = "shipped" commands = ["create.images"] tools = ["doc_create"] -evidence = ["crates/create/src/tests.rs::black_and_white_images_are_stored_at_one_bit", "crates/create/src/tests.rs::jpeg_2000_images_are_embedded_as_is", "crates/create/src/tests.rs::images_export_as_jpeg_unchanged_and_others_as_png", "crates/create/src/tests.rs::embedded_icc_profiles_tag_the_image_colour_space"] -notes = "PNG, JPEG, TIFF (multi-page), GIF (first frame), BMP, and JPEG 2000 (JP2 or codestream, embedded as JPXDecode with its capture resolution). JPEG and PNG ICC profiles are kept as /ICCBased; TIFF profiles are not read yet. A picture of only pure black and white (a 1-bit PNG or TIFF, eight-bit grey, a two-colour palette, RGB without a profile) is stored at one bit per pixel, as CCITT Group 4 or Flate, whichever is smaller" +evidence = ["crates/create/src/tests.rs::black_and_white_images_are_stored_at_one_bit", "crates/create/src/tests.rs::jpeg_2000_images_are_embedded_as_is", "crates/create/src/tests.rs::images_export_as_jpeg_unchanged_and_others_as_png", "crates/create/src/tests.rs::embedded_icc_profiles_tag_the_image_colour_space", "crates/create/src/tests.rs::a_set_of_differently_shaped_images_lands_on_one_paper_size", "crates/automation/tests/automation.rs::image_pages_go_on_a_chosen_paper_size_through_every_create_tool"] +notes = "PNG, JPEG, TIFF (multi-page), GIF (first frame), BMP, and JPEG 2000 (JP2 or codestream, embedded as JPXDecode with its capture resolution). JPEG and PNG ICC profiles are kept as /ICCBased; TIFF profiles are not read yet. A picture of only pure black and white (a 1-bit PNG or TIFF, eight-bit grey, a two-colour palette, RGB without a profile) is stored at one bit per pixel, as CCITT Group 4 or Flate, whichever is smaller. Pages follow the image at its resolution, or sit on a chosen sheet (page_size: a paper name or points, scaled to fit, centred, turned to the image unless page_turn is false) in doc_create and doc_create_multiple; doc_combine does not take it yet, and there is no dialog for it" [[feature]] id = "create.from-multipage-tiff" From 86bd77fa9ddfda2e168da5992c4d3457bb2608b7 Mon Sep 17 00:00:00 2001 From: Muhammad Saad Date: Wed, 21 Oct 2026 08:34:27 +0400 Subject: [PATCH 11/30] M10: cover both tools in the page_size refusal test (#3273) Review follow-up. The test's comment said a bad page_size is refused "on every tool", but the loop called only doc_create. It now calls doc_create and both of doc_create_multiple's modes, so the comment is what the test proves rather than a claim beside it. create_separate checked page_size after creating out_dir, so a refused request left an empty folder behind. The check moves above the mkdir and the test asserts neither the file nor the folder appears. The parity entry listed only doc_create under tools, although its own notes and evidence already covered doc_create_multiple. --- crates/automation/tests/it/automation.rs | 16 +++++++++++----- parity/acrobat-features.toml | 4 ++-- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index 8f6394715a..bee7551245 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -9465,13 +9465,19 @@ fn image_pages_go_on_a_chosen_paper_size_through_every_create_tool() { let one = ok(&mut a, "doc_open", json!({ "path": "out/a_page_1.pdf" }))["doc"].as_u64().unwrap(); assert!(close(size(&mut a, one, 0), A4)); - // A size that is not a paper name or a pair of points is refused, on every tool. + // A size that is not a paper name or a pair of points is refused, by every tool that takes + // one and in both of doc_create_multiple's modes, before anything is written. for bad in [json!("A9"), json!([300]), json!(["a", "b"]), json!(5), json!({})] { - assert!( - matches!(a.call("doc_create", &json!({ "from": "images", "paths": shots, "page_size": bad })), Err(ToolError::InvalidArgs(_))), - "{bad} should be refused" - ); + for (tool, args) in [ + ("doc_create", json!({ "from": "images", "paths": shots, "page_size": bad.clone() })), + ("doc_create_multiple", json!({ "paths": shots, "page_size": bad.clone(), "out": "refused.pdf" })), + ("doc_create_multiple", json!({ "paths": shots, "mode": "separate", "out_dir": "refused", "page_size": bad.clone() })), + ] { + assert!(matches!(a.call(tool, &args), Err(ToolError::InvalidArgs(_))), "{tool}: {bad} should be refused"); + } } + assert!(!dir.join("refused.pdf").exists(), "a refused page_size leaves no file behind"); + assert!(!dir.join("refused").exists(), "nor a folder"); } /// Three paragraphs: Alpha (two rows), Bravo (one row) and Charlie (two rows), at the leading diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 63e2c6367d..5b4a679304 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -6895,8 +6895,8 @@ tier = "P0" milestone = "M10" status = "shipped" commands = ["create.images"] -tools = ["doc_create"] -evidence = ["crates/create/src/tests.rs::black_and_white_images_are_stored_at_one_bit", "crates/create/src/tests.rs::jpeg_2000_images_are_embedded_as_is", "crates/create/src/tests.rs::images_export_as_jpeg_unchanged_and_others_as_png", "crates/create/src/tests.rs::embedded_icc_profiles_tag_the_image_colour_space", "crates/create/src/tests.rs::a_set_of_differently_shaped_images_lands_on_one_paper_size", "crates/automation/tests/automation.rs::image_pages_go_on_a_chosen_paper_size_through_every_create_tool"] +tools = ["doc_create", "doc_create_multiple"] +evidence = ["crates/create/src/tests.rs::black_and_white_images_are_stored_at_one_bit", "crates/create/src/tests.rs::jpeg_2000_images_are_embedded_as_is", "crates/create/src/tests.rs::images_export_as_jpeg_unchanged_and_others_as_png", "crates/create/src/tests.rs::embedded_icc_profiles_tag_the_image_colour_space", "crates/create/src/tests.rs::a_set_of_differently_shaped_images_lands_on_one_paper_size", "crates/automation/tests/it/automation.rs::image_pages_go_on_a_chosen_paper_size_through_every_create_tool"] notes = "PNG, JPEG, TIFF (multi-page), GIF (first frame), BMP, and JPEG 2000 (JP2 or codestream, embedded as JPXDecode with its capture resolution). JPEG and PNG ICC profiles are kept as /ICCBased; TIFF profiles are not read yet. A picture of only pure black and white (a 1-bit PNG or TIFF, eight-bit grey, a two-colour palette, RGB without a profile) is stored at one bit per pixel, as CCITT Group 4 or Flate, whichever is smaller. Pages follow the image at its resolution, or sit on a chosen sheet (page_size: a paper name or points, scaled to fit, centred, turned to the image unless page_turn is false) in doc_create and doc_create_multiple; doc_combine does not take it yet, and there is no dialog for it" [[feature]] From bbba4b2585f2ff90ef16e7644ddb8d61dfa88d06 Mon Sep 17 00:00:00 2001 From: Muhammad Saad Date: Fri, 23 Oct 2026 03:09:51 +0400 Subject: [PATCH 12/30] M10: let a small image fill its fixed page (#3273 review) The fit scale was capped with MAX_SIDE, which bounds a page side, not a ratio. Past that scale the image came out smaller than the sheet: a 4 x 2 image at 1200 dpi covered 3456 pt of a 14400 pt page instead of all of it, and a 30 x 30 JFIF at 65535 dpi covered 475 pt of Letter. The fit scale needs no cap of its own. It is min(pw / w, ph / h), so the drawn size is at most the page's by construction, and w and h are above zero because a decoded image has at least one pixel and every decoder here falls back to 72 dpi rather than pass on a non-positive resolution. The guards against a zero divisor went with the cap, with a comment saying why the division is defined. Found by the review bot. The test was written before the fix and observed failing at 3456 x 1728. --- crates/create/src/lib.rs | 13 ++++++++++--- crates/create/src/tests.rs | 16 ++++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/crates/create/src/lib.rs b/crates/create/src/lib.rs index ed978de807..76bd79a362 100644 --- a/crates/create/src/lib.rs +++ b/crates/create/src/lib.rs @@ -698,9 +698,16 @@ impl ImagePage { let Self::Fixed { width, height, turn } = self else { return ((w, h), (w, h, 0.0, 0.0)) }; // A square image keeps the page as given; only a clear difference turns the sheet. let (pw, ph) = if turn && (w > h) != (width > height) && w != h { (height, width) } else { (width, height) }; - // `w` and `h` come from a decoded image, so both are above zero; `max` keeps the - // division defined even if a future decoder ever reports an empty one. - let k = (pw / w.max(f64::MIN_POSITIVE)).min(ph / h.max(f64::MIN_POSITIVE)).min(MAX_SIDE); + // A scale is a ratio, not a length, so `MAX_SIDE` has no business capping it: it bounds + // a page side, which `ImagePage::check` has already applied. Capping the scale with it + // only shrank a small image on a large sheet (a 4 x 2 image at 1200 dpi covered 3456 pt + // of a 14400 pt page instead of all of it). The fit scale needs no cap of its own: it is + // `min(pw / w, ph / h)`, so the drawn size is the page's by construction. + // + // `w` and `h` are above zero, so the division is defined: a decoded image has at least + // one pixel, and every decoder here falls back to 72 dpi rather than pass on a + // non-positive resolution (`xppu > 0 && yppu > 0` for PNG, `> 1.0` for JPEG). + let k = (pw / w).min(ph / h); let (dw, dh) = (w * k, h * k); ((pw, ph), (dw, dh, (pw - dw) / 2.0, (ph - dh) / 2.0)) } diff --git a/crates/create/src/tests.rs b/crates/create/src/tests.rs index 260713763d..f380340fee 100644 --- a/crates/create/src/tests.rs +++ b/crates/create/src/tests.rs @@ -2296,3 +2296,19 @@ fn an_unusable_page_size_is_refused_and_nothing_is_written() { // The largest page PDF allows is fine. assert!(from_images_with(&images, ImageResolution::Embedded, ImagePage::fixed((14_400.0, 14_400.0), true)).is_ok()); } + +/// A fixed page is filled by the image whatever its resolution: a tiny image at a high dpi is +/// enlarged to the sheet, not left small on it. `MAX_SIDE` bounds a page side, which +/// `ImagePage::check` has already applied, so it must not also cap the fit scale. +#[test] +fn a_tiny_high_dpi_image_still_fills_its_fixed_page() { + let images = [("photo.png".into(), png_bytes(true))]; + // 4 x 2 px at 1200 dpi is 0.24 x 0.12 pt: the fit scale is 60000, far past MAX_SIDE. + let page = ImagePage::fixed((MAX_SIDE, MAX_SIDE), false); + let doc = reopen(&from_images_with(&images, ImageResolution::Dpi(1200.0), page).unwrap()); + let p = pages(&doc); + let c = doc.resolve(p[0].get(b"Contents").unwrap()); + let Object::Stream(s) = &*c else { panic!("expected a content stream") }; + let text = String::from_utf8_lossy(&s.decoded().unwrap()).into_owned(); + assert!(text.contains("14400.000 0 0 7200.000 0.000 3600.000 cm"), "the image should span the full 14400 pt page: {text}"); +} From 8bd4d2986ea33fdf780741956e861863527efde2 Mon Sep 17 00:00:00 2001 From: Muhammad Saad Date: Mon, 26 Oct 2026 10:05:03 +0400 Subject: [PATCH 13/30] M10: refuse an out-of-range page_size before out_dir is made (#3273) image_page validated the shape of page_size but not its magnitude, so [14401, 792] passed it and only the conversion refused the page. In mode "separate" that is a side effect ahead of the check: create_separate makes out_dir first and then fails once per file, leaving an empty folder behind. The comment there claimed a bad page_size left nothing behind, which was only true of a malformed one. ImagePage::check already applies the 3 to 14400 point limit (ISO 32000-2 Annex C), so make it public and call it from image_page rather than repeat the number: an unmakeable page is the caller's argument being wrong, so it is InvalidArgs, and every creation path shares the one helper. The tool schema gains the maximum it was documenting only as a minimum. Tests: the existing refusal test gains [14401, 792], [612, 2] and [-612, 792], and already asserts that no file and no folder is left behind. Removing the check reds it with `doc_create: [14401,792] should be refused`. cargo fmt --check, clippy -D warnings, pdfcraft-create (52) and pdfcraft-automation (245 + 37) tests, xtask layers (37 crates) and xtask assets all pass. --- crates/automation/src/assemble.rs | 16 ++++++++++------ crates/automation/src/tools.rs | 4 ++-- crates/automation/tests/it/automation.rs | 9 ++++++--- crates/create/src/lib.rs | 7 ++++++- 4 files changed, 24 insertions(+), 12 deletions(-) diff --git a/crates/automation/src/assemble.rs b/crates/automation/src/assemble.rs index 6e9af489c1..8420f44f82 100644 --- a/crates/automation/src/assemble.rs +++ b/crates/automation/src/assemble.rs @@ -10,15 +10,19 @@ impl Automation { fn image_page(a: &Args) -> Result { let turn = a.opt_bool("page_turn")?.unwrap_or(true); let bad = || ToolError::InvalidArgs("page_size must be a paper name or [width, height] in points".into()); - match a.get("page_size") { - None | Some(Value::Null) => Ok(pdfcraft_engine::ImagePage::Image), - Some(Value::String(s)) => Ok(pdfcraft_engine::ImagePage::fixed(super::printing::paper_named(Some(s))?.1, turn)), + let page = match a.get("page_size") { + None | Some(Value::Null) => pdfcraft_engine::ImagePage::Image, + Some(Value::String(s)) => pdfcraft_engine::ImagePage::fixed(super::printing::paper_named(Some(s))?.1, turn), Some(Value::Array(v)) if v.len() == 2 => { let side = |i: usize| v.get(i).and_then(Value::as_f64).ok_or_else(bad); - Ok(pdfcraft_engine::ImagePage::fixed((side(0)?, side(1)?), turn)) + pdfcraft_engine::ImagePage::fixed((side(0)?, side(1)?), turn) } - Some(_) => Err(bad()), - } + Some(_) => return Err(bad()), + }; + // A page the creator cannot make is the caller's argument being wrong, not a conversion + // failure, and refusing it here is what keeps mode "separate" from making out_dir first. + page.check().map_err(|e| ToolError::InvalidArgs(e.to_string()))?; + Ok(page) } pub(crate) fn doc_create(&mut self, a: &Args) -> Result { diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index 3d70705da9..b675f3d7e7 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -276,7 +276,7 @@ pub fn tools() -> Vec { "out": save_out.clone(), "open": open.clone(), "out_dir": { "type": "string", "description": "Folder for mode \"separate\"." }, - "page_size": { "type": ["string", "array"], "items": { "type": "number", "minimum": 3 }, "minItems": 2, "maxItems": 2, "description": "For image files: put each image on a sheet of this size instead of a page as large as the image. A paper name (A4, Letter, Legal, Tabloid, A0-A6, ARCH A-E, ANSI C-E) or [width, height] in points; the image is scaled to fit and centred." }, + "page_size": { "type": ["string", "array"], "items": { "type": "number", "minimum": 3, "maximum": 14400 }, "minItems": 2, "maxItems": 2, "description": "For image files: put each image on a sheet of this size instead of a page as large as the image. A paper name (A4, Letter, Legal, Tabloid, A0-A6, ARCH A-E, ANSI C-E) or [width, height] in points, each between 3 and 14400 (the largest a PDF page may be); the image is scaled to fit and centred." }, "page_turn": { "type": "boolean", "description": "With page_size: turn the sheet to match each image's orientation, so a landscape photo gets a landscape page (default true)." }, }), &["paths"], @@ -1340,7 +1340,7 @@ pub fn tools() -> Vec { "width": { "type": "number", "minimum": 3 }, "height": { "type": "number", "minimum": 3 }, "name": { "type": "string", "description": "Name for the new document (default derived from the source)." }, - "page_size": { "type": ["string", "array"], "items": { "type": "number", "minimum": 3 }, "minItems": 2, "maxItems": 2, "description": "For image files: put each image on a sheet of this size instead of a page as large as the image. A paper name (A4, Letter, Legal, Tabloid, A0-A6, ARCH A-E, ANSI C-E) or [width, height] in points; the image is scaled to fit and centred." }, + "page_size": { "type": ["string", "array"], "items": { "type": "number", "minimum": 3, "maximum": 14400 }, "minItems": 2, "maxItems": 2, "description": "For image files: put each image on a sheet of this size instead of a page as large as the image. A paper name (A4, Letter, Legal, Tabloid, A0-A6, ARCH A-E, ANSI C-E) or [width, height] in points, each between 3 and 14400 (the largest a PDF page may be); the image is scaled to fit and centred." }, "page_turn": { "type": "boolean", "description": "With page_size: turn the sheet to match each image's orientation, so a landscape photo gets a landscape page (default true)." }, }), diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index bee7551245..2c9ce9bc9d 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -9465,9 +9465,12 @@ fn image_pages_go_on_a_chosen_paper_size_through_every_create_tool() { let one = ok(&mut a, "doc_open", json!({ "path": "out/a_page_1.pdf" }))["doc"].as_u64().unwrap(); assert!(close(size(&mut a, one, 0), A4)); - // A size that is not a paper name or a pair of points is refused, by every tool that takes - // one and in both of doc_create_multiple's modes, before anything is written. - for bad in [json!("A9"), json!([300]), json!(["a", "b"]), json!(5), json!({})] { + // A size no page can be is refused the same way: not a paper name, not a pair of points, or + // a pair outside the 3 to 14400 points a PDF page may be (ISO 32000-2 Annex C). Checked for + // every tool that takes one and in both of doc_create_multiple's modes, because "separate" + // makes out_dir before it converts anything and a size reported only by the conversion would + // leave the folder behind. + for bad in [json!("A9"), json!([300]), json!(["a", "b"]), json!(5), json!({}), json!([14401, 792]), json!([612, 2]), json!([-612, 792])] { for (tool, args) in [ ("doc_create", json!({ "from": "images", "paths": shots, "page_size": bad.clone() })), ("doc_create_multiple", json!({ "paths": shots, "page_size": bad.clone(), "out": "refused.pdf" })), diff --git a/crates/create/src/lib.rs b/crates/create/src/lib.rs index 76bd79a362..b2fd766deb 100644 --- a/crates/create/src/lib.rs +++ b/crates/create/src/lib.rs @@ -684,7 +684,12 @@ impl ImagePage { Self::Fixed { width: size.0, height: size.1, turn } } - fn check(self) -> Result<(), CreateError> { + /// Refuse a page this crate cannot make. + /// + /// Public so a caller that acts before converting can refuse the size before the side effect: + /// `doc_create_multiple` in mode "separate" makes `out_dir` first, and an out-of-range size + /// reported only by the conversion would leave the folder behind. + pub fn check(self) -> Result<(), CreateError> { let Self::Fixed { width, height, .. } = self else { return Ok(()) }; if !(width.is_finite() && height.is_finite() && (3.0..=MAX_SIDE).contains(&width) && (3.0..=MAX_SIDE).contains(&height)) { return Err(CreateError::Invalid(format!("the page must be between 3 and {MAX_SIDE} points on each side"))); From 3ba8deed53087f700ebd87ce0a364892d9e8cdbc Mon Sep 17 00:00:00 2001 From: Muhammad Saad Date: Mon, 26 Oct 2026 20:11:41 +0400 Subject: [PATCH 14/30] M10: cover that page_size lays out images and nothing else (#3273) @FredApps approved at 2bc3cbd and said which part he had read but not run: whether a PDF or text source ignores page_size. It does, and the reason is one line in convert_to_pdf_with: only the SourceKind::Image arm is handed `page`, a PDF comes back as its own bytes and text goes through create_from_text, which takes no page at all. An approval resting on a reading is worth turning into evidence, especially for a behaviour that is easy to widen by accident. doc_create_multiple over a PDF, a .txt and an image with page_size: A4 now asserts the PDF's first page keeps its own size, the image's page is the sheet either way up, and all three sources contributed pages. It also asserts the fixture is not A4 to begin with, since otherwise the first assertion would pass for the wrong reason. Proved by regression: routing the Pdf arm through create_blank at the requested size reds it with `the PDF's first page keeps its own size: (595.28, 841.89)`. cargo fmt --check, clippy -D warnings and pdfcraft-automation (271 + 45 passed) all pass. --- crates/automation/tests/it/automation.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index 2c9ce9bc9d..3754174f5c 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -9481,6 +9481,25 @@ fn image_pages_go_on_a_chosen_paper_size_through_every_create_tool() { } assert!(!dir.join("refused.pdf").exists(), "a refused page_size leaves no file behind"); assert!(!dir.join("refused").exists(), "nor a folder"); + + // page_size lays out images and nothing else. A PDF source is returned as it is and a .txt + // goes through create_from_text, so neither takes the sheet: #3273 asked for photos to stop + // dictating the page, not for every source to be re-sized. Covering it because the engine + // passes `page` only to the image arm of `convert_to_pdf_with`, which is easy to widen by + // accident later (@FredApps named this as the part he read but did not run). + std::fs::write(dir.join("notes.txt"), "Some notes").unwrap(); + let mixed = ok(&mut a, "doc_create_multiple", json!({ "paths": ["a.pdf", "notes.txt", shots[0]], "page_size": "A4", "out": "mixed.pdf" })); + assert!(mixed["bytes"].as_u64().unwrap_or(0) > 0, "the mixed run produced a file: {mixed}"); + let doc_mixed = ok(&mut a, "doc_open", json!({ "path": "mixed.pdf" }))["doc"].as_u64().unwrap(); + let pages = ok(&mut a, "doc_info", json!({ "doc": doc_mixed }))["pages"].as_array().cloned().unwrap_or_default(); + let a_pdf = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap(); + let kept = size(&mut a, a_pdf, 0); + assert!(!close(kept, A4) && !close(kept, (A4.1, A4.0)), "the fixture is not A4 already, or this test proves nothing: {kept:?}"); + assert!(close(size(&mut a, doc_mixed, 0), kept), "the PDF's first page keeps its own size: {:?}", size(&mut a, doc_mixed, 0)); + let last = pages.len() - 1; + let image_page = size(&mut a, doc_mixed, last); + assert!(close(image_page, A4) || close(image_page, (A4.1, A4.0)), "the image page did go on the sheet: {image_page:?}"); + assert!(pages.len() > 2, "all three sources contributed pages: {}", pages.len()); } /// Three paragraphs: Alpha (two rows), Bravo (one row) and Charlie (two rows), at the leading From e931e0c817841d6cc9d95767a4c9a8182e9f9f48 Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Sat, 31 Oct 2026 18:16:57 +0800 Subject: [PATCH 15/30] M3: a repeated /NM costs the GoToE name index nothing The per-page /NM index keeps only the first annotation with each name, but it charged the shared byte budget for every /NM on the page. One long name repeated across about 16,000 annotations spent the whole 16 MiB budget without adding an entry, so the page's index was dropped and every GoToE target naming an annotation there went back to scanning /Annots. A name already in the index is now skipped before the budget is charged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Pq7HyCfwzyRXj4VfQAVVdv --- crates/render/src/inspect/annotations.rs | 6 +++- crates/render/src/inspect/tests.rs | 42 ++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/crates/render/src/inspect/annotations.rs b/crates/render/src/inspect/annotations.rs index 39ac45ab0f..c52865e5c4 100644 --- a/crates/render/src/inspect/annotations.rs +++ b/crates/render/src/inspect/annotations.rs @@ -325,6 +325,10 @@ impl<'a> Inspector<'a> { let mut budget = self.annotation_name_budget.get(); for (i, a) in annots.iter().enumerate() { let Some(nm) = self.annotation_name(a).filter(|nm| nm.len() <= MAX_INDEXED_ANNOTATION_NAME_BYTES) else { continue }; + // A repeated name keeps its first position and adds no entry, so it costs nothing. + if names.contains_key(nm) { + continue; + } // Each entry costs its name and its slot, so many short names are bounded too. let Some(left) = budget.checked_sub(nm.len().saturating_add(std::mem::size_of::<(Vec, usize)>())) else { // What the page used so far is spent; nothing of it is kept. @@ -332,7 +336,7 @@ impl<'a> Inspector<'a> { return None; }; budget = left; - names.entry(nm.to_vec()).or_insert(i); + names.insert(nm.to_vec(), i); } self.annotation_name_budget.set(budget); Some(names) diff --git a/crates/render/src/inspect/tests.rs b/crates/render/src/inspect/tests.rs index a2fd612018..e09bf6c251 100644 --- a/crates/render/src/inspect/tests.rs +++ b/crates/render/src/inspect/tests.rs @@ -1423,6 +1423,48 @@ fn embedded_go_to_annotation_name_indexes_share_a_byte_budget() { assert!(indexed.iter().all(|&len| len < 1 << 20), "the long name was indexed"); } +/// A `/NM` repeated across a page's `/Annots` is charged to the index budget once: one long name +/// on 17,000 annotations would otherwise spend the whole budget, drop the page's index and send +/// every GoToE target on that page back to scanning `/Annots`. +#[test] +fn embedded_go_to_repeated_annotation_name_is_charged_once() { + use super::annotations::MAX_ANNOTATION_NAME_INDEX_BYTES; + const REPEATS: usize = 17_000; + let long = "r".repeat(1000); + let annots = format!("{} 6 0 R", "5 0 R ".repeat(REPEATS)); + let mut pdf = + String::from("%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >> endobj\n"); + pdf += &format!("3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Annots [{annots}] >> endobj\n"); + pdf += "4 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Annots [8 0 R 9 0 R] >> endobj\n"; + pdf += &format!("5 0 obj << /Type /Annot /Subtype /FileAttachment /Rect [0 0 1 1] /NM ({long}) >> endobj\n"); + pdf += "6 0 obj << /Type /Annot /Subtype /FileAttachment /Rect [0 0 1 1] /NM (last) >> endobj\n"; + let link = |o: usize, nm: &str| { + format!("{o} 0 obj << /Type /Annot /Subtype /Link /Rect [0 0 1 1] /A << /S /GoToE /T << /R /C /P 0 /A ({nm}) >> /D [0 /Fit] >> >> endobj\n") + }; + pdf += &link(8, &long); + pdf += &link(9, "last"); + pdf += "trailer << /Root 1 0 R >>\n%%EOF"; + let doc = Document::load_mem(pdf.as_bytes()).expect("loads"); + let blank = PageInfo { width: 200.0, height: 200.0, crop: [0.0, 0.0, 200.0, 200.0], rotation: 0, label: String::new() }; + let mut info = DocInfo { pages: vec![blank; 2], ..Default::default() }; + let inspector = Inspector::new(&doc); + inspector.fill(&mut info); + let indexes: Vec = info + .links + .iter() + .filter_map(|l| match &l.target { + LinkTarget::EmbeddedGoTo { source: AttachmentSource::Annotation { page: 0, index }, .. } => Some(*index), + _ => None, + }) + .collect(); + assert_eq!(indexes, [0, REPEATS]); + let page = inspector.annotation_names.get().and_then(|pages| pages.first()).and_then(|page| page.get()); + let Some(Some(names)) = page else { panic!("page 0's /NM index was dropped: {page:?}") }; + assert_eq!(names.len(), 2); + let spent = MAX_ANNOTATION_NAME_INDEX_BYTES - inspector.annotation_name_budget.get(); + assert!(spent < 2 * (1000 + 64), "{spent} budget bytes spent on two names"); +} + #[test] fn links_read_bounded_local_remote_go_to_actions() { use DestView::{Fit, Xyz}; From a70b3f67300216dabb09e26a2c26bf88437a310f Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Mon, 2 Nov 2026 22:56:26 +0800 Subject: [PATCH 16/30] test(engine): probe an opaque pixel in main's cropped copy-image check Main added a crop step to copy_image_finds_the_image_under_a_point_and_decodes_it_at_full_size that probes the image centre, which is a transparent pixel. With this branch a picture is picked only where it shows, so that probe found nothing. Probe the red pixel inside the kept box instead, and the red top-left corner for the cropped-away check, so both still test the crop. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Pq7HyG234xeYkJfr41E6iP --- crates/engine/src/tests.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 300fb4782f..6a0abd8d8a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -8145,8 +8145,10 @@ fn copy_image_finds_the_image_under_a_point_and_decodes_it_at_full_size() { let crop_keep = [r[0] + (r[2] - r[0]) * 0.25, r[1] + (r[3] - r[1]) * 0.25, r[0] + (r[2] - r[0]) * 0.75, r[1] + (r[3] - r[1]) * 0.75]; s.apply(id, Edit::EditPageImage { page: 0, index: 0, change: ImageEdit::Crop(crop_keep) }).unwrap(); let d = s.get(id).unwrap(); - assert_eq!(d.page_image_at(0, [(r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0]), Some(0)); - assert_eq!(d.page_image_at(0, [r[0] + 0.1, r[1] + 0.1]), None, "cropped-away corner must not hit-test positive"); + // Probe the red pixel: a picture is picked only where it shows, so a transparent pixel would + // not hit-test positive whether or not it was cropped away. + assert_eq!(d.page_image_at(0, [r[0] + (r[2] - r[0]) * 0.29, r[1] + (r[3] - r[1]) * 0.65]), Some(0)); + assert_eq!(d.page_image_at(0, [r[0] + 0.1, r[3] - 0.1]), None, "cropped-away corner must not hit-test positive"); } /// Copy Image: a JPEG drawn through grouped Form artwork (as Word, InDesign and scanners write From dc686b51cf4ca1da8097b8a0c6f1eb6b4014120e Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Mon, 2 Nov 2026 23:36:12 +0800 Subject: [PATCH 17/30] M7: the opacity grid decodes its picture and masks through an ImageBudget Main now decodes images outside the renderer only through `pdfcraft_cos::ImageBudget` (`Document::decoded_image_within` became test-only), so the size checks of the picture and its `/SMask` or `/Mask` and the extraction that follows share one allowance. The byte bound each check passes is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Pq7HyG234xeYkJfr41E6iP --- crates/engine/src/image_alpha.rs | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/image_alpha.rs b/crates/engine/src/image_alpha.rs index 3accb79df9..8cb93070c2 100644 --- a/crates/engine/src/image_alpha.rs +++ b/crates/engine/src/image_alpha.rs @@ -104,18 +104,20 @@ fn build(cos: &pdfcraft_cos::Document, object: ObjRef) -> Option { // The picture and the mask images it brings are decoded in full before anything is scaled // down to the picture's size, so each must be small enough, in pixels and in decoded bytes, // before any of it is decoded. + // One decoding allowance for the picture and its masks (`ImageBudget`), however many there are. + let mut budget = pdfcraft_cos::ImageBudget::new(cos); let components = if stencil { 1 } else { components(cos, s.dict.get(b"ColorSpace")) }; - if !within_budget(cos, s, components, stencil) { + if !within_budget(cos, &mut budget, s, components, stencil) { return None; } for key in [&b"SMask"[..], b"Mask"] { if let Some(Object::Stream(mask)) = s.dict.get(key).map(|v| cos.resolve(v)).as_deref() - && !within_budget(cos, mask, 1, key == b"Mask" || flag(cos, mask, b"ImageMask")) + && !within_budget(cos, &mut budget, mask, 1, key == b"Mask" || flag(cos, mask, b"ImageMask")) { return None; } } - let (_, bytes) = pdfcraft_create::image_file(cos, object).ok()?; + let (_, bytes) = pdfcraft_create::image_file_within(cos, object, &mut budget).ok()?; let format = image::guess_format(&bytes).ok()?; let mut reader = image::ImageReader::with_format(std::io::Cursor::new(bytes.as_slice()), format); let mut limits = image::Limits::default(); @@ -182,8 +184,15 @@ fn flag(cos: &pdfcraft_cos::Document, s: &pdfcraft_cos::Stream, key: &[u8]) -> b /// its samples are decoded through its filters, no more decoded bytes than its declared size /// needs, with room for padding a writer left after the samples. Without that bound a 1 × 1 /// picture whose stream inflates to a gigabyte would be decoded in full on the first hover. JPEG, -/// JPEG 2000 and JBIG2 data go to their own decoders instead. -fn within_budget(cos: &pdfcraft_cos::Document, s: &pdfcraft_cos::Stream, components: u64, stencil: bool) -> bool { +/// JPEG 2000 and JBIG2 data go to their own decoders instead. The decode is charged to +/// `allowance`, the picture's shared [`ImageBudget`](pdfcraft_cos::ImageBudget). +fn within_budget( + cos: &pdfcraft_cos::Document, + allowance: &mut pdfcraft_cos::ImageBudget, + s: &pdfcraft_cos::Stream, + components: u64, + stencil: bool, +) -> bool { let size = |key: &[u8]| u64::try_from(s.dict.int(key).unwrap_or(0)).unwrap_or(0); let (w, h) = (size(b"Width"), size(b"Height")); if w.saturating_mul(h) > MAX_DECODE_PIXELS { @@ -201,7 +210,7 @@ fn within_budget(cos: &pdfcraft_cos::Document, s: &pdfcraft_cos::Stream, compone let row = w.checked_mul(components).and_then(|n| n.checked_mul(bpc)).map(|bits| bits.div_ceil(8)); let budget = row.and_then(|r| r.checked_mul(h)).and_then(|n| n.checked_add(n / 4)).and_then(|n| n.checked_add(DECODE_SLACK)); let Some(budget) = budget.and_then(|n| usize::try_from(n).ok()) else { return false }; - cos.decoded_image_within(s, budget).is_ok() + allowance.decode(cos, s, budget).is_ok() } /// The colour components of an image in colour space `space` (ISO 32000-2 §8.6): one for an From bb0a19323bc947e0dd8a35c8e8556a7b0c65ea55 Mon Sep 17 00:00:00 2001 From: cyfung1031 <44498510+cyfung1031@users.noreply.github.com> Date: Sat, 24 Oct 2026 00:06:32 +0000 Subject: [PATCH 18/30] M14: show an opening notice during PDF preparation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rebased onto main as one commit (the branch had merged main several times). The catalogs added on main since (ca, ckb, fi, hi, id, ko, lo, nb, ro, sq, th) get the "Opening {name}…" string too; ATTRIBUTION.toml no longer records catalog hashes. --- crates/ui-egui/src/platform/open_worker/tests.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/ui-egui/src/platform/open_worker/tests.rs b/crates/ui-egui/src/platform/open_worker/tests.rs index c0fe2f03a2..b930297794 100644 --- a/crates/ui-egui/src/platform/open_worker/tests.rs +++ b/crates/ui-egui/src/platform/open_worker/tests.rs @@ -71,6 +71,10 @@ fn open_prepare_keeps_control_and_existing_tabs_live_until_atomic_commit() { let open_reply = request(&mut harness, &client, "ui.open", json!({ "path": path.to_string_lossy() })); assert_eq!(open_reply["pending"], true); started.recv_timeout(Duration::from_secs(5)).expect("worker reached prepare barrier"); + let name = path.file_name().expect("test path has a file name").to_string_lossy(); + let opening_label = format!("Opening {name}…"); + assert_eq!(harness.state().opening_notice.as_ref().map(|notice| notice.label.as_str()), Some(opening_label.as_str())); + harness.get_by_label(&opening_label); let state = request(&mut harness, &client, "ui.state", json!({})); assert_eq!(state["documents"].as_array().map(Vec::len), Some(1)); @@ -87,6 +91,8 @@ fn open_prepare_keeps_control_and_existing_tabs_live_until_atomic_commit() { assert_eq!(app.views.len(), 2, "one prepared document commits exactly once"); assert_eq!(app.session.get(app.views[1].id).expect("new tab").info.pages.len(), 2); assert_eq!(app.active, Some(1)); + assert!(app.opening_notice.is_none(), "the opening notice clears after commit"); + assert!(harness.query_by_label(&opening_label).is_none(), "the opening notice is no longer visible"); let _ = std::fs::remove_file(path); } From fb59affa415bfbfc0242118f8c1e27c2b60304ae Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 24 Oct 2026 01:44:58 +0000 Subject: [PATCH 19/30] M14: re-translate the opening notice after a language change A language change while an open was pending kept the notice in the previous language: the label was built once per pending open. The notice records its language and is rebuilt when the current language differs (CodeRabbit review). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VnaJBEsWwx1aCoDEMofbXs --- crates/ui-egui/src/platform/open_worker/tests.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/ui-egui/src/platform/open_worker/tests.rs b/crates/ui-egui/src/platform/open_worker/tests.rs index b930297794..669f9dfdc4 100644 --- a/crates/ui-egui/src/platform/open_worker/tests.rs +++ b/crates/ui-egui/src/platform/open_worker/tests.rs @@ -75,6 +75,14 @@ fn open_prepare_keeps_control_and_existing_tabs_live_until_atomic_commit() { let opening_label = format!("Opening {name}…"); assert_eq!(harness.state().opening_notice.as_ref().map(|notice| notice.label.as_str()), Some(opening_label.as_str())); harness.get_by_label(&opening_label); + // A language change while the open is pending re-translates the notice. + let language = std::mem::replace(&mut harness.state_mut().language, "ja".into()); + harness.step(); + let japanese_label = format!("{name} を開いています…"); + assert_eq!(harness.state().opening_notice.as_ref().map(|notice| notice.label.as_str()), Some(japanese_label.as_str())); + harness.state_mut().language = language; + harness.step(); + assert_eq!(harness.state().opening_notice.as_ref().map(|notice| notice.label.as_str()), Some(opening_label.as_str())); let state = request(&mut harness, &client, "ui.state", json!({})); assert_eq!(state["documents"].as_array().map(Vec::len), Some(1)); From fd6f7b602b07ec2a1f1f548c6aa280d49207dd1b Mon Sep 17 00:00:00 2001 From: CY Fung Date: Thu, 5 Nov 2026 21:35:30 +0000 Subject: [PATCH 20/30] M14: restore opening feedback on current UI structure --- crates/ui-egui/src/app.rs | 2 ++ crates/ui-egui/src/app/files.rs | 19 ++++++++++ crates/ui-egui/src/app/frame.rs | 2 ++ crates/ui-egui/src/lib.rs | 9 +++++ crates/ui-egui/src/widgets.rs | 63 ++++++++++++++++++++++++++++++++- 5 files changed, 94 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 04dbd19447..87f805e11f 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -143,6 +143,8 @@ impl PdfCraftApp { #[cfg(not(target_arch = "wasm32"))] pending_opens: Vec::new(), #[cfg(not(target_arch = "wasm32"))] + opening_notice: None, + #[cfg(not(target_arch = "wasm32"))] next_open_token: 0, #[cfg(not(target_arch = "wasm32"))] launch_layout: None, diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index c4d0a26c85..0a6820c7c8 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -120,9 +120,27 @@ impl PdfCraftApp { then: request.then, display_override: None, }); + self.refresh_opening_notice(); Ok(token) } + #[cfg(not(target_arch = "wasm32"))] + fn refresh_opening_notice(&mut self) { + let Some(pending) = self.pending_opens.first() else { + self.opening_notice = None; + return; + }; + let lang = i18n::current(); + if self.opening_notice.as_ref().is_some_and(|notice| notice.token == pending.token && notice.lang == lang) { + return; + } + self.opening_notice = Some(OpeningNotice { + token: pending.token, + lang, + label: i18n::fmt(tl!("Opening {name}…"), &[("name", &pending.name)]), + }); + } + #[cfg(not(target_arch = "wasm32"))] pub(crate) fn poll_pending_opens(&mut self) { let pending_opens = std::mem::take(&mut self.pending_opens); @@ -149,6 +167,7 @@ impl PdfCraftApp { // earlier waiting replies, without consuming a blocked receiver's result. waiting.append(&mut self.pending_opens); self.pending_opens = waiting; + self.refresh_opening_notice(); self.settle_launch_layout(); } diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 3d6f493e10..4802bfea09 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -3,6 +3,8 @@ use super::*; impl PdfCraftApp { /// Draw the running job's progress card and pass a Cancel click on to the job. pub(super) fn show_progress(&mut self, ctx: &egui::Context) { + #[cfg(not(target_arch = "wasm32"))] + widgets::opening_notice(self.opening_notice.as_ref().map(|notice| notice.label.as_str()), self.progress_notice.is_some(), ctx); if widgets::progress_notice(self, ctx) { self.cancel_optimize(); self.cancel_scan_clean(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 380f84a644..604eec3c15 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -254,6 +254,13 @@ struct PendingOpen { display_override: Option<(canvas::PageLayout, bool)>, } +#[cfg(not(target_arch = "wasm32"))] +struct OpeningNotice { + token: u64, + lang: i18n::Lang, + label: String, +} + pub struct PdfCraftApp { /// Tools side and pane widths; which panes are open is `left_open` and `right`. pub side_panels: side_panels::SidePanels, @@ -404,6 +411,8 @@ pub struct PdfCraftApp { #[cfg(not(target_arch = "wasm32"))] pending_opens: Vec, #[cfg(not(target_arch = "wasm32"))] + opening_notice: Option, + #[cfg(not(target_arch = "wasm32"))] next_open_token: u64, /// Explicit CLI layout waits for flagged launch opens, never targeting restored tabs. #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index f621c7832b..7d24a9af5f 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -17,6 +17,8 @@ const FIELD_MIN_HEIGHT: f32 = 30.0; /// Padding inside every modal. const DIALOG_PAD_X: i8 = 20; const DIALOG_PAD_Y: i8 = 16; +#[cfg(not(target_arch = "wasm32"))] +const OPENING_HEIGHT: &str = "opening-notice-height"; fn dialog_frame(ctx: &egui::Context) -> egui::Frame { let t = Tokens::get(ctx); @@ -476,7 +478,15 @@ pub fn toast(app: &mut PdfCraftApp, ctx: &egui::Context) { let screen = ctx.content_rect(); // Above the progress notice while a job runs. let card = if app.progress_notice.is_some() { ctx.data(|d| d.get_temp::(egui::Id::unique(PROGRESS_HEIGHT))).unwrap_or(0.0) } else { 0.0 }; - let lift = if card > 0.0 { 28.0 + card + 10.0 } else { 28.0 }; + #[cfg(not(target_arch = "wasm32"))] + let opening = if app.opening_notice.is_some() { + ctx.data(|d| d.get_temp::(egui::Id::new(OPENING_HEIGHT))).unwrap_or(0.0) + 10.0 + } else { + 0.0 + }; + #[cfg(target_arch = "wasm32")] + let opening = 0.0; + let lift = if card > 0.0 { 28.0 + card + 10.0 + opening } else { 28.0 + opening }; // A running batch keeps its toast up (poll_ocr re-notifies), so it can carry the one // control a long job needs: Cancel — the file in flight finishes, the rest are not run. let batch_running = app.ocr_batch.is_some(); @@ -610,6 +620,57 @@ pub fn progress_notice(app: &PdfCraftApp, ctx: &egui::Context) -> bool { cancel } +/// Draw the indeterminate opening card above the progress card, if any. +#[cfg(not(target_arch = "wasm32"))] +pub fn opening_notice(label: Option<&str>, progress_visible: bool, ctx: &egui::Context) { + let Some(label) = label else { + ctx.data_mut(|d| d.insert_temp(egui::Id::new(OPENING_HEIGHT), 0.0_f32)); + return; + }; + let t = Tokens::get(ctx); + let screen = ctx.content_rect(); + let (fill, text) = if t.dark() { + (Color32::from_rgb(0xEC, 0xEC, 0xEF), Color32::from_rgb(0x22, 0x22, 0x26)) + } else { + (Color32::from_rgb(0x2A, 0x2A, 0x2F), Color32::WHITE) + }; + let progress_height = if progress_visible { ctx.data(|d| d.get_temp::(egui::Id::unique(PROGRESS_HEIGHT))).unwrap_or(0.0) + 10.0 } else { 0.0 }; + let animated = crate::motion::animated(ctx); + let area = egui::Area::new(egui::Id::new("opening-notice")) + .order(egui::Order::Tooltip) + .pivot(Align2::CENTER_BOTTOM) + .fixed_pos(screen.center_bottom() - vec2(0.0, 28.0 + progress_height)) + .show(ctx, |ui| { + egui::Frame::NONE.fill(fill).corner_radius(CornerRadius::same(10)).inner_margin(egui::Margin::symmetric(16, 12)).show(ui, |ui| { + let width = 340.0_f32.min(screen.width() - 64.0).max(160.0); + ui.set_width(width); + ui.horizontal(|ui| { + let (rect, response) = ui.allocate_exact_size(vec2(18.0, 18.0), Sense::hover()); + response.widget_info(|| egui::WidgetInfo::new(egui::WidgetType::ProgressIndicator)); + let center = rect.center(); + let painter = ui.painter(); + if animated { + let now = ui.input(|i| i.time); + let phase = if now.is_finite() && now >= 0.0 { (now * 8.0).floor() as usize % 8 } else { 0 }; + for i in 0..8 { + let angle = std::f32::consts::TAU * i as f32 / 8.0; + let point = center + vec2(angle.cos() * 6.0, angle.sin() * 6.0); + let age = (phase + 8 - i) % 8; + painter.circle_filled(point, 1.5, text.gamma_multiply(0.2 + 0.8 * (1.0 - age as f32 / 8.0))); + } + } else { + painter.circle_stroke(center, 6.0, Stroke::new(1.5, text.gamma_multiply(0.7))); + } + ui.add(egui::Label::new(egui::RichText::new(label).color(text)).wrap()); + }); + }); + }); + ctx.data_mut(|d| d.insert_temp(egui::Id::new(OPENING_HEIGHT), area.response.rect.height())); + if animated { + ctx.request_repaint_after(std::time::Duration::from_millis(80)); + } +} + /// The ArtCraft wordmark (Storyteller's brand, docs/brand/; not open source), sized to `height`. pub fn artcraft_logo(ui: &mut egui::Ui, height: f32) -> Response { let dark = ui.visuals().dark_mode; From b8c44a5e7976b061510326a11114bb632089ab57 Mon Sep 17 00:00:00 2001 From: cyfung1031 <44498510+cyfung1031@users.noreply.github.com> Date: Fri, 6 Nov 2026 07:10:39 +0900 Subject: [PATCH 21/30] Fix opening indicator review comments --- crates/ui-egui/src/app/files.rs | 7 ++----- crates/ui-egui/src/platform/open_worker/tests.rs | 16 +++++++++------- crates/ui-egui/src/widgets.rs | 3 ++- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 0a6820c7c8..0b42a7c54b 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -134,11 +134,8 @@ impl PdfCraftApp { if self.opening_notice.as_ref().is_some_and(|notice| notice.token == pending.token && notice.lang == lang) { return; } - self.opening_notice = Some(OpeningNotice { - token: pending.token, - lang, - label: i18n::fmt(tl!("Opening {name}…"), &[("name", &pending.name)]), - }); + self.opening_notice = + Some(OpeningNotice { token: pending.token, lang, label: i18n::fmt(tl!("Opening {name}…"), &[("name", &pending.name)]) }); } #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/platform/open_worker/tests.rs b/crates/ui-egui/src/platform/open_worker/tests.rs index 669f9dfdc4..0650af2d47 100644 --- a/crates/ui-egui/src/platform/open_worker/tests.rs +++ b/crates/ui-egui/src/platform/open_worker/tests.rs @@ -75,13 +75,15 @@ fn open_prepare_keeps_control_and_existing_tabs_live_until_atomic_commit() { let opening_label = format!("Opening {name}…"); assert_eq!(harness.state().opening_notice.as_ref().map(|notice| notice.label.as_str()), Some(opening_label.as_str())); harness.get_by_label(&opening_label); - // A language change while the open is pending re-translates the notice. - let language = std::mem::replace(&mut harness.state_mut().language, "ja".into()); - harness.step(); - let japanese_label = format!("{name} を開いています…"); - assert_eq!(harness.state().opening_notice.as_ref().map(|notice| notice.label.as_str()), Some(japanese_label.as_str())); - harness.state_mut().language = language; - harness.step(); + // A language change while the open is pending re-translates the notice when catalogs exist. + if crate::i18n::needs_catalogs() { + let language = std::mem::replace(&mut harness.state_mut().language, "ja".into()); + harness.step(); + let japanese_label = format!("{name} を開いています…"); + assert_eq!(harness.state().opening_notice.as_ref().map(|notice| notice.label.as_str()), Some(japanese_label.as_str())); + harness.state_mut().language = language; + harness.step(); + } assert_eq!(harness.state().opening_notice.as_ref().map(|notice| notice.label.as_str()), Some(opening_label.as_str())); let state = request(&mut harness, &client, "ui.state", json!({})); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 7d24a9af5f..01b02ebf89 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -634,7 +634,8 @@ pub fn opening_notice(label: Option<&str>, progress_visible: bool, ctx: &egui::C } else { (Color32::from_rgb(0x2A, 0x2A, 0x2F), Color32::WHITE) }; - let progress_height = if progress_visible { ctx.data(|d| d.get_temp::(egui::Id::unique(PROGRESS_HEIGHT))).unwrap_or(0.0) + 10.0 } else { 0.0 }; + let progress_height = + if progress_visible { ctx.data(|d| d.get_temp::(egui::Id::unique(PROGRESS_HEIGHT))).unwrap_or(0.0) + 10.0 } else { 0.0 }; let animated = crate::motion::animated(ctx); let area = egui::Area::new(egui::Id::new("opening-notice")) .order(egui::Order::Tooltip) From 48cf60e055268f8606db0c7b01b5f89c912e15b1 Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Mon, 9 Nov 2026 11:19:33 +0800 Subject: [PATCH 22/30] M3: a bookmark's GoToE action is read as a link's is (view.follow-links) Main's bookmark actions (#5410) share Inspector::action_target with links, so the GoToE arm serves bookmarks too; the test now covers it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Pq7HyCHD1R3rywQBPCHXZA --- crates/render/src/inspect/tests.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/crates/render/src/inspect/tests.rs b/crates/render/src/inspect/tests.rs index 587572f093..91880e754d 100644 --- a/crates/render/src/inspect/tests.rs +++ b/crates/render/src/inspect/tests.rs @@ -1963,8 +1963,8 @@ fn outline_items_carry_their_colour_and_style() { /// A bookmark's action (`/A`, ISO 32000-2 §12.3.3 Table 151) is read as a link's is. Only a /// go-to's `/D` is a page of this document: a remote go-to's names a page or destination of the /// other file (§12.6.4.3), so `[0 /FitH 200]` there is not this file's first page. A web address, -/// another PDF and actions PdfCraft doesn't run are kept for the bookmark to run or report. An -/// action without a type is still read as the go-to its `/D` suggests. +/// another PDF, a PDF attached to this one (GoToE, §12.6.4.4) and actions PdfCraft doesn't run +/// are kept for the bookmark to run or report. An action without a type is still read as the go-to its `/D` suggests. #[test] fn bookmark_actions_are_read_as_links_read_them() { use DestView::*; @@ -1974,6 +1974,7 @@ fn bookmark_actions_are_read_as_links_read_them() { ("Other file", "/A << /S /GoToR /F (other.pdf) /D [0 /FitH 200] /NewWindow true >>"), ("Other file, named", "/A << /S /GoToR /F (other.pdf) /D (sec) >>"), ("Launch", "/A << /S /Launch /F (other.pdf) >>"), + ("Attached", "/A << /S /GoToE /T << /R /C /N (inner.pdf) >> /D [1 /Fit] >>"), ("Menu item", "/A << /S /Named /N /NextPage >>"), ("Script", "/A << /S /JavaScript /JS (app.alert\\(1\\)) >>"), ("No type", "/A << /D [3 0 R /Fit] >>"), @@ -2004,6 +2005,16 @@ fn bookmark_actions_are_read_as_links_read_them() { Top, Some(LinkTarget::RemoteGoTo { launch: true, file: "other.pdf".into(), destination: RemoteDestination::Default, new_window: None }) ), + ( + "Attached", + None, + Top, + Some(LinkTarget::EmbeddedGoTo { + source: AttachmentSource::Document { key: "inner.pdf".into() }, + destination: RemoteDestination::Page { page: 1, view: Fit }, + new_window: None + }) + ), ("Menu item", None, Top, Some(LinkTarget::Other("Named".into()))), ("Script", None, Top, Some(LinkTarget::Other("JavaScript".into()))), ("No type", Some(0), Fit, None), From 76d57c7c88fedd69bc8462f221ada4425583ab87 Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Tue, 10 Nov 2026 00:17:34 +0800 Subject: [PATCH 23/30] Re-run CI From fef44106b4e38e2376d7750ad477f1805b0ddcb4 Mon Sep 17 00:00:00 2001 From: CY Fung Date: Sat, 28 Nov 2026 01:46:37 +0000 Subject: [PATCH 24/30] Fix opening notice compilation after main sync --- crates/ui-egui/src/app/files.rs | 2 ++ crates/ui-egui/src/notices.rs | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 42369f9679..d6c3c93116 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -8,6 +8,8 @@ use craft::host::{FileFilter, PickRequest, Picked}; #[cfg(not(target_arch = "wasm32"))] use craft::platform::watch::FileStamp; use craft::ui::patterns::form_dialogs::{PasswordDialog, PasswordPurpose}; +#[cfg(not(target_arch = "wasm32"))] +use crate::OpeningNotice; /// Whether an open's reply asks for a password: the file is encrypted and none, or a wrong one, /// was given. diff --git a/crates/ui-egui/src/notices.rs b/crates/ui-egui/src/notices.rs index c8f08df440..13741cdfa6 100644 --- a/crates/ui-egui/src/notices.rs +++ b/crates/ui-egui/src/notices.rs @@ -179,7 +179,7 @@ fn show_opening(app: &PdfCraftApp, ui: &mut egui::Ui) { let toast_count = craft::ui::runtime::toast::cards(&ctx, &window).len(); let lift = (28.0 + toast_count as f32 * 120.0).min((screen.height() - 72.0).max(28.0)); - let _ = egui::Area::new(egui::Id::new("opening-notice")) + let _ = egui::Area::new(egui::Id::unique("opening-notice")) .order(egui::Order::Tooltip) .pivot(egui::Align2::CENTER_BOTTOM) .fixed_pos(screen.center_bottom() - egui::vec2(0.0, lift)) From 56593767826348b037215120664f9c9a63f40780 Mon Sep 17 00:00:00 2001 From: CY Fung Date: Sat, 28 Nov 2026 02:24:14 +0000 Subject: [PATCH 25/30] Fix opening notice UI assertion --- crates/ui-egui/src/app/files.rs | 4 ++-- crates/ui-egui/src/platform/open_worker/tests.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index d6c3c93116..5c57c55751 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -1,6 +1,8 @@ use super::{DocId, DocView, LeftPanel, Mode, PasswordPrompt, PdfCraftApp, RecentFile, RightPanel, UnlockPrompt, canvas, i18n}; #[cfg(not(target_arch = "wasm32"))] use super::{OpenOutcome, OpenRequest, PendingOpen, open_worker}; +#[cfg(not(target_arch = "wasm32"))] +use crate::OpeningNotice; use craft::docpath::names::safe_file_name; #[cfg(not(target_arch = "wasm32"))] use craft::host::queue::Priority; @@ -8,8 +10,6 @@ use craft::host::{FileFilter, PickRequest, Picked}; #[cfg(not(target_arch = "wasm32"))] use craft::platform::watch::FileStamp; use craft::ui::patterns::form_dialogs::{PasswordDialog, PasswordPurpose}; -#[cfg(not(target_arch = "wasm32"))] -use crate::OpeningNotice; /// Whether an open's reply asks for a password: the file is encrypted and none, or a wrong one, /// was given. diff --git a/crates/ui-egui/src/platform/open_worker/tests.rs b/crates/ui-egui/src/platform/open_worker/tests.rs index 46c5d49fea..9679bf8607 100644 --- a/crates/ui-egui/src/platform/open_worker/tests.rs +++ b/crates/ui-egui/src/platform/open_worker/tests.rs @@ -225,7 +225,7 @@ fn open_prepare_keeps_control_and_existing_tabs_live_until_atomic_commit() { assert_eq!(rig.jobs.waiting(), 1); let opening_label = format!("Opening {}…", file.name()); assert_eq!(rig.h.state().opening_notice.as_ref().map(|notice| notice.label.as_str()), Some(opening_label.as_str())); - assert!(rig.h.query_by_label(&opening_label).is_some()); + assert!(rig.notice_says(&opening_label)); if crate::i18n::needs_catalogs() { let language = std::mem::replace(&mut rig.h.state_mut().language, "ja".into()); rig.h.run_steps(1); @@ -251,7 +251,7 @@ fn open_prepare_keeps_control_and_existing_tabs_live_until_atomic_commit() { assert_eq!(app.session.get(app.views[1].id).expect("new tab").info.pages.len(), 2); assert_eq!(app.active, Some(1)); assert!(app.opening_notice.is_none(), "the opening notice clears after commit"); - assert!(rig.h.query_by_label(&opening_label).is_none(), "the opening notice is no longer visible"); + assert!(!rig.notice_says(&opening_label), "the opening notice is no longer visible"); } /// Picking a file for a tool must carry the tool through native preparation; another file From 08ed8b94ec543ec5bbc1910c021b0d0d0a4334c0 Mon Sep 17 00:00:00 2001 From: CY Fung Date: Sat, 28 Nov 2026 03:08:57 +0000 Subject: [PATCH 26/30] Announce opening notice as a status --- crates/ui-egui/src/notices.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/notices.rs b/crates/ui-egui/src/notices.rs index 13741cdfa6..eb58b8aa0f 100644 --- a/crates/ui-egui/src/notices.rs +++ b/crates/ui-egui/src/notices.rs @@ -8,7 +8,7 @@ #[cfg(not(target_arch = "wasm32"))] use craft::theme::variant::Tone; #[cfg(not(target_arch = "wasm32"))] -use craft::ui::contract::{Props as _, Show as _}; +use craft::ui::contract::{Politeness, Props as _, Show as _}; #[cfg(not(target_arch = "wasm32"))] use craft::ui::display::Spinner; #[cfg(not(target_arch = "wasm32"))] @@ -186,6 +186,7 @@ fn show_opening(app: &PdfCraftApp, ui: &mut egui::Ui) { .show(&ctx, |ui| { Notice::new(Tone::Neutral, notice.label.clone()) .layout(NoticeLayout::Toast) + .announce(Politeness::Polite) .content(Spinner::new().label(notice.label.clone()), |_| {}) .show(ui); }); From bb747187de2d06e209dd53cf9f991888e9515932 Mon Sep 17 00:00:00 2001 From: CY Fung Date: Sat, 28 Nov 2026 03:54:25 +0000 Subject: [PATCH 27/30] Advance UI frame before checking opening status --- crates/ui-egui/src/platform/open_worker/tests.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/platform/open_worker/tests.rs b/crates/ui-egui/src/platform/open_worker/tests.rs index 9679bf8607..1e0dcba7d5 100644 --- a/crates/ui-egui/src/platform/open_worker/tests.rs +++ b/crates/ui-egui/src/platform/open_worker/tests.rs @@ -225,6 +225,7 @@ fn open_prepare_keeps_control_and_existing_tabs_live_until_atomic_commit() { assert_eq!(rig.jobs.waiting(), 1); let opening_label = format!("Opening {}…", file.name()); assert_eq!(rig.h.state().opening_notice.as_ref().map(|notice| notice.label.as_str()), Some(opening_label.as_str())); + rig.h.run_steps(1); assert!(rig.notice_says(&opening_label)); if crate::i18n::needs_catalogs() { let language = std::mem::replace(&mut rig.h.state_mut().language, "ja".into()); From 96aec4a39829f96de90043cb6496519b324086db Mon Sep 17 00:00:00 2001 From: CY Fung Date: Sat, 28 Nov 2026 07:15:35 +0000 Subject: [PATCH 28/30] Document new helpers and tests --- crates/ui-egui/src/app/files.rs | 1 + crates/ui-egui/src/panels/comments_panel.rs | 2 ++ crates/ui-egui/tests/it/protect.rs | 1 + 3 files changed, 4 insertions(+) diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 5c57c55751..41e5b26f20 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -175,6 +175,7 @@ impl PdfCraftApp { } #[cfg(not(target_arch = "wasm32"))] + /// Updates the notice for the first pending native document, including its current language. fn refresh_opening_notice(&mut self) { let Some(pending) = self.pending_opens.first() else { self.opening_notice = None; diff --git a/crates/ui-egui/src/panels/comments_panel.rs b/crates/ui-egui/src/panels/comments_panel.rs index a290766444..09ab248275 100644 --- a/crates/ui-egui/src/panels/comments_panel.rs +++ b/crates/ui-egui/src/panels/comments_panel.rs @@ -453,6 +453,7 @@ mod tests { use super::*; + /// Builds a minimal annotation for comments-panel tests. fn mock_annotation(subtype: &str, intent: Option<&str>) -> Annotation { Annotation { page: 0, @@ -479,6 +480,7 @@ mod tests { } } + /// Checks that a freehand highlight annotation uses its localized kind label. #[test] fn freehand_highlight_kind_label() { let freehand = mock_annotation("Ink", Some("FreehandHighlight")); diff --git a/crates/ui-egui/tests/it/protect.rs b/crates/ui-egui/tests/it/protect.rs index 012dd986e3..49f9c67368 100644 --- a/crates/ui-egui/tests/it/protect.rs +++ b/crates/ui-egui/tests/it/protect.rs @@ -35,6 +35,7 @@ fn type_into(h: &mut Harness<'static, PdfCraftApp>, label: &str, text: &str) { h.run_steps(2); } +/// Sets the password pair through the Protect dialog's Advanced Options. fn open_password_pair(h: &mut Harness<'static, PdfCraftApp>, password: &str) { type_into(h, "Type Password", password); type_into(h, "Re-type Password", password); From 8636becdec2411359e978ada3c50ef568eaf72b2 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:58:47 +0700 Subject: [PATCH 29/30] ci: skip Windows clippy and debug info so a cold-cache Windows gate reaches its tests Clippy runs on Linux in cargo xtask ci, and its lints don't differ by platform. Debug info for every dependency made a cold-cache Windows gate spend its 90 minutes compiling (run 46775764634), so cargo test never started. Closes #9032 --- .github/workflows/ci.yml | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a1fb0bbc3d..0f33bde866 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -45,7 +45,12 @@ jobs: tools: cargo-nextest@0.9.150,cargo-deny@0.20.2 # A missing oracle fails the job instead of printing a skip notice that reads as a pass. linux-env: PDFCRAFT_ORACLES_REQUIRED=1 - windows-env: PDFCRAFT_REQUIRE_WINRES=1 + # One KEY=VALUE per line. No debug info on Windows: a cold-cache gate built it for every + # dependency and spent the 90-minute cap compiling before the tests started. + windows-env: | + PDFCRAFT_REQUIRE_WINRES=1 + CARGO_PROFILE_DEV_DEBUG=0 + CARGO_PROFILE_TEST_DEBUG=0 # Windows completed its 54m33s gate, then cache save hit the default 60m job cap # (run 44364342368). Leave bounded room for setup and post-job cleanup. # This changes no test watchdog or selection; craft-common-actions#60. @@ -54,7 +59,7 @@ jobs: command: | pwsh -NoProfile -File packaging/windows/test-font-notices.ps1 cargo xtask ci - # Windows checks what differs by platform: the build (with resources) and the tests. + # Windows checks what differs by platform: the build (with resources) and the tests. Clippy + # runs on Linux in `cargo xtask ci`; lints don't differ by platform. windows-command: | - cargo clippy --workspace --all-targets --locked -- -D warnings cargo test --workspace --locked From 2dd24dcdf93695af5187a8fa96e3fabcd03fb45d Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 2 Dec 2026 13:40:33 +0700 Subject: [PATCH 30/30] Format with rustfmt after the main merge Import lists in engine/src/lib.rs and session.rs reflow, and one blank line goes from the automation tests; no other change. --- crates/automation/tests/it/automation.rs | 1 - crates/engine/src/lib.rs | 3 +-- crates/engine/src/session.rs | 6 +++--- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index 7b86364164..149b966aa7 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -15583,7 +15583,6 @@ fn pdf_watermark_uses_visible_source_crop_through_tools() { } } - /// #3273: images became pages as large as their pixels, so a set of photos gave pages of several /// sizes and none of them paper. `page_size` puts them all on one sheet, scaled to fit. #[test] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 8d8efad592..ce8a728bd5 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -97,8 +97,7 @@ pub use pdfcraft_organize::view::{InitialView, Layout as InitialLayout, Magnific pub use pdfcraft_cos::{Algorithm, civil_from_days}; pub use pdfcraft_create::{ - CONVERTIBLE, CreateError, IMAGE_EXTENSIONS, ImagePage, ImageResolution, OFFICE_EXTENSIONS, SourceKind, TEXT_EXTENSIONS, decode_text, - source_kind, + CONVERTIBLE, CreateError, IMAGE_EXTENSIONS, ImagePage, ImageResolution, OFFICE_EXTENSIONS, SourceKind, TEXT_EXTENSIONS, decode_text, source_kind, }; pub use pdfcraft_edit::added::{ CHAR_SPACING_LIMIT as ADDED_CHAR_SPACING_LIMIT, paste_place as added_paste_place, paste_rect as added_paste_rect, text_rect as added_text_rect, diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 33b14770d4..a003af6fa4 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -10,9 +10,9 @@ use crate::check_refresh_panic; use crate::edit::{EditCtx, check_permission, run_edit}; use crate::history::{Keys, MAX_UNDO, Scope, keys_after, scope_of, uses_scripts}; use crate::{ - BookmarkPage, BookmarkRow, CombineSource, Combined, DataFormat, DocId, Document, Edit, EditError, Hairlines, HairlinesFixed, Hidden, - ImagePage, ImageResolution, LOW_RESOLUTION_PRINT_DPI, Label, ObjectKind, OptimizeReport, RecoverySnapshot, SignOptions, SourceKind, - SplitPart, StatusCaptions, SummarySort, TrustStore, XFA_REMOVED_PREFIX, XFA_SCRIPTS_OFF, apply_layer_state, carry_verdict_marks, comment_list, + BookmarkPage, BookmarkRow, CombineSource, Combined, DataFormat, DocId, Document, Edit, EditError, Hairlines, HairlinesFixed, Hidden, ImagePage, + ImageResolution, LOW_RESOLUTION_PRINT_DPI, Label, ObjectKind, OptimizeReport, RecoverySnapshot, SignOptions, SourceKind, SplitPart, + StatusCaptions, SummarySort, TrustStore, XFA_REMOVED_PREFIX, XFA_SCRIPTS_OFF, apply_layer_state, carry_verdict_marks, comment_list, comment_summary, decode_text, display_bytes, display_config, editor_signatures, guard, info_fields, js, local_utc_offset, note_warnings, office_to_pdf, open_source, open_source_with, optimize, outline_rows, parse_ymd, print, print_layer_states, print_raster, render_threads, scan_colours, set_default_layer_state, shown_under_redactions, source_kind, sync_xfa_state, undrawn_notices, use_layer_choices, writable, xfa,