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 1/6] 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 2/6] 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 3/6] 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 4/6] 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 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 5/6] 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 6/6] 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