diff --git a/crates/automation/src/dispatch.rs b/crates/automation/src/dispatch.rs index ceac61c01e..539feb0b26 100644 --- a/crates/automation/src/dispatch.rs +++ b/crates/automation/src/dispatch.rs @@ -401,7 +401,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 18ed24fdf7..e0b1e46e20 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -1718,7 +1718,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 f1ca84bb9c..dfef9d044e 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -14625,6 +14625,53 @@ 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])); +} + /// text_extract says when a page's text is incomplete because its content was cut at the /// renderer's limits (#623); a page read whole carries no such mark. #[test] diff --git a/crates/engine/src/copy_image.rs b/crates/engine/src/copy_image.rs index 3db00a28d2..057d6b1249 100644 --- a/crates/engine/src/copy_image.rs +++ b/crates/engine/src/copy_image.rs @@ -46,7 +46,7 @@ impl Document { self.page_images(page).iter().rposition(|i| { i.contains(at) && 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 f3d6ec098c..cf3b004ed8 100644 --- a/crates/engine/src/document.rs +++ b/crates/engine/src/document.rs @@ -80,6 +80,8 @@ pub struct Document { /// applied redactions left that still hold the removed text. 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..8cb93070c2 --- /dev/null +++ b/crates/engine/src/image_alpha.rs @@ -0,0 +1,257 @@ +//! 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, pictures that show nowhere 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; +/// 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)] +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, 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>>); + +#[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 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; + } + // 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, &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, &mut budget, mask, 1, key == b"Mask" || flag(cos, mask, b"ImageMask")) + { + return None; + } + } + 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(); + 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 rows = cells_covered(y, h, gh); + for x in 0..w { + if shows(x, y) { + // 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; + } + } + } + } + } + } + // 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 }) +} + +/// 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. 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 { + 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 }; + 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 +/// 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]; + 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 546858c3f2..1a669b2e27 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -34,6 +34,7 @@ pub mod field_table; mod fill_sign; pub mod find_replace; 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 516f138e77..a0b022354f 100644 --- a/crates/engine/src/open.rs +++ b/crates/engine/src/open.rs @@ -410,6 +410,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 1251eda327..d99266b412 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -11789,7 +11789,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(); @@ -11801,8 +11803,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 @@ -14520,6 +14524,234 @@ fn repeated_backdrop_artwork_survives_background_undo_redo_and_both_save_modes() 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 +} + +/// #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 +/// 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); +} + +/// `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])); +} + /// A form saved with its pages whose signature box sits deeper than the 32 nested fields looked /// through counts as signed, as the xfa crate counts it, so it is left as saved rather than laid /// out again over a signature that may be there; nested less deep, unsigned, it is laid out. diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 60feacff47..78f28bce15 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -988,8 +988,9 @@ fn page_parts_of(ui: &mut egui::Ui, body: &PageBody<'_>, session: &mut PageSessi } if cx.editing_content { if cx.tool == QuickTool::EditText && cx.can_modify { + let pointer = ui.input(|i| i.pointer.latest_pos()); for placed in body.pages { - parts.extend(crate::edit_text_ui::picture_parts(session, cx.doc, placed.page, placed, geo)); + parts.extend(crate::edit_text_ui::picture_parts(session, cx.doc, placed.page, placed, geo, pointer)); } } // A picture being cropped holds every press on its page: its paragraphs and added text take none there. 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 8928e6beef..c6954c406e 100644 --- a/crates/ui-egui/src/tools/edit_text_ui/image.rs +++ b/crates/ui-egui/src/tools/edit_text_ui/image.rs @@ -610,14 +610,18 @@ fn picture_change( } /// The parts of the pictures of `page`, in paint order so the topmost wins a press: a picture's -/// visible shape, and for the selected one its whole frame, a hole in it included. None while -/// the picture is cropped, whose crop overlay holds the page. +/// visible shape where it shows, and for the selected one its whole frame, a hole in it included. +/// None while the picture is cropped, whose crop overlay holds the page. +/// +/// A picture with transparency is picked only where it shows: with the pointer at `pointer` over +/// one of its see-through parts, it has no part this pass, so the press goes to what lies below. pub(crate) fn picture_parts( session: &PageSession, doc: &pdfcraft_engine::Document, page: usize, placed: &PlacedPage, geo: PageGeometry<'_>, + pointer: Option, ) -> Vec { let Some(xf) = session.page_xform(page, geo) else { return Vec::new() }; let selection = session.image_selection.as_ref().filter(|s| s.page == page); @@ -628,7 +632,7 @@ pub(crate) fn picture_parts( doc.page_images(page) .iter() .enumerate() - .map(|(index, image)| { + .filter_map(|(index, image)| { let quad = picture_quad(&xf, &doc.info, page, image); let visible = image.visible_rect.map(|r| xf.user_rect(&doc.info, page, r.map(|v| v as f32)).intersect(placed.rect)); let (shape, icon) = if selected == Some(index) { @@ -636,7 +640,13 @@ pub(crate) fn picture_parts( } else { (visible.map_or_else(|| HitShape::Polygon(quad.to_vec()), HitShape::Rect), CursorIcon::PointingHand) }; - PagePart::new(Owner::Picture { index }, page, shape, PageLayer::Picture).cursor(icon) + // Through a picture's transparent parts, the one below is picked (the selected one keeps its frame). + let see_through = selected != Some(index) + && pointer.is_some_and(|at| { + let (x, y) = screen_to_user(&xf, &doc.info, page, at); + shape.hit(at) && !doc.image_shows_at(image, [x, y]) + }); + (!see_through).then(|| PagePart::new(Owner::Picture { index }, page, shape, PageLayer::Picture).cursor(icon)) }) .collect() } diff --git a/crates/ui-egui/tests/it/editing.rs b/crates/ui-egui/tests/it/editing.rs index ed5f013721..aa290c7678 100644 --- a/crates/ui-egui/tests/it/editing.rs +++ b/crates/ui-egui/tests/it/editing.rs @@ -11647,6 +11647,83 @@ fn affine_review_cropped_rotation_preview_matches_saved_corners() { } } +/// 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. Once selected, a picture keeps its whole frame. +#[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 harness = || { + let bytes = bytes.clone(); + let mut h = Harness::builder().with_size(egui::vec2(900.0, 800.0)).build_eframe(move |cc| { + crate::support::install_runtime(&cc.egui_ctx); + let mut app = crate::control::new_app(); + app.set_option(&egui::Context::default(), "language", "en").unwrap(); + app.open_bytes(&egui::Context::default(), "overlap.pdf", None, bytes).unwrap(); + app + }); + h.run_steps(4); + assert!(h.execute("edit.edit_text")); + h.state_mut().views[0].view.fit = pdfcraft_ui_egui::canvas::Fit::Page; + h.run_steps(4); + h + }; + let click = |h: &mut Harness<'static, PdfCraftApp>, x: f32, y: f32| { + 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 v = info.user_to_view(x, y); + let p = page.min + egui::vec2(v[0], v[1]) * (page.width() / info.width); + h.hover_at(p); + h.run_steps(1); + h.drag_at(p); + h.run_steps(1); + h.drop_at(p); + h.run_steps(3); + h.state().views[0].session.image_selection.as_ref().map(|s| s.index) + }; + // With nothing selected: where the top picture shows, it is picked; through its transparent + // three quarters, the picture below is. + 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 mut h = harness(); + assert_eq!(click(&mut h, x, y), Some(want), "click at {x}, {y}"); + } + // The selected picture's frame is its own, its transparent parts included. + let mut h = harness(); + assert_eq!(click(&mut h, 150.0, 150.0), Some(1)); + assert_eq!(click(&mut h, 100.0, 100.0), Some(1), "the selected picture keeps its frame"); +} + /// The Escape that closes a dialog opened from a menu while a paragraph is being typed is the /// dialog's: the typing stays, in the open paragraph or applied to the page. It was thrown away. #[test] diff --git a/docs/editing-images.md b/docs/editing-images.md index 16a78f711a..2698cf9c35 100644 --- a/docs/editing-images.md +++ b/docs/editing-images.md @@ -43,7 +43,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 6b8d8b318a..0be6b7d8c9 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -2184,8 +2184,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", "crates/automation/tests/it/automation.rs::transforming_page_images_through_tools"] -notes = "existing raster images and grouped Form artwork: select, drag to move, 8-point handles to resize (corners keep proportions, edges scale along axis, Shift inverts aspect lock); Delete removes one placement. Headless: image_edit action move (a new box) or transform (any finite, non-flat 6-number matrix in top-left-origin points, applied after the placement: the edit a resize of a turned image makes). 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/automation/tests/it/automation.rs::transforming_page_images_through_tools", "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, 8-point handles to resize (corners keep proportions, edges scale along axis, Shift inverts aspect lock); Delete removes one placement. Headless: image_edit action move (a new box) or transform (any finite, non-flat 6-number matrix in top-left-origin points, applied after the placement: the edit a resize of a turned image makes). 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"