Skip to content

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

Merge remote-tracking branch 'upstream/main'

Combiler0191c575b1df51
diff --cc Cargo.lock
index e579e9d9f,47d73be44..5382cc84d
--- a/Cargo.lock
+++ b/Cargo.lock
@@@ -4392,9 -4392,9 +4394,10 @@@ dependencies =
"pdfcraft-platform",
"pdfcraft-render",
"pdfcraft-xfa",
+ "plist",
"png 0.18.1",
"pollster 1.0.1",
+ "proptest",
"rfd",
"rustix 1.1.5",
"serde",
diff --cc crates/edit/src/images.rs
index 7ed2fc239,6f14271be..058d94e08
--- a/crates/edit/src/images.rs
+++ b/crates/edit/src/images.rs
@@@ -9,28 -9,8 +9,29 @@@ use pdfcraft_cos::{Dict, Document, ObjR
use std::sync::Arc;
use crate::EditError;
+ use crate::text::content_streams;
+/// The identity of a soft mask (`/SMask`) in the PDF graphics state.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum MaskIdentity {
+ /// Indirect reference to a mask dictionary or stream.
+ Ref(u32, u16),
+ /// Indirect reference to the transparency group (`/G`) in a mask dictionary.
+ Group(u32, u16),
+ /// Explicit named mask or resource name.
+ Named(Vec<u8>),
+}
+
+impl std::fmt::Display for MaskIdentity {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ MaskIdentity::Ref(num, generation) => write!(f, "{num} {generation} R"),
+ MaskIdentity::Group(num, generation) => write!(f, "group {num} {generation} R"),
+ MaskIdentity::Named(name) => write!(f, "{}", String::from_utf8_lossy(name)),
+ }
+ }
+}
+
/// An image drawn on a page.
#[derive(Clone, Debug, PartialEq)]
pub struct PageImage {
@@@ -291,11 -227,9 +281,11 @@@ pub fn page_images(doc: &Document, page
let mut out = Vec::new();
// The streams are one stream in pieces, so the graphics state and operators carry over.
let mut state = ImageState::new(Matrix::IDENTITY, p.crop(doc), Vec::new());
+ let mut tracker = ExtendedGStateTracker::default();
- let pieces = joined(&streams(doc, &p.dict));
+ let pieces = joined(&content_streams(doc, &p.dict)?);
for (i, op) in pieces.parse().ops.iter().enumerate() {
state.apply(op)?;
+ tracker.step(op, &ext_gstates, doc, state.placement.matrix)?;
let ctm = state.placement.matrix;
if op.is("Do") {
let Some(name) = op.name(0) else { continue };
@@@ -551,900 -475,6 +547,900 @@@ fn clip_matrix(draw: Matrix, cm: Matrix
Some(outer.then(&t).then(&outer.invert()?))
}
+pub(crate) fn is_entire_page_wrapped(ops: &[Op]) -> bool {
+ if ops.len() < 2 || !ops.first().is_some_and(|o| o.is("q")) || !ops.last().is_some_and(|o| o.is("Q")) {
+ return false;
+ }
+ let mut depth: usize = 0;
+ for (i, op) in ops.iter().enumerate() {
+ if op.is("q") {
+ depth = depth.saturating_add(1);
+ } else if op.is("Q") {
+ depth = depth.saturating_sub(1);
+ if depth == 0 && i < ops.len().saturating_sub(1) {
+ return false;
+ }
+ }
+ }
+ depth == 0
+}
+
+pub(crate) fn content_units(ops: &[Op], scan_start: usize, scan_end: usize) -> Vec<std::ops::Range<usize>> {
+ let mut units = Vec::new();
+ let mut i = scan_start;
+ while i < scan_end {
+ let op = match ops.get(i) {
+ Some(o) => o,
+ None => break,
+ };
+ if op.is("BDC") || op.is("BMC") {
+ // A marked-content sequence is one unit up to its matching EMC (#3145), so Arrange moves
+ // it whole and never inserts into another one: its content belongs to its tag (ISO 32000-2
+ // § 14.6). An unbalanced sequence runs to the end of the scan.
+ let mut depth: usize = 1;
+ let mut j = i.saturating_add(1);
+ while j < scan_end {
+ if let Some(next) = ops.get(j) {
+ if next.is("BDC") || next.is("BMC") {
+ depth = depth.saturating_add(1);
+ } else if next.is("EMC") {
+ depth = depth.saturating_sub(1);
+ if depth == 0 {
+ j = j.saturating_add(1);
+ break;
+ }
+ }
+ }
+ j = j.saturating_add(1);
+ }
+ units.push(i..j);
+ i = j;
+ } else if op.is("q") {
+ let mut depth: usize = 1;
+ let mut j = i.saturating_add(1);
+ while j < scan_end {
+ if let Some(next) = ops.get(j) {
+ if next.is("q") {
+ depth = depth.saturating_add(1);
+ } else if next.is("Q") {
+ depth = depth.saturating_sub(1);
+ if depth == 0 {
+ j = j.saturating_add(1);
+ break;
+ }
+ }
+ }
+ j = j.saturating_add(1);
+ }
+ units.push(i..j);
+ i = j;
+ } else if op.is("BT") {
+ let mut j = i.saturating_add(1);
+ while j < scan_end {
+ if ops.get(j).is_some_and(|o| o.is("ET")) {
+ j = j.saturating_add(1);
+ break;
+ }
+ j = j.saturating_add(1);
+ }
+ units.push(i..j);
+ i = j;
+ } else if op.is("BI") {
+ let mut j = i.saturating_add(1);
+ while j < scan_end {
+ if ops.get(j).is_some_and(|o| o.is("EI")) {
+ j = j.saturating_add(1);
+ break;
+ }
+ j = j.saturating_add(1);
+ }
+ units.push(i..j);
+ i = j;
+ } else if op.is("Do") || op.is("sh") {
+ units.push(i..i.saturating_add(1));
+ i = i.saturating_add(1);
+ } else {
+ let mut j = i;
+ let mut found_end = false;
+ while j < scan_end {
+ let next = match ops.get(j) {
+ Some(o) => o,
+ None => break,
+ };
+ if matches!(next.op.as_slice(), b"S" | b"s" | b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*" | b"n") {
+ j = j.saturating_add(1);
+ found_end = true;
+ break;
+ } else if j > i && matches!(next.op.as_slice(), b"q" | b"BT" | b"BI" | b"Do" | b"sh" | b"BDC" | b"BMC") {
+ found_end = true;
+ break;
+ }
+ j = j.saturating_add(1);
+ }
+ let u_end = if found_end { j } else { scan_end };
+ units.push(i..u_end);
+ i = u_end;
+ }
+ }
+ units.retain(|u| {
+ ops.get(u.clone()).is_some_and(|slice| {
+ slice.iter().any(|op| {
+ matches!(
+ op.op.as_slice(),
+ b"Do" | b"sh" | b"BI" | b"S" | b"s" | b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*" | b"Tj" | b"TJ" | b"'" | b"\""
+ )
+ })
+ })
+ });
+ units
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub(crate) struct ExtractedScopeState {
+ pub clip_ops: Vec<Op>,
+ pub state_ops: Vec<Op>,
+ pub effective_cm: Matrix,
+ pub do_op: Op,
+}
+
+#[derive(Clone, Debug, Default, PartialEq)]
+struct EffectiveGState {
+ ca: Option<f64>,
+ ca_stroke: Option<f64>,
+ bm: Option<Vec<u8>>,
+ smask: Option<MaskIdentity>,
+}
+
+impl EffectiveGState {
+ fn effective_ca(&self) -> f64 {
+ self.ca.unwrap_or(1.0)
+ }
+
+ fn effective_ca_stroke(&self) -> f64 {
+ self.ca_stroke.unwrap_or(1.0)
+ }
+
+ fn effective_bm(&self) -> &[u8] {
+ self.bm.as_deref().unwrap_or(b"Normal")
+ }
+
+ fn effective_smask(&self) -> Option<&MaskIdentity> {
+ self.smask.as_ref()
+ }
+
+ fn visually_differs(&self, other: &EffectiveGState) -> bool {
+ (self.effective_ca() - other.effective_ca()).abs() > 1e-4
+ || (self.effective_ca_stroke() - other.effective_ca_stroke()).abs() > 1e-4
+ || self.effective_bm() != other.effective_bm()
+ || self.effective_smask() != other.effective_smask()
+ }
+
+ fn merge_dict(&mut self, dict: &Dict, doc: &Document, gs_name: Option<&[u8]>) {
+ if let Some(val) = dict.get(b"ca").map(|v| doc.resolve(v)).and_then(|v| v.as_f64()) {
+ self.ca = Some(val);
+ }
+ if let Some(val) = dict.get(b"CA").map(|v| doc.resolve(v)).and_then(|v| v.as_f64()) {
+ self.ca_stroke = Some(val);
+ }
+ if let Some(bm_obj) = dict.get(b"BM").map(|v| doc.resolve(v)) {
+ if let Some(name) = bm_obj.as_name() {
+ self.bm = Some(name.to_vec());
+ } else if let Some(arr) = bm_obj.as_array()
+ && let Some(first_name) = arr.first().map(|v| doc.resolve(v)).and_then(|v| v.as_name().map(|n| n.to_vec()))
+ {
+ self.bm = Some(first_name);
+ }
+ }
+ if let Some(raw_smask) = dict.get(b"SMask") {
+ let resolved = doc.resolve(raw_smask);
+ if let Some(name) = resolved.as_name() {
+ if name == b"None" {
+ self.smask = None;
+ } else {
+ self.smask = Some(MaskIdentity::Named(name.to_vec()));
+ }
+ } else if let Some(mask_dict) = resolved.as_dict() {
+ if let Some(gr) = mask_dict.get(b"G").and_then(|g| g.as_ref()) {
+ self.smask = Some(MaskIdentity::Group(gr.num, gr.generation));
+ } else if let Some(r) = raw_smask.as_ref() {
+ self.smask = Some(MaskIdentity::Ref(r.num, r.generation));
+ } else if let Some(name) = mask_dict.get(b"Name").map(|n| doc.resolve(n)).and_then(|n| n.as_name().map(|s| s.to_vec())) {
+ self.smask = Some(MaskIdentity::Named(name));
+ } else if let Some(name) = gs_name {
+ self.smask = Some(MaskIdentity::Named(name.to_vec()));
+ } else {
+ self.smask = Some(MaskIdentity::Named(b"CustomMask".to_vec()));
+ }
+ } else if let Some(r) = raw_smask.as_ref() {
+ self.smask = Some(MaskIdentity::Ref(r.num, r.generation));
+ }
+ }
+ }
+}
+
+#[derive(Clone, Default)]
+struct ExtendedGStateTracker {
+ stack: Vec<(EffectiveGState, Vec<(Op, Matrix)>)>,
+ current_state: EffectiveGState,
+ active_gs_ops: Vec<(Op, Matrix)>,
+}
+
+impl ExtendedGStateTracker {
+ fn step(&mut self, op: &Op, ext_gstates: &Dict, doc: &Document, ctm: Matrix) -> Result<(), EditError> {
+ match op.op.as_slice() {
+ b"q" => {
+ if self.stack.len() >= 4096 {
+ return Err(EditError::Invalid("the image graphics state is too deeply nested".into()));
+ }
+ self.stack.push((self.current_state.clone(), self.active_gs_ops.clone()));
+ }
+ b"Q" => {
+ if let Some((prev_state, prev_ops)) = self.stack.pop() {
+ self.current_state = prev_state;
+ self.active_gs_ops = prev_ops;
+ }
+ }
+ b"gs" => {
+ if let Some(name) = op.name(0) {
+ if let Some(dict) = ext_gstates.get(name).map(|v| doc.resolve(v)).and_then(|v| v.as_dict().cloned()) {
+ self.current_state.merge_dict(&dict, doc, Some(name));
+ }
+ self.active_gs_ops.retain(|(o, _)| o.name(0) != Some(name));
+ self.active_gs_ops.push((op.clone(), ctm));
+ }
+ }
+ _ => {}
+ }
+ Ok(())
+ }
+}
+
+fn clip_path_to_ops(clip: &ClipPath) -> Vec<Op> {
+ let mut ops = Vec::new();
+ let mut current_pt = Point::ZERO;
+ for el in clip.path.elements() {
+ match el {
+ kurbo::PathEl::MoveTo(p) => {
+ if !p.x.is_finite() || !p.y.is_finite() {
+ return Vec::new();
+ }
+ current_pt = *p;
+ ops.push(Op::new("m", vec![pdfcraft_content::num(p.x), pdfcraft_content::num(p.y)]));
+ }
+ kurbo::PathEl::LineTo(p) => {
+ if !p.x.is_finite() || !p.y.is_finite() {
+ return Vec::new();
+ }
+ current_pt = *p;
+ ops.push(Op::new("l", vec![pdfcraft_content::num(p.x), pdfcraft_content::num(p.y)]));
+ }
+ kurbo::PathEl::QuadTo(p1, p2) => {
+ if !p1.x.is_finite() || !p1.y.is_finite() || !p2.x.is_finite() || !p2.y.is_finite() {
+ return Vec::new();
+ }
+ let c1_x = current_pt.x + (p1.x - current_pt.x) * (2.0 / 3.0);
+ let c1_y = current_pt.y + (p1.y - current_pt.y) * (2.0 / 3.0);
+ let c2_x = p2.x + (p1.x - p2.x) * (2.0 / 3.0);
+ let c2_y = p2.y + (p1.y - p2.y) * (2.0 / 3.0);
+ if !c1_x.is_finite() || !c1_y.is_finite() || !c2_x.is_finite() || !c2_y.is_finite() {
+ return Vec::new();
+ }
+ current_pt = *p2;
+ ops.push(Op::new(
+ "c",
+ vec![
+ pdfcraft_content::num(c1_x),
+ pdfcraft_content::num(c1_y),
+ pdfcraft_content::num(c2_x),
+ pdfcraft_content::num(c2_y),
+ pdfcraft_content::num(p2.x),
+ pdfcraft_content::num(p2.y),
+ ],
+ ));
+ }
+ kurbo::PathEl::CurveTo(p1, p2, p3) => {
+ if !p1.x.is_finite() || !p1.y.is_finite() || !p2.x.is_finite() || !p2.y.is_finite() || !p3.x.is_finite() || !p3.y.is_finite() {
+ return Vec::new();
+ }
+ current_pt = *p3;
+ ops.push(Op::new(
+ "c",
+ vec![
+ pdfcraft_content::num(p1.x),
+ pdfcraft_content::num(p1.y),
+ pdfcraft_content::num(p2.x),
+ pdfcraft_content::num(p2.y),
+ pdfcraft_content::num(p3.x),
+ pdfcraft_content::num(p3.y),
+ ],
+ ));
+ }
+ kurbo::PathEl::ClosePath => {
+ ops.push(Op::new("h", vec![]));
+ }
+ }
+ }
+ if !ops.is_empty() {
+ ops.push(Op::new(if clip.even_odd { "W*" } else { "W" }, vec![]));
+ ops.push(Op::new("n", vec![]));
+ }
+ ops
+}
+
+pub(crate) fn extract_scope_state(ops: &[Op], start: usize, target: usize, initial_ctm: Matrix) -> Result<Option<ExtractedScopeState>, EditError> {
+ if target >= ops.len() || start > target {
+ return Ok(None);
+ }
+ let target_op = ops.get(target).cloned().ok_or_else(|| EditError::Invalid("the image operation is missing".into()))?;
+ if start == target {
+ return Ok(Some(ExtractedScopeState { clip_ops: Vec::new(), state_ops: Vec::new(), effective_cm: initial_ctm, do_op: target_op }));
+ }
+ let mut clip_ops = Vec::new();
+ let mut state_ops = Vec::new();
+ let mut pending_path: Vec<Op> = Vec::new();
+ let mut pending_clip = false;
+ let mut active_path = false;
+ let mut depth: usize = 0;
+ let mut matrix = initial_ctm;
+ let mut matrix_at_clip = None;
+
+ let scan_start = if ops.get(start).is_some_and(|o| o.is("q")) { start.saturating_add(1) } else { start };
+
+ for i in scan_start..target {
+ let Some(op) = ops.get(i) else {
+ return Ok(None);
+ };
+ match op.op.as_slice() {
+ b"q" => {
+ if depth >= 4096 {
+ return Err(EditError::Invalid("the image graphics state is too deeply nested".into()));
+ }
+ depth = depth.saturating_add(1);
+ }
+ b"Q" => {
+ if depth == 0 {
+ return Ok(None);
+ }
+ depth = depth.saturating_sub(1);
+ }
+ _ if depth > 0 => {}
+ b"cm" => {
+ if active_path {
+ return Ok(None);
+ }
+ if let Some(m) = op.nums::<6>() {
+ matrix = Matrix(m).then(&matrix);
+ }
+ }
+ b"m" | b"l" | b"c" | b"v" | b"y" | b"re" | b"h" => {
+ active_path = true;
+ pending_path.push(op.clone());
+ }
+ b"W" | b"W*" => {
+ if !active_path {
+ return Ok(None);
+ }
+ pending_clip = true;
+ pending_path.push(op.clone());
+ }
+ b"n" => {
+ if pending_clip {
+ if matrix_at_clip.is_none() {
+ matrix_at_clip = Some(matrix);
+ } else if matrix_at_clip != Some(matrix) {
+ return Ok(None);
+ }
+ clip_ops.extend(std::mem::take(&mut pending_path));
+ clip_ops.push(op.clone());
+ pending_clip = false;
+ active_path = false;
+ } else {
+ pending_path.clear();
+ active_path = false;
+ }
+ }
+ b"S" | b"s" | b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*" => {
+ if pending_clip {
+ return Ok(None);
+ }
+ pending_path.clear();
+ active_path = false;
+ }
+ b"gs" | b"CS" | b"cs" | b"SC" | b"sc" | b"SCN" | b"scn" | b"G" | b"g" | b"RG" | b"rg" | b"K" | b"k" | b"ri" | b"i" => {
+ state_ops.push(op.clone());
+ }
+ b"BT" => {
+ return Ok(None);
+ }
+ _ => {}
+ }
+ }
+
+ if depth != 0 || active_path || pending_clip {
+ return Ok(None);
+ }
+
+ if !clip_ops.is_empty() && matrix_at_clip != Some(Matrix::IDENTITY) {
+ return Ok(None);
+ }
+
+ Ok(Some(ExtractedScopeState { clip_ops, state_ops, effective_cm: matrix, do_op: target_op }))
+}
+
+/// Change the stacking order of image `index` on `page`.
+pub fn arrange_image(doc: &mut Document, page: usize, index: usize, order: ArrangeOrder) -> Result<(), EditError> {
+ let images = page_images(doc, page)?;
+ let img = images.get(index).cloned().ok_or_else(|| EditError::Invalid(format!("page {} has no image {}", page + 1, index + 1)))?;
+ let p = page_of(doc, page)?;
- let all = streams(doc, &p.dict);
++ let all = content_streams(doc, &p.dict)?;
+ let pieces = pdfcraft_content::Pieces::join(&all.iter().map(|(_, data)| data.as_slice()).collect::<Vec<_>>());
+ let ops = pieces.parse().ops;
+ let target = img.op;
+ if !ops.get(target).is_some_and(|op| op.is("Do")) {
+ return Err(EditError::Invalid("the image operation could not be located".into()));
+ }
+
+ let is_wrapped = is_entire_page_wrapped(&ops);
+ let (scan_start, scan_end) = if is_wrapped { (1, ops.len().saturating_sub(1)) } else { (0, ops.len()) };
+ let units = content_units(&ops, scan_start, scan_end);
+ let Some(target_idx) = units.iter().position(|u| u.start <= target && target < u.end) else {
+ return Err(EditError::Invalid("the image content unit could not be located".into()));
+ };
+ if units.len() <= 1 {
+ return Err(EditError::Invalid("the page has only one content unit to arrange".into()));
+ }
+
+ let (dest_unit, insert_after) = match order {
+ ArrangeOrder::BringToFront => {
+ if target_idx == units.len().saturating_sub(1) {
+ return Err(EditError::Invalid("the image is already in front".into()));
+ }
+ let Some(u) = units.last() else {
+ return Err(EditError::Invalid("the image is already in front".into()));
+ };
+ (u, true)
+ }
+ ArrangeOrder::SendToBack => {
+ if target_idx == 0 {
+ return Err(EditError::Invalid("the image is already at the back".into()));
+ }
+ let Some(u) = units.first() else {
+ return Err(EditError::Invalid("the image is already at the back".into()));
+ };
+ (u, false)
+ }
+ ArrangeOrder::BringForward => {
+ if target_idx == units.len().saturating_sub(1) {
+ return Err(EditError::Invalid("the image is already in front".into()));
+ }
+ let Some(u) = units.get(target_idx.saturating_add(1)) else {
+ return Err(EditError::Invalid("the image is already in front".into()));
+ };
+ (u, true)
+ }
+ ArrangeOrder::SendBackward => {
+ if target_idx == 0 {
+ return Err(EditError::Invalid("the image is already at the back".into()));
+ }
+ let Some(u) = target_idx.checked_sub(1).and_then(|i| units.get(i)) else {
+ return Err(EditError::Invalid("the image is already at the back".into()));
+ };
+ (u, false)
+ }
+ };
+
+ let Some(target_unit) = units.get(target_idx) else { return Ok(()) };
+ let has_other_paint = ops.iter().enumerate().any(|(i, op)| {
+ i >= target_unit.start
+ && i < target_unit.end
+ && i != target
+ && matches!(
+ op.op.as_slice(),
+ b"Do" | b"Tj" | b"TJ" | b"'" | b"\"" | b"sh" | b"BI" | b"S" | b"s" | b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*"
+ )
+ });
+
+ // A marked-content sequence that holds other content too moves only the image out of the
+ // sequence, wrapping it in its own tag at the destination so it is not grouped with the
+ // other content and leaves the remaining tagged content intact.
+ let marked_unit = ops.get(target_unit.start).is_some_and(|o| o.is("BDC") || o.is("BMC"));
+
+ let target_op = ops.get(target).ok_or_else(|| EditError::Invalid("the image operation could not be located".into()))?;
+ let (mut target_span, scope_start, rem_start, rem_end) = if has_other_paint {
+ if let Ok(Some((sub_start, sub_end, _))) = image_exclusive_scope(&ops, target)
+ && sub_start >= target_unit.start
+ && sub_end < target_unit.end
+ {
+ let start_op = ops.get(sub_start).unwrap_or(target_op);
+ let end_op = ops.get(sub_end).unwrap_or(target_op);
+ (start_op.span.start..end_op.span.end, sub_start, sub_start, sub_end.saturating_add(1))
+ } else {
+ (target_op.span.start..target_op.span.end, target, target, target.saturating_add(1))
+ }
+ } else if let Ok(Some((sub_start, sub_end, _))) = image_exclusive_scope(&ops, target)
+ && sub_start >= target_unit.start
+ && sub_end < target_unit.end
+ && !marked_unit
+ {
+ let start_op = ops.get(sub_start).unwrap_or(target_op);
+ let end_op = ops.get(sub_end).unwrap_or(target_op);
+ (start_op.span.start..end_op.span.end, sub_start, sub_start, sub_end.saturating_add(1))
+ } else if marked_unit {
+ // A marked-content unit holding only this image moves whole, with its BDC…EMC.
+ // The whole sequence is removed; the image's state is rebuilt from the ops inside it.
+ let Some(first_op) = ops.get(target_unit.start) else { return Ok(()) };
+ let Some(last_op) = target_unit.end.checked_sub(1).and_then(|i| ops.get(i)) else { return Ok(()) };
+ (first_op.span.start..last_op.span.end, target_unit.start.saturating_add(1).min(target), target_unit.start, target_unit.end)
+ } else {
+ let Some(first_op) = ops.get(target_unit.start) else { return Ok(()) };
+ let Some(last_op) = target_unit.end.checked_sub(1).and_then(|i| ops.get(i)) else { return Ok(()) };
+ (first_op.span.start..last_op.span.end, target_unit.start, target_unit.start, target_unit.end)
+ };
+
+ let (dest_pos, scan_target) = if insert_after {
+ let Some(op) = dest_unit.end.checked_sub(1).and_then(|i| ops.get(i)) else { return Ok(()) };
+ (op.span.end, dest_unit.end)
+ } else {
+ let Some(op) = ops.get(dest_unit.start) else { return Ok(()) };
+ (op.span.start, dest_unit.start)
+ };
+
+ let res = p.dict.get(b"Resources").map(|r| doc.resolve(r)).and_then(|r| r.as_dict().cloned()).unwrap_or_default();
+ let ext_gstates = res.get(b"ExtGState").map(|g| doc.resolve(g)).and_then(|g| g.as_dict().cloned()).unwrap_or_default();
+
+ let mut state = ImageState::new(Matrix::IDENTITY, p.crop(doc), Vec::new());
+ let mut tracker = ExtendedGStateTracker::default();
+ let mut source_effective_state = EffectiveGState::default();
+ let mut source_gs_ops = Vec::new();
+ let mut dest_effective_state = EffectiveGState::default();
+ let mut dest_ctm = Matrix::IDENTITY;
+ let mut scope_start_ctm = Matrix::IDENTITY;
+ let mut outer_clips = Vec::new();
+ let mut dest_clips = Vec::new();
+ let mut ctm_before_removal = Matrix::IDENTITY;
+ let mut ctm_after_removal = Matrix::IDENTITY;
+
+ let max_scan = scan_target.max(target.saturating_add(1)).max(scope_start.saturating_add(1)).max(rem_end);
+ for (i, op) in ops.iter().enumerate() {
+ if i == rem_start {
+ ctm_before_removal = state.placement.matrix;
+ }
+ if i == scope_start {
+ scope_start_ctm = state.placement.matrix;
+ outer_clips = state.placement.clips.clone();
+ }
+ if i == target {
+ source_effective_state = tracker.current_state.clone();
+ source_gs_ops = tracker.active_gs_ops.clone();
+ }
+ if i == scan_target {
+ dest_effective_state = tracker.current_state.clone();
+ dest_ctm = state.placement.matrix;
+ dest_clips = state.placement.clips.clone();
+ }
+ if i >= max_scan {
+ break;
+ }
+ state.apply(op)?;
+ tracker.step(op, &ext_gstates, doc, state.placement.matrix)?;
+ if i == rem_end.saturating_sub(1) {
+ ctm_after_removal = state.placement.matrix;
+ }
+ }
+ if scan_target >= ops.len() {
+ dest_effective_state = tracker.current_state.clone();
+ dest_ctm = state.placement.matrix;
+ dest_clips = state.placement.clips.clone();
+ }
+ if dest_ctm.invert().is_none() {
+ return Err(EditError::Invalid("unsupported graphics state: non-invertible CTM".into()));
+ }
+
+ let mut extracted = match extract_scope_state(&ops, scope_start, target, scope_start_ctm)? {
+ Some(ext) => ext,
+ None if scope_start != target => {
+ let target_op = ops.get(target).cloned().ok_or_else(|| EditError::Invalid("the image operation is missing".into()))?;
+ if !marked_unit || has_other_paint {
+ target_span = target_op.span.start..target_op.span.end;
+ }
+ extract_scope_state(&ops, target, target, Matrix(img.draw_matrix))?
+ .ok_or_else(|| EditError::Invalid("unsupported graphics state: unable to cleanly extract image scope state".into()))?
+ }
+ None => {
+ return Err(EditError::Invalid("unsupported graphics state: unable to cleanly extract image scope state".into()));
+ }
+ };
+
+ // The clips the moved unit draws itself: all of the image's when they are rebuilt from
+ // `img.clips`, else those its own scope set after the clips around it.
+ let all_clips = extracted.clip_ops.is_empty();
+ let reemitted = if all_clips {
+ img.clips.as_slice()
+ } else if img.clips.starts_with(&outer_clips) {
+ img.clips.get(outer_clips.len()..).unwrap_or_default()
+ } else {
+ return Err(EditError::Invalid("unsupported graphics state: the image clipping path cannot be cleanly preserved".into()));
+ };
+ // At the destination it is clipped by the clips there and the ones it draws. Moving past a
+ // clip the image isn't under (or out from under one it is) would change what part shows.
+ if !dest_clips.iter().all(|c| img.clips.contains(c)) || !img.clips.iter().all(|c| dest_clips.contains(c) || reemitted.contains(c)) {
+ return Err(EditError::Invalid(
+ "unsupported graphics state: moving the image past a clipping path would change what part of it shows".into(),
+ ));
+ }
+
+ if all_clips && !img.clips.is_empty() {
+ for clip in &img.clips {
+ let ops = clip_path_to_ops(clip);
+ if !ops.is_empty() {
+ extracted.clip_ops.extend(ops);
+ }
+ }
+ }
+
+ let has_inherited_clip = !img.clips.is_empty() && extracted.clip_ops.is_empty();
+ if has_inherited_clip {
+ return Err(EditError::Invalid("unsupported graphics state: inherited clipping path cannot be cleanly preserved".into()));
+ }
+
+ let non_gs_ops: Vec<Op> = extracted.state_ops.into_iter().filter(|o| !o.is("gs")).collect();
+
+ let mut reconstructed_state = dest_effective_state.clone();
+ for (op, _) in &source_gs_ops {
+ if let Some(name) = op.name(0)
+ && let Some(dict) = ext_gstates.get(name).map(|v| doc.resolve(v)).and_then(|v| v.as_dict().cloned())
+ {
+ reconstructed_state.merge_dict(&dict, doc, Some(name));
+ }
+ }
+
+ if reconstructed_state.visually_differs(&source_effective_state) {
+ return Err(EditError::Invalid(
+ "unsupported graphics state: moving the image would alter effective opacity, blend mode, or soft mask".into(),
+ ));
+ }
+
+ let mut unit_ops = Vec::new();
+ let marked_open = if marked_unit { ops.get(target_unit.start).cloned() } else { None };
+ if let Some(open) = &marked_open {
+ unit_ops.push(open.clone());
+ }
+ unit_ops.push(Op::new("q", vec![]));
+ let mut current_ctm = dest_ctm;
+
+ for (gs_op, target_ctm) in &source_gs_ops {
+ if *target_ctm != current_ctm {
+ let Some(current_inv) = current_ctm.invert() else {
+ return Err(EditError::Invalid("unsupported graphics state: non-invertible CTM".into()));
+ };
+ let delta = target_ctm.then(&current_inv);
+ if !delta.0.iter().all(|v| v.is_finite()) {
+ return Err(EditError::Invalid("unsupported graphics state: invalid transform coordinates".into()));
+ }
+ if delta != Matrix::IDENTITY {
+ unit_ops.push(Op::new("cm", delta.0.map(pdfcraft_content::num).to_vec()));
+ current_ctm = *target_ctm;
+ }
+ }
+ unit_ops.push(gs_op.clone());
+ }
+
+ unit_ops.extend(non_gs_ops);
+
+ if !extracted.clip_ops.is_empty() {
+ if current_ctm != Matrix::IDENTITY {
+ let Some(current_inv) = current_ctm.invert() else {
+ return Err(EditError::Invalid("unsupported graphics state: non-invertible CTM".into()));
+ };
+ unit_ops.push(Op::new("cm", current_inv.0.map(pdfcraft_content::num).to_vec()));
+ }
+ unit_ops.extend(extracted.clip_ops);
+ if Matrix(img.draw_matrix) != Matrix::IDENTITY {
+ unit_ops.push(Op::new("cm", img.draw_matrix.map(pdfcraft_content::num).to_vec()));
+ }
+ } else {
+ if Matrix(img.draw_matrix) != current_ctm {
+ let Some(current_inv) = current_ctm.invert() else {
+ return Err(EditError::Invalid("unsupported graphics state: non-invertible CTM".into()));
+ };
+ let delta = Matrix(img.draw_matrix).then(&current_inv);
+ if !delta.0.iter().all(|v| v.is_finite()) {
+ return Err(EditError::Invalid("unsupported graphics state: invalid transform coordinates".into()));
+ }
+ if delta != Matrix::IDENTITY {
+ unit_ops.push(Op::new("cm", delta.0.map(pdfcraft_content::num).to_vec()));
+ }
+ }
+ }
+ unit_ops.push(extracted.do_op);
+ unit_ops.push(Op::new("Q", vec![]));
+ // An unbalanced sequence had no EMC; it doesn't gain one.
+ if marked_open.is_some() && (has_other_paint || target_unit.end.checked_sub(1).and_then(|i| ops.get(i)).is_some_and(|o| o.is("EMC"))) {
+ unit_ops.push(Op::new("EMC", vec![]));
+ }
+
+ let mut serialized = Vec::new();
+ serialized.push(b'\n');
+ serialized.extend_from_slice(&serialize_ops(&unit_ops));
+ serialized.push(b'\n');
+
+ let leaking = if let Some(inv) = ctm_before_removal.invert() { ctm_after_removal.then(&inv) } else { Matrix::IDENTITY };
+ let removal_replacement = if leaking != Matrix::IDENTITY {
+ let leak_ops = vec![Op::new("cm", leaking.0.map(pdfcraft_content::num).to_vec())];
+ let mut s = Vec::new();
+ s.push(b'\n');
+ s.extend_from_slice(&serialize_ops(&leak_ops));
+ s.push(b'\n');
+ s
+ } else {
+ Vec::new()
+ };
+
+ let mut edits = Vec::new();
+ if dest_pos >= target_span.end {
+ edits.push((target_span, removal_replacement));
+ edits.push((dest_pos..dest_pos, serialized));
+ } else if dest_pos <= target_span.start {
+ edits.push((dest_pos..dest_pos, serialized));
+ edits.push((target_span, removal_replacement));
+ } else {
+ return Err(EditError::Invalid("no change in image stacking order".into()));
+ }
+
+ let changed = pieces.splice(edits);
+ let contents = crate::text::rewritten_contents(doc, &all, changed);
+ doc.update_dict(p.obj, |d| d.set(b"Contents".to_vec(), contents))?;
+ Ok(())
+}
+
+/// Locate the innermost graphics state scope enclosing only `target` (with no other painting operations).
+/// Returns `Some((start, end, scope_matrix))` where `start` is the index of `q`, `end` is the index of `Q`,
+/// and `scope_matrix` is the CTM in effect immediately before entering that `q`.
+fn image_exclusive_scope(ops: &[Op], target: usize) -> Result<Option<(usize, usize, Matrix)>, EditError> {
+ struct Scope {
+ start: usize,
+ matrix: Matrix,
+ inherited_clip: bool,
+ inherited_path: bool,
+ selected: bool,
+ other_paint: bool,
+ }
+ let mut stack: Vec<Scope> = Vec::new();
+ let mut matrix = Matrix::IDENTITY;
+ let mut clipped = false;
+ let mut path = false;
+ let mut pending_clip = false;
+ let mut text = false;
+ let mut at_image = None;
+ let mut isolated = None;
+ for (index, op) in ops.iter().enumerate() {
+ match op.op.as_slice() {
+ b"q" => {
+ if stack.len() >= 256 {
+ return Err(EditError::Invalid("the image graphics state is too deeply nested".into()));
+ }
+ stack.push(Scope { start: index, matrix, inherited_clip: clipped, inherited_path: path, selected: false, other_paint: false });
+ }
+ b"Q" => {
+ if let Some(scope) = stack.pop() {
+ if scope.selected && !scope.other_paint && !scope.inherited_clip && !scope.inherited_path {
+ isolated.get_or_insert((scope.start, index, scope.matrix));
+ }
+ matrix = scope.matrix;
+ clipped = scope.inherited_clip;
+ }
+ }
+ b"cm" => {
+ if let Some(m) = op.nums::<6>() {
+ matrix = Matrix(m).then(&matrix);
+ }
+ }
+ b"BT" => text = true,
+ b"ET" => text = false,
+ b"m" | b"l" | b"c" | b"v" | b"y" | b"re" => path = true,
+ b"W" | b"W*" => pending_clip = true,
+ _ => {}
+ }
+ if index == target {
+ if text {
+ return Err(EditError::Invalid("an image inside a text object cannot be cropped".into()));
+ }
+ at_image = Some(matrix);
+ for scope in &mut stack {
+ scope.selected = true;
+ }
+ } else if matches!(
+ op.op.as_slice(),
+ b"Do" | b"Tj" | b"TJ" | b"'" | b"\"" | b"sh" | b"BI" | b"S" | b"s" | b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*"
+ ) {
+ for scope in &mut stack {
+ scope.other_paint = true;
+ }
+ }
+ if matches!(op.op.as_slice(), b"n" | b"S" | b"s" | b"f" | b"F" | b"f*" | b"B" | b"B*" | b"b" | b"b*") {
+ clipped |= pending_clip;
+ pending_clip = false;
+ path = false;
+ }
+ }
+ if at_image.is_none() {
+ return Err(EditError::Invalid("the image operation is missing".into()));
+ }
+ Ok(isolated)
+}
+
+/// The scope `start..=end` without its clipping paths, for drawing in the CTM `scope_matrix`
+/// in effect before it. Its `cm`s go too, and one `cm` before the image `Do` at `target` puts
+/// it back at `draw`, so clips any earlier move put around it (`cm inverse`, path, `W n`,
+/// absolute `cm`) can't leave the image displaced.
+fn extract_image_drawing_ops(ops: &[Op], start: usize, end: usize, target: usize, scope_matrix: Matrix, draw: Matrix) -> Result<Vec<Op>, EditError> {
+ let inverse = scope_matrix.invert().ok_or_else(|| EditError::Invalid("unsupported graphics state: non-invertible CTM".into()))?;
+ let placement = draw.then(&inverse);
+ if !placement.0.iter().all(|v| v.is_finite()) {
+ return Err(EditError::Invalid("unsupported graphics state: invalid transform coordinates".into()));
+ }
+ let is_path = |o: &Op| matches!(o.op.as_slice(), b"m" | b"l" | b"c" | b"v" | b"y" | b"h" | b"re");
+ let mut drawing = Vec::new();
+ let mut i = start.saturating_add(1);
+ while i < end {
+ let Some(op) = ops.get(i) else { break };
+ if op.is("cm") {
+ i = i.saturating_add(1);
+ continue;
+ }
+ if is_path(op) {
+ let mut k = i;
+ while ops.get(k).is_some_and(is_path) {
+ k = k.saturating_add(1);
+ }
+ if ops.get(k).is_some_and(|o| o.is("W") || o.is("W*")) && ops.get(k.saturating_add(1)).is_some_and(|o| o.is("n")) {
+ i = k.saturating_add(2);
+ continue;
+ }
+ }
+ if i == target && placement != Matrix::IDENTITY {
+ drawing.push(Op::new("cm", placement.0.map(pdfcraft_content::num).to_vec()));
+ }
+ drawing.push(op.clone());
+ i = i.saturating_add(1);
+ }
+ Ok(drawing)
+}
+
+/// Remove any private clipping path / crop on image `index` on `page`.
+pub fn remove_image_crop(doc: &mut Document, page: usize, index: usize) -> Result<(), EditError> {
+ let images = page_images(doc, page)?;
+ let img = images.get(index).cloned().ok_or_else(|| EditError::Invalid(format!("page {} has no image {}", page + 1, index + 1)))?;
+ let p = page_of(doc, page)?;
- let all = streams(doc, &p.dict);
++ let all = content_streams(doc, &p.dict)?;
+ let pieces = pdfcraft_content::Pieces::join(&all.iter().map(|(_, data)| data.as_slice()).collect::<Vec<_>>());
+ let ops = pieces.parse().ops;
+ let target = img.op;
+ if !ops.get(target).is_some_and(|op| op.is("Do")) {
+ return Err(EditError::Invalid("the image operation could not be located".into()));
+ }
+ if let Some((start, end, scope_matrix)) = image_exclusive_scope(&ops, target)? {
+ let drawing_ops = extract_image_drawing_ops(&ops, start, end, target, scope_matrix, Matrix(img.draw_matrix))?;
+ let start_op = ops.get(start).ok_or_else(|| EditError::Invalid("the image operation is missing".into()))?;
+ let end_op = ops.get(end).ok_or_else(|| EditError::Invalid("the image operation is missing".into()))?;
+ let range = start_op.span.start..end_op.span.end;
+ let mut unit_ops = Vec::new();
+ unit_ops.push(Op::new("q", vec![]));
+ unit_ops.extend(drawing_ops);
+ unit_ops.push(Op::new("Q", vec![]));
+ let serialized = serialize_ops(&unit_ops);
+ let changed = pieces.splice([(range, serialized)]);
+ let contents = crate::text::rewritten_contents(doc, &all, changed);
+ doc.update_dict(p.obj, |d| d.set(b"Contents".to_vec(), contents))?;
+ }
+ Ok(())
+}
+
+/// Crop image `index` on `page` to `crop_rect` in user space `[x0, y0, x1, y1]`.
+pub fn crop_image(doc: &mut Document, page: usize, index: usize, crop_rect: [f64; 4]) -> Result<(), EditError> {
+ change_image(doc, page, index, &ImageChange::Crop(crop_rect))
+}
+
/// Change image `index` (from [`page_images`]) on `page`.
pub fn change_image(doc: &mut Document, page: usize, index: usize, change: &ImageChange) -> Result<(), EditError> {
let images = page_images(doc, page)?;
diff --cc crates/edit/src/tests.rs
index 62416b372,b1c463a6a..ec6cda76a
--- a/crates/edit/src/tests.rs
+++ b/crates/edit/src/tests.rs
@@@ -7152,153 -6354,220 +7152,369 @@@ fn reading_keeps_dotted_leader_entries_
"Ordinary body text. Still the same paragraph.",
]
);
+
+ #[cfg(test)]
+ mod proptests {
+ use super::*;
+ use proptest::prelude::*;
+
+ proptest! {
+
+ #[test]
+ fn prop_is_entire_page_wrapped_arbitrary_bytes(bytes in proptest::collection::vec(any::<u8>(), 0..2048)) {
+ let pieces = pdfcraft_content::Pieces::join(&[&bytes]);
+ let ops = pieces.parse().ops;
+ let _ = images::is_entire_page_wrapped(&ops);
+ }
+
+ #[test]
+ fn prop_content_units_arbitrary_bytes(
+ bytes in proptest::collection::vec(any::<u8>(), 0..2048),
+ start in 0usize..50,
+ end in 0usize..50,
+ ) {
+ let pieces = pdfcraft_content::Pieces::join(&[&bytes]);
+ let ops = pieces.parse().ops;
+ let scan_start = start.min(ops.len());
+ let scan_end = end.min(ops.len()).max(scan_start);
+ let units = images::content_units(&ops, scan_start, scan_end);
+ for u in units {
+ prop_assert!(u.start <= u.end);
+ prop_assert!(u.end <= ops.len());
+ }
+ }
+
+ #[test]
+ fn prop_arrange_image_arbitrary_malformed(
+ index in 0usize..10,
+ order_idx in 0u8..4,
+ bytes in proptest::collection::vec(any::<u8>(), 0..1024),
+ ) {
+ let order = match order_idx {
+ 0 => images::ArrangeOrder::BringToFront,
+ 1 => images::ArrangeOrder::SendToBack,
+ 2 => images::ArrangeOrder::BringForward,
+ _ => images::ArrangeOrder::SendBackward,
+ };
+ let mut doc = image_page_with(&String::from_utf8_lossy(&bytes));
+ let _ = images::arrange_image(&mut doc, 0, index, order);
+ }
+
+ #[test]
+ fn prop_crop_image_malformed_inputs(
+ x1 in -500.0f64..500.0,
+ y1 in -500.0f64..500.0,
+ x2 in -500.0f64..500.0,
+ y2 in -500.0f64..500.0,
+ bytes in proptest::collection::vec(any::<u8>(), 0..1024),
+ ) {
+ let mut doc = image_page_with(&String::from_utf8_lossy(&bytes));
+ let _ = images::crop_image(&mut doc, 0, 0, [x1, y1, x2, y2]);
+ let _ = images::remove_image_crop(&mut doc, 0, 0);
+ }
+ }
+ }
+}
+
+/// One 600×800 page: Im0 (4×2 gray image), Fm0 (200×100 Form), ExtGState GSone (ca 1).
+fn regression_page(content: &str) -> Document {
+ let form = "0 g 0 0 200 100 re f";
+ let objs: Vec<String> = vec![
+ "<< /Type /Catalog /Pages 2 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 600 800] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> /XObject << /Im0 6 0 R /Fm0 7 0 R >> /ExtGState << /GSone << /Type /ExtGState /ca 1 >> >> >> >>".into(),
+ format!("<< /Length {} >>\nstream\n{content}\nendstream", content.len()),
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".into(),
+ "<< /Type /XObject /Subtype /Image /Width 4 /Height 2 /ColorSpace /DeviceGray /BitsPerComponent 8 /Length 8 >>\nstream\n\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\u{0}\nendstream".into(),
+ format!("<< /Type /XObject /Subtype /Form /BBox [0 0 200 100] /Length {} >>\nstream\n{form}\nendstream", form.len()),
+ ];
+ let mut out = b"%PDF-1.7\n".to_vec();
+ let mut offs = Vec::new();
+ for (i, o) in objs.iter().enumerate() {
+ offs.push(out.len());
+ out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
+ }
+ let x = out.len();
+ out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
+ for o in offs {
+ out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
+ }
+ out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{x}\n%%EOF\n", objs.len() + 1).as_bytes());
+ Document::open(Arc::new(out)).unwrap()
+}
+
+fn regression_rects(doc: &Document) -> Vec<[i64; 4]> {
+ let mut v: Vec<[i64; 4]> = images::page_images(doc, 0).unwrap().iter().map(|i| i.rect.map(|x| x.round() as i64)).collect();
+ v.sort();
+ v
+}
+
+/// A `cm` inside a BDC…EMC unit applies to later content; arranging the unit must not shift anything.
+#[test]
+fn arrange_keeps_cm_leaking_out_of_marked_content() {
+ let mut doc = regression_page("/Figure <</MCID 0>> BDC 1 0 0 1 50 50 cm q 100 0 0 100 0 0 cm /Im0 Do Q EMC q 10 0 0 10 200 200 cm /Im0 Do Q");
+ let before = regression_rects(&doc);
+ images::arrange_image(&mut doc, 0, 0, images::ArrangeOrder::BringToFront).unwrap();
+ assert_eq!(before, regression_rects(&reopen(&doc)), "other content moved");
+}
+
+/// Cropping a Form XObject to 100×100 keeps a 100×100 visible area (or is refused) — never 1×1.
+#[test]
+fn crop_form_xobject_keeps_requested_area() {
+ let mut doc = regression_page("q 1 0 0 1 100 100 cm /Fm0 Do Q");
+ if images::crop_image(&mut doc, 0, 0, [100.0, 100.0, 200.0, 200.0]).is_err() {
+ return; // refusing to crop vector art is also acceptable
+ }
+ let after = images::page_images(&reopen(&doc), 0).unwrap()[0].clone();
+ let v = after.visible_rect.unwrap_or(after.rect);
+ assert!((v[2] - v[0] - 100.0).abs() < 1.0 && (v[3] - v[1] - 100.0).abs() < 1.0, "expected 100x100 visible, got {v:?}");
+}
+
+/// A gs naming a missing ExtGState must not be read as 50% opacity and block the reorder.
+#[test]
+fn arrange_tolerates_missing_extgstate() {
+ let mut doc = regression_page("q /GSmissing gs 100 0 0 100 50 50 cm /Im0 Do Q /GSone gs q 10 0 0 10 200 200 cm /Im0 Do Q");
+ let r = images::arrange_image(&mut doc, 0, 0, images::ArrangeOrder::BringToFront);
+ assert!(r.is_ok(), "{r:?}");
+}
+
+/// Bring to front on the image already in front must not report a change it didn't make.
+#[test]
+fn noop_arrange_is_not_ok_without_change() {
+ let mut doc = regression_page("q 10 0 0 10 200 200 cm /Im0 Do Q q 100 0 0 100 50 50 cm /Im0 Do Q");
+ let before = write_incremental(&doc, &SaveOptions::default()).unwrap();
+ let r = images::arrange_image(&mut doc, 0, 1, images::ArrangeOrder::BringToFront);
+ let after = write_incremental(&doc, &SaveOptions::default()).unwrap();
+ assert!(r.is_err() || before != after, "Ok with no change");
+}
+
+/// Cropping a turned image keeps the requested upright box in user space, rather than expanding
+/// to the bounding box of the turned image coordinates.
+#[test]
+fn crop_turned_image_preserves_requested_area() {
+ let mut doc = regression_page("q 70.71 70.71 -70.71 70.71 300 100 cm /Im0 Do Q");
+ let req = [270.0, 150.0, 330.0, 200.0];
+ images::crop_image(&mut doc, 0, 0, req).expect("crop succeeds");
+ let after = &images::page_images(&reopen(&doc), 0).unwrap()[0];
+ let v = after.visible_rect.expect("visible rect exists");
+ assert!((v[0] - req[0]).abs() < 1.0, "x0: expected {}, got {}", req[0], v[0]);
+ assert!((v[1] - req[1]).abs() < 1.0, "y0: expected {}, got {}", req[1], v[1]);
+ assert!((v[2] - req[2]).abs() < 1.0, "x1: expected {}, got {}", req[2], v[2]);
+ assert!((v[3] - req[3]).abs() < 1.0, "y1: expected {}, got {}", req[3], v[3]);
}
+
+ #[test]
+ fn added_text_is_wrapped_once_per_write() {
+ let mut doc = fixture();
+ let lines: Vec<String> = (0..40).map(|i| format!("line {i}")).collect();
+ let text = AddedText { rect: [72.0, 100.0, 300.0, 700.0], text: lines.join("\n"), size: 10.0, align: Align::Justify, ..AddedText::default() };
+ added::WRAP_CALLS.with(|c| c.set(0));
+ add_content(&mut doc, 0, &Content::Text(text)).unwrap();
+ let calls = added::WRAP_CALLS.with(std::cell::Cell::get);
+ assert!(calls <= 4, "the text was wrapped {calls} times for 40 lines");
+ }
+
+ /// A field tree whose every node lists its child twice is pruned in work linear in its nodes, not
+ /// in its paths, and a node listing itself is visited once.
+ #[test]
+ fn flattening_prunes_a_field_tree_with_repeated_kids_once_per_node() {
+ let levels = 16;
+ let page = stream("", " ");
+ // 5: the flattened widget; 6…: the chain; then the hidden widget at its end, on the page.
+ let leaf = 6 + levels;
+ let fields = format!("<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [5 0 R 6 0 R {} 0 R] >> >>", leaf + 2);
+ let annots = format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> /Contents 4 0 R /Annots [5 0 R {leaf} 0 R] >>");
+ let mut objs: Vec<String> = vec![
+ fields,
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
+ annots,
+ page,
+ format!("<< /Type /Annot /Subtype /Widget /FT /Tx /T (shown) /Rect [10 10 150 40] /F 4 /AP << /N {} 0 R >> >>", leaf + 1),
+ ];
+ for i in 0..levels {
+ let next = 7 + i;
+ objs.push(format!("<< /T (n{i}) /Kids [{next} 0 R {next} 0 R] >>"));
+ }
+ objs.push("<< /Type /Annot /Subtype /Widget /FT /Tx /T (hidden) /Rect [10 90 150 120] /F 2 >>".into());
+ objs.push("<< /Type /XObject /Subtype /Form /BBox [0 0 140 30] /Length 0 >>\nstream\n\nendstream".into());
+ objs.push(format!("<< /T (loop) /Kids [{} 0 R] >>", leaf + 2));
+ let objs: Vec<&str> = objs.iter().map(String::as_str).collect();
+ let mut doc = build(&objs);
+ flatten::KEEP_CALLS.with(|c| c.set(0));
+ assert_eq!(flatten(&mut doc, &[0], false, true).unwrap(), 1);
+ let calls = flatten::KEEP_CALLS.with(std::cell::Cell::get);
+ assert!(calls <= 2 * (levels + 4), "{calls} field-tree visits");
+ let root = doc.root().unwrap();
+ let af = doc.resolve(doc.get(root).as_dict().unwrap().get(b"AcroForm").unwrap());
+ let left = doc.resolve(af.as_dict().unwrap().get(b"Fields").unwrap()).as_array().unwrap().len();
+ assert_eq!(left, 2, "the chain to the hidden widget and the self-listing node stay");
+ }
+
+ /// A field reached first at the end of a long chain has its kids cut off by the depth limit, so
+ /// they survive there. A shorter path to the same field still looks at its kids: an off-page widget
+ /// under it is taken out when every field is flattened.
+ #[test]
+ fn a_field_reached_again_by_a_shorter_path_is_pruned_there() {
+ let chain = 64;
+ let page = stream("", " ");
+ // 7…: the chain; then the shared field, its off-page widget, and the short path to it.
+ let shared = 7 + chain;
+ let fields = format!("<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [5 0 R 7 0 R {} 0 R] >> >>", shared + 2);
+ let mut objs: Vec<String> = vec![
+ fields,
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> /Contents 4 0 R /Annots [5 0 R] >>".into(),
+ page,
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (shown) /Rect [10 10 150 40] /F 4 /AP << /N 6 0 R >> >>".into(),
+ "<< /Type /XObject /Subtype /Form /BBox [0 0 140 30] /Length 0 >>\nstream\n\nendstream".into(),
+ ];
+ for i in 0..chain {
+ objs.push(format!("<< /T (c{i}) /Kids [{} 0 R] >>", 8 + i));
+ }
+ objs.push(format!("<< /T (shared) /Kids [{} 0 R] >>", shared + 1));
+ objs.push("<< /Type /Annot /Subtype /Widget /FT /Tx /T (orphan) /Rect [10 50 150 80] /F 4 >>".into());
+ objs.push(format!("<< /T (short) /Kids [{shared} 0 R] >>"));
+ let objs: Vec<&str> = objs.iter().map(String::as_str).collect();
+ let mut doc = build(&objs);
+ assert_eq!(flatten(&mut doc, &[0], false, true).unwrap(), 1);
+ let shared_ref = pdfcraft_cos::ObjRef::new(u32::try_from(shared).unwrap(), 0);
+ let kids = doc.resolve(doc.get(shared_ref).as_dict().unwrap().get(b"Kids").unwrap()).as_array().unwrap().len();
+ assert_eq!(kids, 0, "the off-page widget is pruned along the short path");
+ }
+
+ /// A ToUnicode destination is repeated for every glyph that shows its code: a page whose text
+ /// would run past the extraction budget is refused, not built in memory.
+ #[test]
+ fn page_text_past_the_budget_is_refused() {
+ let cmap = stream("", &format!("1 beginbfchar <41> <{}> endbfchar", "0041".repeat(256)));
+ let page = |shown: &str| {
+ let content = stream("", &format!("BT /F1 12 Tf 10 10 Td ({shown}) Tj ET"));
+ build(&[
+ "<< /Type /Catalog /Pages 2 0 R >>",
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>",
+ &content,
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /ToUnicode 6 0 R >>",
+ &cmap,
+ ])
+ };
+ let doc = page(&"A".repeat(100_000));
+ assert!(matches!(text_lines(&doc, 0), Err(EditError::Invalid(_))), "25 MB of text from a 100 kB page");
+ let doc = page("AA");
+ assert_eq!(text_lines(&doc, 0).unwrap()[0].text.len(), 512, "a page within the budget still reads");
+ }
+
+ /// A one-page document from the page's /Contents and /Resources, built in code.
+ fn page_with(build: impl FnOnce(&mut Document) -> (Object, Dict)) -> Document {
+ let mut doc = Document::new_empty();
+ let pages = doc.add(Object::Null);
+ let (contents, resources) = build(&mut doc);
+ let page: Dict = [
+ (b"Type".to_vec(), Object::Name(b"Page".to_vec())),
+ (b"Parent".to_vec(), Object::Ref(pages)),
+ (b"MediaBox".to_vec(), Object::Array([0, 0, 200, 300].map(Object::from).to_vec())),
+ (b"Contents".to_vec(), contents),
+ (b"Resources".to_vec(), Object::Dict(resources)),
+ ]
+ .into_iter()
+ .collect();
+ let page = doc.add(page);
+ let tree: Dict = [
+ (b"Type".to_vec(), Object::Name(b"Pages".to_vec())),
+ (b"Kids".to_vec(), Object::Array(vec![Object::Ref(page)])),
+ (b"Count".to_vec(), Object::Int(1)),
+ ]
+ .into_iter()
+ .collect();
+ doc.set(pages, Object::Dict(tree));
+ let catalog: Dict = [(b"Type".to_vec(), Object::Name(b"Catalog".to_vec())), (b"Pages".to_vec(), Object::Ref(pages))].into_iter().collect();
+ let catalog = doc.add(catalog);
+ doc.trailer_mut().set(b"Root".to_vec(), Object::Ref(catalog));
+ doc
+ }
+
+ #[test]
+ fn repeated_content_references_share_one_decode_budget() {
+ // One 1 MiB stream (a kilobyte on disk) named 300 times by the page's /Contents.
+ let doc = page_with(|doc| {
+ let spaces = doc.add(Stream::flate(Dict::new(), &vec![b' '; 1 << 20]));
+ (Object::Array(vec![Object::Ref(spaces); 300]), Dict::new())
+ });
+ match text_lines(&doc, 0) {
+ Ok(lines) => panic!("read {} lines from more content than a page may decode", lines.len()),
+ Err(e) => assert!(matches!(e, EditError::Invalid(_)), "{e}"),
+ }
+ }
+
+ #[test]
+ fn reading_images_stops_at_the_page_record_limit() {
+ // 20 draws of a form drawing a form 20 times that draws an image 20 times: 8,000 images
+ // per level-two form, 160,000 in all, from a few hundred bytes.
+ let doc = page_with(|doc| {
+ let image: Dict = [
+ (b"Subtype".to_vec(), Object::Name(b"Image".to_vec())),
+ (b"Width".to_vec(), Object::Int(1)),
+ (b"Height".to_vec(), Object::Int(1)),
+ (b"ColorSpace".to_vec(), Object::Name(b"DeviceGray".to_vec())),
+ (b"BitsPerComponent".to_vec(), Object::Int(8)),
+ ]
+ .into_iter()
+ .collect();
+ let mut inner = doc.add(Stream::from_raw(image, vec![0]));
+ let draws = "/X Do ".repeat(20);
+ let resources = |inner: pdfcraft_cos::ObjRef| -> Dict {
+ let xobjects: Dict = [(b"X".to_vec(), Object::Ref(inner))].into_iter().collect();
+ [(b"XObject".to_vec(), Object::Dict(xobjects))].into_iter().collect()
+ };
+ for _ in 0..3 {
+ let mut d = resources(inner);
+ d = [(b"Subtype".to_vec(), Object::Name(b"Form".to_vec())), (b"Resources".to_vec(), Object::Dict(d))].into_iter().collect();
+ inner = doc.add(Stream::from_raw(d, draws.clone().into_bytes()));
+ }
+ let page = doc.add(Stream::from_raw(Dict::new(), draws.into_bytes()));
+ (Object::Ref(page), resources(inner))
+ });
+ if let Ok(images) = crate::reading_images(&doc, 0) {
+ assert!(images.len() <= crate::images::MAX_PAGE_IMAGES, "{} images", images.len());
+ }
+ }
+
+ #[test]
+ fn reading_spends_one_decode_budget_on_content_and_forms() {
+ // 130 MiB of content and a 130 MiB form (a kilobyte each on disk): each fits a page's budget,
+ // together they don't, so reading leaves the form out and says so.
+ let doc = page_with(|doc| {
+ let mut body = b"%".to_vec();
+ body.resize(130 << 20, b'x');
+ let form: Dict = [(b"Subtype".to_vec(), Object::Name(b"Form".to_vec()))].into_iter().collect();
+ let form = doc.add(Stream::flate(form, &body));
+ let mut content = b"/X Do\n%".to_vec();
+ content.resize(130 << 20, b'x');
+ let content = doc.add(Stream::flate(Dict::new(), &content));
+ let xobjects: Dict = [(b"X".to_vec(), Object::Ref(form))].into_iter().collect();
+ (Object::Ref(content), [(b"XObject".to_vec(), Object::Dict(xobjects))].into_iter().collect())
+ });
+ assert!(crate::text::reading_blocks_checked(&doc, 0).unwrap().truncated);
+ }
+
+ /// A page that can't take flattened content on top (marked content nested past the depth budget)
+ /// refuses the whole flatten: the pages before it keep their comments and content.
+ #[test]
+ fn a_flatten_refused_on_a_later_page_changes_nothing() {
+ let deep = stream("", &"/Artifact BMC\n".repeat(10_001));
+ let mut doc = build(&[
+ "<< /Type /Catalog /Pages 2 0 R >>",
+ "<< /Type /Pages /Kids [3 0 R 6 0 R] /Count 2 >>",
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> /Contents 4 0 R /Annots [5 0 R] >>",
+ &stream("", " "),
+ "<< /Type /Annot /Subtype /Square /Rect [10 10 50 50] /F 4 /AP << /N 9 0 R >> >>",
+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> /Contents 7 0 R /Annots [8 0 R] >>",
+ &deep,
+ "<< /Type /Annot /Subtype /Square /Rect [10 10 50 50] /F 4 /AP << /N 9 0 R >> >>",
+ "<< /Type /XObject /Subtype /Form /BBox [0 0 40 40] /Length 0 >>\nstream\n\nendstream",
+ ]);
+ let first = pdfcraft_cos::ObjRef::new(3, 0);
+ let before = (*doc.get(first)).clone();
+ assert!(matches!(flatten(&mut doc, &[0, 1], true, false), Err(EditError::Invalid(_))));
+ assert_eq!((*doc.get(first)).clone(), before, "the first page keeps its comment and content");
+ }
diff --cc crates/engine/src/tests.rs
index 93060a5c2,afe6fd06c..f712aa97e
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@@ -7241,86 -7284,48 +7291,132 @@@ fn exporting_office_keeps_dotted_leader
assert!(positions.windows(2).all(|pair| pair[0] < pair[1]), "reading order: {html}");
}
+ /// A page whose forms go past the reading limit and whose picture goes past the image budget is
+ /// listed once among the truncated pages.
+ #[test]
+ fn a_page_truncated_for_forms_and_pictures_is_listed_once() {
+ let depth = compare::MAX_FORM_DEPTH + 1;
+ let mut objs: Vec<String> = vec![
+ "<< /Type /Catalog /Pages 2 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 200] >>".into(),
+ String::new(),
+ "<< /Type /XObject /Subtype /Image /Width 2 /Height 2 /ColorSpace /DeviceGray /BitsPerComponent 8 /Length 4 >>\nstream\n\0\x20\x40\x7f\nendstream".into(),
+ "<< /Length 34 >>\nstream\nq 10 0 0 10 0 0 cm /Im Do Q /D1 Do\nendstream".into(),
+ ];
+ // Forms D1..D{depth}, objects 6 onwards, each drawing the next.
+ let xobjects: String = (1..=depth).map(|i| format!("/D{i} {} 0 R ", 5 + i)).collect();
+ let resources = format!("<< /XObject << /Im 4 0 R {xobjects}>> >>");
+ for i in 1..=depth {
+ let body = if i == depth { "q Q".to_string() } else { format!("/D{} Do", i + 1) };
+ objs.push(format!(
+ "<< /Type /XObject /Subtype /Form /BBox [0 0 200 200] /Resources {resources} /Length {} >>\nstream\n{body}\nendstream",
+ body.len()
+ ));
+ }
+ objs[2] = format!("<< /Type /Page /Parent 2 0 R /Contents 5 0 R /Resources {resources} >>");
+ 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{o}\nendobj\n", i + 1).as_bytes());
+ }
+ 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 s = Session::new();
+ let id = s.open("both.pdf", None, Arc::new(bytes), None).unwrap();
+ let doc = s.get(id).unwrap();
+ assert_eq!(doc.export_pages_checked(false, 0).1, [0], "the forms alone truncate the page");
+ let (exported, _) = doc.export_pages_checked(true, 1 << 20);
+ assert_eq!(exported[0].images.len(), 1, "the picture exports within a sufficient budget");
+ let (pages, truncated) = doc.export_pages_checked(true, 0);
+ assert!(pages[0].images.is_empty(), "the picture is past the budget");
+ assert_eq!(truncated, [0]);
+ }
++
+/// Moving an added image, then rotating it, must keep the moved position.
+#[test]
+fn added_image_move_then_rotate_keeps_position() {
+ let mut png = Vec::new();
+ {
+ let mut enc = png::Encoder::new(&mut png, 2, 2);
+ enc.set_color(png::ColorType::Rgb);
+ enc.write_header().unwrap().write_image_data(&[255u8; 12]).unwrap();
+ }
+ let (mut s, id) = session_with(1);
+ s.apply(id, Edit::AddImage { page: 0, rect: Some([20.0, 20.0, 60.0, 60.0]), name: "p.png".into(), bytes: Arc::new(png) }).unwrap();
+ let rect = |s: &Session| s.get(id).unwrap().page_images(0)[0].rect;
+ s.apply(id, Edit::EditPageImage { page: 0, index: 0, change: ImageEdit::Move([120.0, 120.0, 160.0, 160.0]) }).unwrap();
+ let moved = rect(&s);
+ s.apply(id, Edit::EditPageImage { page: 0, index: 0, change: ImageEdit::Rotate(1) }).unwrap();
+ let rotated = rect(&s);
+ let c = |r: [f64; 4]| ((r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0);
+ let (a, b) = (c(moved), c(rotated));
+ assert!((a.0 - b.0).abs() < 1.0 && (a.1 - b.1).abs() < 1.0, "rotate moved the centre from {a:?} to {b:?}");
+}
+
+/// Transforming an added image, then rotating it, must keep the moved position.
+#[test]
+fn added_image_transform_then_rotate_keeps_position() {
+ let mut png = Vec::new();
+ {
+ let mut enc = png::Encoder::new(&mut png, 2, 2);
+ enc.set_color(png::ColorType::Rgb);
+ enc.write_header().unwrap().write_image_data(&[255u8; 12]).unwrap();
+ }
+ let (mut s, id) = session_with(1);
+ s.apply(id, Edit::AddImage { page: 0, rect: Some([20.0, 20.0, 60.0, 60.0]), name: "p.png".into(), bytes: Arc::new(png) }).unwrap();
+ let rect = |s: &Session| s.get(id).unwrap().page_images(0)[0].rect;
+ // Translate by (100, 100): matrix [1, 0, 0, 1, 100, 100]
+ s.apply(id, Edit::EditPageImage { page: 0, index: 0, change: ImageEdit::Transform([1.0, 0.0, 0.0, 1.0, 100.0, 100.0]) }).unwrap();
+ let transformed = rect(&s);
+ s.apply(id, Edit::EditPageImage { page: 0, index: 0, change: ImageEdit::Rotate(1) }).unwrap();
+ let rotated = rect(&s);
+ let c = |r: [f64; 4]| ((r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0);
+ let (a, b) = (c(transformed), c(rotated));
+ assert!((a.0 - b.0).abs() < 1.0 && (a.1 - b.1).abs() < 1.0, "rotate moved the centre from {a:?} to {b:?}");
+}
+
+/// Moving an added image, then rotating by degrees, must keep the moved position.
+#[test]
+fn added_image_move_then_rotate_by_keeps_position() {
+ let mut png = Vec::new();
+ {
+ let mut enc = png::Encoder::new(&mut png, 2, 2);
+ enc.set_color(png::ColorType::Rgb);
+ enc.write_header().unwrap().write_image_data(&[255u8; 12]).unwrap();
+ }
+ let (mut s, id) = session_with(1);
+ s.apply(id, Edit::AddImage { page: 0, rect: Some([20.0, 20.0, 60.0, 60.0]), name: "p.png".into(), bytes: Arc::new(png) }).unwrap();
+ let rect = |s: &Session| s.get(id).unwrap().page_images(0)[0].rect;
+ s.apply(id, Edit::EditPageImage { page: 0, index: 0, change: ImageEdit::Move([120.0, 120.0, 160.0, 160.0]) }).unwrap();
+ let moved = rect(&s);
+ s.apply(id, Edit::EditPageImage { page: 0, index: 0, change: ImageEdit::RotateBy(90.0) }).unwrap();
+ let rotated = rect(&s);
+ let c = |r: [f64; 4]| ((r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0);
+ let (a, b) = (c(moved), c(rotated));
+ assert!((a.0 - b.0).abs() < 1.0 && (a.1 - b.1).abs() < 1.0, "rotate_by moved the centre from {a:?} to {b:?}");
+}
+
+/// Arranging an added image moves it into the document stream and converts it to an ordinary
+/// page image (dropping the PCAdded marker), so no empty shell remains in list_added.
+#[test]
+fn added_image_arrange_converts_to_ordinary_image() {
+ let mut png = Vec::new();
+ {
+ let mut enc = png::Encoder::new(&mut png, 2, 2);
+ enc.set_color(png::ColorType::Rgb);
+ enc.write_header().unwrap().write_image_data(&[255u8; 12]).unwrap();
+ }
+ let (mut s, id) = session_with(1);
+ s.apply(id, Edit::AddImage { page: 0, rect: Some([20.0, 20.0, 60.0, 60.0]), name: "p1.png".into(), bytes: Arc::new(png.clone()) }).unwrap();
+ s.apply(id, Edit::AddImage { page: 0, rect: Some([100.0, 100.0, 200.0, 200.0]), name: "p2.png".into(), bytes: Arc::new(png) }).unwrap();
+ assert_eq!(s.get(id).unwrap().page_images(0).len(), 2);
+ assert_eq!(s.get(id).unwrap().added().len(), 2);
+ s.apply(id, Edit::EditPageImage { page: 0, index: 1, change: ImageEdit::Arrange(ArrangeOrder::SendToBack) }).unwrap();
+ assert_eq!(s.get(id).unwrap().page_images(0).len(), 2);
+ assert_eq!(s.get(id).unwrap().added().len(), 1, "arranged image is converted and no longer an added-item shell");
+}