PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Fixes As Requested [WASM Build Failure, Clipping Path Destruction, Graphics State(opacity)]
Combiler010ca27d3145c7
diff --git a/crates/edit/src/images.rs b/crates/edit/src/images.rsindex b54ecd5bf..9b73dddac 100644--- a/crates/edit/src/images.rs+++ b/crates/edit/src/images.rs@@ -538,6 +538,109 @@ fn content_units(ops: &[Op], scan_start: usize, scan_end: usize) -> Vec<std::opsunits}+struct ExtractedScopeState {+ clip_ops: Vec<Op>,+ state_ops: Vec<Op>,+}++fn extract_scope_state(ops: &[Op], start: usize, target: usize) -> Result<Option<ExtractedScopeState>, EditError> {+ if start >= target || target >= ops.len() {+ return Ok(None);+ }+ 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 = Matrix::IDENTITY;+ 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 >= 256 {+ 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 }))+}+/// 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)?;@@ -649,34 +752,37 @@ pub fn arrange_image(doc: &mut Document, page: usize, index: usize, order: Arranfirst_op.span.start..last_op.span.end};- let is_clipped = img.visible_rect.is_some() && img.visible_rect != Some(img.rect);- if has_other_paint && is_clipped && img.clips.len() > 1 {- // Safely decline extraction when complex multi-path clipping cannot be preserved+ let scope_start = 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+ {+ sub_start+ } else {+ target_unit.start+ }+ } else {+ target_unit.start+ };++ let is_clipped = (img.visible_rect.is_some() && img.visible_rect != Some(img.rect)) || !img.clips.is_empty();++ let extracted = extract_scope_state(&ops, scope_start, target)?;+ let Some(extracted) = extracted else {+ return Ok(());+ };++ if is_clipped && extracted.clip_ops.is_empty() {return Ok(());}let mut unit_ops = Vec::new();unit_ops.push(Op::new("q", vec![]));- if is_clipped {+ if !extracted.clip_ops.is_empty() {if dest_ctm != Matrix::IDENTITY {unit_ops.push(Op::new("cm", dest_inv.0.map(pdfcraft_content::num).to_vec()));}- if let Some(clip) = img.visible_rect {- let cx0 = clip[0];- let cy0 = clip[1];- let cw = clip[2] - clip[0];- let ch = clip[3] - clip[1];- if cw > 0.0 && ch > 0.0 {- unit_ops.push(Op::new("re", vec![- pdfcraft_content::num(cx0),- pdfcraft_content::num(cy0),- pdfcraft_content::num(cw),- pdfcraft_content::num(ch),- ]));- unit_ops.push(Op::new("W", vec![]));- unit_ops.push(Op::new("n", 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()));}@@ -686,6 +792,7 @@ pub fn arrange_image(doc: &mut Document, page: usize, index: usize, order: Arranunit_ops.push(Op::new("cm", local.0.map(pdfcraft_content::num).to_vec()));}}+ unit_ops.extend(extracted.state_ops);unit_ops.push(ops.get(target).cloned().unwrap_or_else(|| Op::new("Do", vec![Object::name(&img.name)])));unit_ops.push(Op::new("Q", vec![]));diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rsindex af3c6c390..782cd3acd 100644--- a/crates/edit/src/tests.rs+++ b/crates/edit/src/tests.rs@@ -1846,6 +1846,46 @@ fn image_arrange_preserves_shared_group_clipping_bounds() {assert!(str_content.contains("External Text"), "external text preserved");}+#[test]+fn image_arrange_preserves_extended_graphics_state_opacity() {+ let content = "q /GS0 gs 100 0 0 100 50 50 cm /Im0 Do Q BT /F1 12 Tf 72 700 Td (External Text) Tj ET";+ let mut doc = image_page_with(content);+ let initial = images::page_images(&doc, 0).unwrap();+ assert_eq!(initial.len(), 1);+ assert_eq!(initial[0].rect, [50.0, 50.0, 150.0, 150.0]);++ images::arrange_image(&mut doc, 0, 0, images::ArrangeOrder::BringToFront).unwrap();+ let doc = reopen(&doc);+ let after = images::page_images(&doc, 0).unwrap();+ assert_eq!(after.len(), 1, "image preserved");+ assert_eq!(after[0].rect, [50.0, 50.0, 150.0, 150.0]);++ let bytes = page_content_bytes(&doc, 0);+ let str_content = String::from_utf8_lossy(&bytes);+ assert!(str_content.contains("/GS0 gs"), "extended graphics state /GS0 gs is retained");+ let gs_pos = str_content.rfind("/GS0 gs").unwrap();+ let do_pos = str_content.rfind("/Im0 Do").unwrap();+ assert!(gs_pos < do_pos, "/GS0 gs must precede /Im0 Do in the new unit");+}++#[test]+fn image_arrange_preserves_exact_non_rectangular_clipping_path() {+ let content = "q 120 120 m 160 120 l 140 160 l h W* n 100 0 0 100 100 100 cm /Im0 Do /Im0 Do Q BT /F1 12 Tf 72 700 Td (External Text) Tj ET";+ let mut doc = image_page_with(content);+ let initial = images::page_images(&doc, 0).unwrap();+ assert_eq!(initial.len(), 2);++ images::arrange_image(&mut doc, 0, 0, images::ArrangeOrder::BringToFront).unwrap();+ let doc = reopen(&doc);+ let after = images::page_images(&doc, 0).unwrap();+ assert_eq!(after.len(), 2, "both images preserved");++ let bytes = page_content_bytes(&doc, 0);+ let str_content = String::from_utf8_lossy(&bytes);+ assert!(str_content.contains("W*"), "even-odd W* fill rule must be preserved");+ assert!(str_content.contains("120 120 m 160 120 l 140 160 l h W* n"), "exact non-rectangular clip path preserved");+}+#[test]fn form_artwork_edits_only_the_selected_placement() {diff --git a/crates/ui-egui/src/content_ui.rs b/crates/ui-egui/src/content_ui.rsindex 186503220..70c03d0a1 100644--- a/crates/ui-egui/src/content_ui.rs+++ b/crates/ui-egui/src/content_ui.rs@@ -792,9 +792,10 @@ impl crate::PdfCraftApp {}#[cfg(not(target_arch = "wasm32"))]- let (has_system_cb, os_image_res) = if self.system_clipboard {+ let (has_system_cb, os_image) = if self.system_clipboard {if let Ok(mut cb) = arboard::Clipboard::new() {- (true, Some(cb.get_image()))+ let img_opt = cb.get_image().ok().map(|img| (img.width, img.height, img.bytes.to_vec()));+ (true, img_opt)} else {(false, None)}@@ -802,18 +803,18 @@ impl crate::PdfCraftApp {(false, None)};#[cfg(target_arch = "wasm32")]- let (has_system_cb, os_image_res): (bool, Option<Result<arboard::ImageData<'static>, arboard::Error>>) = (false, None);+ let (has_system_cb, os_image): (bool, Option<(usize, usize, Vec<u8>)>) = (false, None);let image_data: Option<(String, Vec<u8>)> = if has_system_cb {- match os_image_res {- Some(Ok(img)) => {+ match os_image {+ Some((width, height, bytes)) => {let matches_internal = self.last_copied_image.as_ref().is_some_and(|(w, h, rgba)| {- *w as usize == img.width && *h as usize == img.height && rgba.as_slice() == img.bytes.as_ref()+ *w as usize == width && *h as usize == height && rgba.as_slice() == bytes.as_slice()});- if matches_internal && let Some((name, bytes)) = self.last_copied_file.clone() {- Some((name, bytes))- } else if let Ok(png_bytes) = crate::create_ui::png_from_rgba(img.width, img.height, &img.bytes) {- self.last_copied_image = Some((img.width as u32, img.height as u32, img.bytes.to_vec()));+ if matches_internal && let Some((name, file_bytes)) = self.last_copied_file.clone() {+ Some((name, file_bytes))+ } else if let Ok(png_bytes) = crate::create_ui::png_from_rgba(width, height, &bytes) {+ self.last_copied_image = Some((width as u32, height as u32, bytes));self.last_copied_file = Some(("clipboard_image.png".to_string(), png_bytes.clone()));self.last_copied_image_rect = None;Some(("clipboard_image.png".to_string(), png_bytes))@@ -823,7 +824,7 @@ impl crate::PdfCraftApp {}// When system clipboard is active and accessible but contains text or non-image data:// Do NOT fall back to stale in-memory cached image!- _ => None,+ None => None,}} else if let Some((name, bytes)) = self.last_copied_file.clone() {Some((name, bytes))