PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Coderavbit Fixes
Combiler0187c1e858e334
diff --git a/crates/edit/src/images.rs b/crates/edit/src/images.rsindex b860348ac..63372a39d 100644--- a/crates/edit/src/images.rs+++ b/crates/edit/src/images.rs@@ -1477,18 +1477,8 @@ fn image_exclusive_scope(ops: &[Op], target: usize) -> Result<Option<(usize, usiOk(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>, bool), EditError> {+/// The scope `start..=end` without its private clipping paths and clipping `W n` sequences.+fn extract_image_drawing_ops(ops: &[Op], start: usize, end: usize) -> Result<(Vec<Op>, bool), EditError> {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 removed_clip = false;@@ -1524,10 +1514,10 @@ pub fn remove_image_crop(doc: &mut Document, page: usize, index: usize) -> Resulif !ops.get(target).is_some_and(|op| op.is("Do")) {return Err(EditError::Invalid("the image operation could not be located".into()));}- let Some((start, end, scope_matrix)) = image_exclusive_scope(&ops, target)? else {+ let Some((start, end, _)) = image_exclusive_scope(&ops, target)? else {return Err(EditError::Invalid("the image has no crop to remove".into()));};- let (drawing_ops, removed_clip) = extract_image_drawing_ops(&ops, start, end, target, scope_matrix, Matrix(img.draw_matrix))?;+ let (drawing_ops, removed_clip) = extract_image_drawing_ops(&ops, start, end)?;if !removed_clip {return Err(EditError::Invalid("the image has no crop to remove".into()));}diff --git a/crates/engine/src/pictures.rs b/crates/engine/src/pictures.rsindex d426fd9f3..48859bc52 100644--- a/crates/engine/src/pictures.rs+++ b/crates/engine/src/pictures.rs@@ -2,6 +2,8 @@use std::sync::Arc;+use image::ImageDecoder;+use crate::EditError;/// A picture for a watermark or background (Acrobat: Source ▸ File): an image, or `page`@@ -60,12 +62,72 @@ pub(crate) fn mark_source(doc: &mut pdfcraft_cos::Document, f: &MarkFile) -> Res/// The dimensions of an image from its bytes (JPEG, PNG, TIFF), without decoding the full raster.pub fn image_dimensions(bytes: &[u8]) -> Option<(u32, u32)> {+ if bytes.len() > 64_000_000 * 4 {+ return None;+ }let format = image::guess_format(bytes).ok()?;let mut reader = image::ImageReader::with_format(std::io::Cursor::new(bytes), format);let mut limits = image::Limits::default();limits.max_alloc = Some(64_000_000 * 4);reader.limits(limits);- let decoder = reader.into_decoder().ok()?;- let (w, h) = image::ImageDecoder::dimensions(&decoder);- if w == 0 || h == 0 { None } else { Some((w, h)) }+ let mut decoder = reader.into_decoder().ok()?;+ let (mut w, mut h) = image::ImageDecoder::dimensions(&decoder);+ if w == 0 || h == 0 {+ return None;+ }+ if format == image::ImageFormat::Jpeg+ && u64::from(w) * u64::from(h) <= (64 << 20)+ && let Ok(orientation) = decoder.orientation()+ && matches!(+ orientation,+ image::metadata::Orientation::Rotate90+ | image::metadata::Orientation::Rotate270+ | image::metadata::Orientation::Rotate90FlipH+ | image::metadata::Orientation::Rotate270FlipH+ )+ {+ std::mem::swap(&mut w, &mut h);+ }+ Some((w, h))+}++#[cfg(test)]+mod tests {+ use super::*;++ fn phone_jpeg(w: u32, h: u32, orientation: u8) -> Vec<u8> {+ use image::codecs::jpeg::JpegEncoder;+ let mut jpeg = Vec::new();+ let mut encoder = JpegEncoder::new(&mut jpeg);+ encoder.encode_image(&image::RgbImage::from_pixel(w, h, image::Rgb([20, 20, 20]))).expect("valid jpeg");+ let mut exif = b"Exif\0\0II\x2a\0\x08\0\0\0\x01\0\x12\x01\x03\0\x01\0\0\0".to_vec();+ exif.extend_from_slice(&[orientation, 0, 0, 0, 0, 0, 0, 0]);+ let mut out = jpeg[..2].to_vec();+ out.extend_from_slice(&[0xff, 0xe1]);+ out.extend_from_slice(&((exif.len() + 2) as u16).to_be_bytes());+ out.extend_from_slice(&exif);+ out.extend_from_slice(&jpeg[2..]);+ out+ }++ #[test]+ fn jpeg_exif_orientation_swaps_dimensions_for_quarter_turns() {+ let turned_6 = phone_jpeg(60, 20, 6);+ assert_eq!(image_dimensions(&turned_6), Some((20, 60)));++ let turned_8 = phone_jpeg(60, 20, 8);+ assert_eq!(image_dimensions(&turned_8), Some((20, 60)));++ let upright_1 = phone_jpeg(60, 20, 1);+ assert_eq!(image_dimensions(&upright_1), Some((60, 20)));+ }++ #[test]+ fn invalid_and_oversized_inputs_return_none() {+ assert_eq!(image_dimensions(&[]), None);+ assert_eq!(image_dimensions(b"not an image"), None);++ let huge = vec![0u8; 64_000_000 * 4 + 1];+ assert_eq!(image_dimensions(&huge), None);+ }}diff --git a/crates/ui-egui/src/editing.rs b/crates/ui-egui/src/editing.rsindex f6e43f8a6..52ec364e9 100644--- a/crates/ui-egui/src/editing.rs+++ b/crates/ui-egui/src/editing.rs@@ -198,7 +198,7 @@ impl PdfCraftApp {if let Some(view) = self.views.get_mut(i) {// A drawing whose annotation wasn't added must not stay painted.view.comments.drawings_refused();- if matches!(edit, Edit::EditPageImage { .. }) {+ if matches!(&edit, Edit::EditPageImage { change, .. } if !matches!(change, pdfcraft_engine::ImageEdit::Arrange(_))) {view.image_selection = None;}// A paragraph that couldn't be applied opens again with its typing, instead ofdiff --git a/crates/ui-egui/src/image_engine.rs b/crates/ui-egui/src/image_engine.rsindex 3dd8d817b..a1c4124ce 100644--- a/crates/ui-egui/src/image_engine.rs+++ b/crates/ui-egui/src/image_engine.rs@@ -1,7 +1,6 @@//! Image manipulation engine for non-destructive crop, anchor-based resize, and movement.//!-//! Ported and adapted from `Egui_image_resize_sandbox` with clean-room guarantees,-//! zero-panic safety, and lockstep pixel-scale invariance.+//! Contributor-original clean-room design with zero-panic safety and lockstep pixel-scale invariance.use egui::{Color32, CursorIcon, Pos2, Rect, Stroke, Vec2, pos2, vec2};diff --git a/crates/ui-egui/src/tools/content_ui.rs b/crates/ui-egui/src/tools/content_ui.rsindex fe45142dc..eff22d04d 100644--- a/crates/ui-egui/src/tools/content_ui.rs+++ b/crates/ui-egui/src/tools/content_ui.rs@@ -1054,7 +1054,12 @@ impl crate::PdfCraftApp {.last_copied_image.as_ref().map(|(w, h, _)| (*w as f64, *h as f64))- .or_else(|| pdfcraft_engine::image_dimensions(&bytes).map(|(w, h)| (w as f64, h as f64)))+ .or_else(|| {+ (bytes.len() <= 64_000_000 * 4)+ .then(|| pdfcraft_engine::image_dimensions(&bytes))+ .flatten()+ .map(|(w, h)| (w as f64, h as f64))+ }).unwrap_or((100.0, 100.0));let (pw, ph) =self.session.get(id).and_then(|d| d.info.pages.get(page)).map(|p| (p.width as f64, p.height as f64)).unwrap_or((612.0, 792.0));diff --git a/crates/ui-egui/tests/it/editing.rs b/crates/ui-egui/tests/it/editing.rsindex a9deb6771..16a81cb9f 100644--- a/crates/ui-egui/tests/it/editing.rs+++ b/crates/ui-egui/tests/it/editing.rs@@ -7510,6 +7510,17 @@ fn undo_arrange_re_resolves_image_selection_or_clears() {let sel_redo = h.state().views[0].image_selection.as_ref().expect("selection re-resolved after redo");assert_eq!(sel_redo.index, 1, "selection should point to FigA at index 1");assert_eq!(images_redo[sel_redo.index].name, "FigA");++ // Bringing to front when already at front is refused, but selection must be preserved+ let applied_again = h.state_mut().apply_edit(pdfcraft_engine::Edit::EditPageImage {+ page: 0,+ index: 1,+ change: pdfcraft_engine::ImageEdit::Arrange(pdfcraft_engine::ArrangeOrder::BringToFront),+ });+ assert!(!applied_again);+ h.run_steps(2);+ let sel_refused = h.state().views[0].image_selection.as_ref().expect("selection preserved after refused arrange");+ assert_eq!(sel_refused.index, 1);}/// #3061: a paragraph running past its page's bottom edge (an HTML converter relying on the