PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Fix mixed-order TIFF type transforms and reject unsafe geometry
Sean Laveryec56c286ddf2
diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rsindex 1e77cdaa6..aa599aa07 100644--- a/crates/io/src/psd_import.rs+++ b/crates/io/src/psd_import.rs@@ -4,7 +4,7 @@ use std::sync::Arc;use photocraft_color::{BlendMode, ColorMode, PixelFormat, SampleType};use photocraft_doc::{- AlphaChannel, Document, Effects, FillCache, Group, Layer, LayerContent, LayerMask, ShapeLayer, SmartContentsId, SmartObject, SmartSource, TextLayer,+ AlphaChannel, Document, Effects, FillCache, Group, Layer, LayerContent, LayerMask, ShapeLayer, SmartContentsId, SmartObject, SmartSource,};use photocraft_geom::{Rect, Size, TILE_SIZE};use photocraft_psd::layer::{CHANNEL_REAL_USER_MASK, CHANNEL_TRANSPARENCY, CHANNEL_USER_MASK};@@ -341,28 +341,26 @@ impl Ctx<'_> {));}LayerContent::Adjustment(adj)- } else if rec.block(b"TySh").is_some() {- // Typed model from TySh/EngineData (photocraft-text); Photoshop's pixels stay the cache.- let data = rec.block(b"TySh").map(|b| b.data.clone()).unwrap_or_default();- let mut t = photocraft_text::psd::text_layer_from_tysh(&data, self.dpi).unwrap_or_else(|| {- let (text, transform) = blocks::parse_tysh(&data).unwrap_or_default();- TextLayer { text, transform, ..Default::default() }- });- if let Some(txt2) = &self.txt2 {- photocraft_text::psd::apply_txt2(&mut t, &data, txt2);- photocraft_text::psd::apply_txt2_frame(&mut t, &data, txt2);+ } else if let Some(block) = rec.block(b"TySh") {+ // Only canonical, safely decoded type data can become editable text. A retained+ // foreign-order block must never be handed to the big-endian reader (#4758).+ let parsed = (!block.is_foreign_order()).then(|| photocraft_text::psd::text_layer_from_tysh(&block.data, self.dpi)).flatten();+ if let Some(mut t) = parsed {+ if let Some(txt2) = &self.txt2 {+ photocraft_text::psd::apply_txt2(&mut t, &block.data, txt2);+ photocraft_text::psd::apply_txt2_frame(&mut t, &block.data, txt2);+ }+ // Photoshop's pixels stay until edited. Writers without type pixels are+ // rendered by text_import::prepare instead of retaining an empty cache.+ let cache = self.record_surface(rec, &name);+ let drawn = !cache.content_bounds().is_empty() || photocraft_text::psd::engine_text_is_blank(&block.data);+ t.cache = drawn.then_some(cache);+ t.psd_raw = principal(b"TySh");+ LayerContent::Text(t)+ } else {+ self.warn(format!("layer \"{name}\": unreadable or unsafe type geometry; kept as pixels with its original type data"));+ LayerContent::Raster(self.record_surface(rec, &name))}- // Photoshop's pixels are the cache only when the file has some: ag-psd, GIMP and- // other writers leave type layers without image data (Photoshop re-renders them on- // open), and an empty cache would show nothing until the layer is edited; the import- // renders such a layer from its model instead (`text_import::prepare`). When the- // engine text itself is blank, Photoshop draws nothing either: keep the empty pixels- // (corpus: text/path-wave-open.psd).- let cache = self.record_surface(rec, &name);- let drawn = !cache.content_bounds().is_empty() || photocraft_text::psd::engine_text_is_blank(&data);- t.cache = drawn.then_some(cache);- t.psd_raw = principal(b"TySh");- LayerContent::Text(t)} else if let Some(k) = smart_key {let Placement { id, transform, perspective, warp } = match rec.block(k) {Some(b) if k == b"PlLd" => self.plld_placement(&b.data, &name),diff --git a/crates/io/tests/psd_structure.rs b/crates/io/tests/psd_structure.rsindex e893adaf9..44d6d33c4 100644--- a/crates/io/tests/psd_structure.rs+++ b/crates/io/tests/psd_structure.rs@@ -422,9 +422,11 @@ fn text_and_smart_detected() {use photocraft_psd::{LayerRecord, TaggedBlock};let mut f = testgen::small(Version::Psd, Compression::Raw);for (name, key) in [("t", b"TySh"), ("s", b"PlLd"), ("sh", b"vscg")] {+ // Type identification needs readable type data, not an eight-byte malformed stub.+ let data = if key == b"TySh" { photocraft_text::psd::build_tysh(&photocraft_doc::TextLayer::default(), 72.0, None) } else { vec![0; 8] };f.layers_mut().push(LayerRecord {name: name.as_bytes().to_vec(),- blocks: vec![TaggedBlock::unicode_name(name), TaggedBlock::new(*key, vec![0; 8])],+ blocks: vec![TaggedBlock::unicode_name(name), TaggedBlock::new(*key, data)],..Default::default()});}diff --git a/crates/io/tests/psd_type_bounds.rs b/crates/io/tests/psd_type_bounds.rsindex 8fabe8be2..a80bc9b7a 100644--- a/crates/io/tests/psd_type_bounds.rs+++ b/crates/io/tests/psd_type_bounds.rs@@ -367,7 +367,21 @@ fn hostile_type_sizes_without_pixels_import_without_a_huge_render() {{let runs = vec![Run { len: 1, size, leading: None }];let data = tysh("M", &runs, None, transform, [10.0, 10.0, 20.0, 20.0]);- let mut t = photocraft_text::psd::text_layer_from_tysh(&data, 72.0).unwrap();+ let Some(mut t) = photocraft_text::psd::text_layer_from_tysh(&data, 72.0) else {+ // Unsafe affine data is now rejected at the boundary (#4758). Exercise the+ // actual file import too: with no saved pixels it must remain empty and safe.+ let mut file = photocraft_psd::testgen::small(photocraft_psd::Version::Psd, photocraft_psd::Compression::Raw);+ file.layers_mut().push(photocraft_psd::LayerRecord {+ name: b"hostile".to_vec(),+ blocks: vec![photocraft_psd::TaggedBlock::new(*b"TySh", data)],+ ..Default::default()+ });+ let back = photocraft_io::import("t.psd", &file.to_bytes().unwrap()).unwrap();+ assert!(back.warnings.iter().any(|w| w.contains("unsafe type geometry")));+ let LayerContent::Raster(pixels) = &back.document.layers.last().unwrap().content else { panic!("unsafe type must stay pixels") };+ assert!(pixels.content_bounds().is_empty());+ continue;+ };if big {// Precondition: the renderer's own guard (256 Mpx) would have drawn this one.let mut engine = photocraft_text::TextEngine::new();diff --git a/crates/io/tests/tiff_type_geometry.rs b/crates/io/tests/tiff_type_geometry.rsnew file mode 100644index 000000000..a64aeb7c2--- /dev/null+++ b/crates/io/tests/tiff_type_geometry.rs@@ -0,0 +1,69 @@+//! Photoshop's mixed-order Intel TIFF type blocks and unsafe/unresolved type fallback (#4758).++use photocraft_color::{ColorMode, SampleType};+use photocraft_doc::text::{CharStyle, TextRun};+use photocraft_doc::{Document, Layer, LayerContent, Size, TextLayer};+use photocraft_geom::Affine;+use photocraft_io::{ExportOptions, PsdExportOptions, document_to_psd_with, export, import, psd_to_document};++fn document() -> Document {+ let mut doc = Document::new("Synthetic type", Size::new(640, 400), ColorMode::Rgb, SampleType::U8);+ doc.resolution_dpi = 300.0;+ let mut t = TextLayer {+ text: "Synthetic".into(),+ transform: Affine { m: [1.8054202887117468, 0.0, -0.143, 1.8063853899082987, 40.0, 120.0] },+ ..Default::default()+ };+ t.runs = vec![TextRun { len: t.text.len(), style: CharStyle { size_pt: 24.0, ..Default::default() } }];+ t.sync_summary();+ t.cache = Some(photocraft_text::TextEngine::default().render(&t, doc.resolution_dpi, doc.pixel_format()).1.surface);+ doc.layers.push(Layer::new("Synthetic", LayerContent::Text(t)));+ doc+}++#[test]+fn photoshop_mixed_order_tiff_import_keeps_editable_geometry_and_pixels() {+ let doc = document();+ let (psd, _) = document_to_psd_with(&doc, &PsdExportOptions::default());+ let canonical = &psd.layers()[0].block(b"TySh").unwrap().data;+ let encoded = export(&doc, "test.tif", &ExportOptions { tiff_layers: true, ..Default::default() }).unwrap();+ let mut image = photocraft_codecs::decode(&encoded.bytes).unwrap();+ let blocks = image.meta.photoshop_layers.as_mut().unwrap();+ let at = blocks.windows(8).position(|b| b == b"MIB8hSyT").unwrap() + 12;+ // Only the text version/descriptor switch order; warp and bounds remain little-endian.+ let (_, used) = photocraft_psd::descriptor::VersionedDescriptor::parse_prefix(&canonical[52..]).unwrap();+ blocks[at + 50..at + 52 + used].copy_from_slice(&canonical[50..52 + used]);+ let bytes = photocraft_codecs::encode(&image, photocraft_codecs::Format::Tiff, &Default::default()).unwrap();+ let opened = import("photoshop.tif", &bytes).unwrap();+ assert!(!opened.warnings.iter().any(|w| w.contains("TySh")), "{:?}", opened.warnings);+ let LayerContent::Text(before) = &doc.layers[0].content else { panic!("source type") };+ let LayerContent::Text(after) = &opened.document.layers[0].content else { panic!("imported type") };+ assert_eq!(after.transform, before.transform);+ assert_eq!(after.size_pt, 24.0);+ assert_eq!(after.text, before.text);+ assert_eq!(after.cache.as_ref().unwrap().content_bounds(), before.cache.as_ref().unwrap().content_bounds());+ let rerendered = photocraft_text::TextEngine::default().render(after, opened.document.resolution_dpi, opened.document.pixel_format()).1.surface;+ assert_eq!(rerendered.content_bounds(), after.cache.as_ref().unwrap().content_bounds());+}++#[test]+fn foreign_or_unsafe_type_keeps_cached_pixels_without_editable_geometry() {+ let doc = document();+ for foreign in [true, false] {+ let (mut psd, _) = document_to_psd_with(&doc, &PsdExportOptions::default());+ let block = psd.layer_info.as_mut().unwrap().layers[0].blocks.iter_mut().find(|b| b.key == *b"TySh").unwrap();+ if foreign {+ // A foreign-order marker must be respected even if the descriptor could parse.+ block.signature = *b"MIB8";+ } else {+ block.data[2..10].copy_from_slice(&1.315776645269349e62f64.to_be_bytes());+ }+ let raw = block.data.clone();+ let (opened, warnings) = psd_to_document(&psd);+ let LayerContent::Raster(pixels) = &opened.layers[0].content else { panic!("unsafe type must stay pixels") };+ assert!(!pixels.content_bounds().is_empty());+ assert_eq!(pixels.content_bounds(), doc.layers[0].surface().unwrap().content_bounds());+ assert!(warnings.iter().any(|w| w.contains("unsafe type geometry")), "{warnings:?}");+ assert!(opened.layers[0].psd_blocks.iter().any(|(k, data)| k == b"TySh" && **data == raw));+ }+}diff --git a/crates/psd/src/tiff.rs b/crates/psd/src/tiff.rsindex 7c8b1940d..8bdebd13a 100644--- a/crates/psd/src/tiff.rs+++ b/crates/psd/src/tiff.rs@@ -845,15 +845,7 @@ pub mod transcode {// Type: version, transform, text version + descriptor, warp version + descriptor,// and the bounds as four 32-bit values (the specification says doubles; Photoshop// writes 16 bytes).- b"TySh" => {- self.u16()?;- self.f64s(6)?;- self.u16()?;- self.versioned_descriptor()?;- self.u16()?;- self.versioned_descriptor()?;- self.i32s(4)?;- }+ b"TySh" => self.type_layer()?,b"vmsk" | b"vsms" => {self.u32()?;self.u32()?;@@ -1151,6 +1143,31 @@ pub mod transcode {// ---- descriptors ----+ /// Photoshop's Intel-order TIFF type blocks can use PSD byte order for the+ /// text descriptor, then container order again for warp and bounds (#4758).+ fn type_layer(&mut self) -> Result<()> {+ self.u16()?;+ self.f64s(6)?;+ self.type_descriptor(50)?;+ self.type_descriptor(1)?;+ self.i32s(4)+ }++ fn type_descriptor(&mut self, version: u16) -> Result<()> {+ let [hi, lo] = version.to_be_bytes();+ let from = if self.from.is_little() && self.r.peek_rest().starts_with(&[hi, lo, 0, 0, 0, 16]) { ByteOrder::Big } else { self.from };+ let data = self.r.peek_rest();+ let mut descriptor = Tx::new(data, self.version, from, self.to);+ descriptor.depth = self.depth;+ descriptor.u16()?;+ descriptor.versioned_descriptor()?;+ let used = data.len() - descriptor.remaining();+ self.r.bytes(used)?;+ self.warnings.append(&mut descriptor.warnings);+ self.out.extend_from_slice(&descriptor.out);+ Ok(())+ }+fn versioned_descriptor(&mut self) -> Result<()> {self.u32()?;self.descriptor()@@ -1794,6 +1811,39 @@ mod tests {assert_eq!(&little[50..58], &1.0f64.to_le_bytes());}+ #[test]+ fn photoshop_type_block_switches_to_big_endian_after_its_matrix() {+ let mut data = Vec::new();+ data.put_u16(1);+ for v in [1.8054202887117468, 0.0, -0.143, 1.8063853899082987, 247.25, 2864.5] {+ data.put_f64(v);+ }+ data.put_u16(50);+ let text = Descriptor::new("TxLr").with("Txt ", Value::Text(UnicodeString::new_nul("Synthetic headline")));+ data.extend(VersionedDescriptor::new(text).to_bytes());+ data.put_u16(1);+ data.extend(VersionedDescriptor::new(Descriptor::new("warp")).to_bytes());+ for v in [0, 0, 120, 30] {+ data.put_i32(v);+ }+ let (_, mut little) = block_rt(*b"TySh", data.clone());+ // Photoshop uses big-endian text but returns to little-endian for warp/bounds.+ let (_, used) = VersionedDescriptor::parse_prefix(&data[52..]).unwrap();+ little[98..100 + used].copy_from_slice(&data[50..52 + used]);+ let (back, warnings) = ImageSourceData::from_bytes(&little).unwrap();+ assert!(warnings.is_empty(), "{warnings:?}");+ assert!(!back.global_blocks[0].is_foreign_order());+ assert_eq!(back.global_blocks[0].data, data);+ // The normalized model remains writable in either order.+ for order in [ByteOrder::Big, ByteOrder::Little] {+ let (bytes, warnings) = back.to_bytes(order).unwrap();+ assert!(warnings.is_empty());+ let (again, warnings) = ImageSourceData::from_bytes(&bytes).unwrap();+ assert!(warnings.is_empty());+ assert_eq!(again.global_blocks[0].data, data);+ }+ }+#[test]fn legacy_effects_and_adjustments() {// lrFX with a drop shadow and a solid fill.diff --git a/crates/text/src/psd.rs b/crates/text/src/psd.rsindex 3f8ce7290..b659a151b 100644--- a/crates/text/src/psd.rs+++ b/crates/text/src/psd.rs@@ -37,6 +37,11 @@ pub fn parse_tysh(data: &[u8]) -> Option<TySh> {for (i, v) in m.iter_mut().enumerate() {*v = f(2 + i * 8)?;}+ // Pixel coordinates use i32 throughout the document. Reject non-finite and+ // unrepresentable affine terms before they reach rendering or egui (#4758).+ if !m.iter().all(|v| v.is_finite() && v.abs() <= f64::from(i32::MAX)) {+ return None;+ }let (text, used) = VersionedDescriptor::parse_prefix(data.get(52..)?).ok()?;let rest = data.get(52 + used..).unwrap_or(&[]);let (warp, wused) = match rest.get(2..).and_then(|r| VersionedDescriptor::parse_prefix(r).ok()) {@@ -1334,3 +1339,22 @@ pub fn build_tysh(layer: &TextLayer, dpi: f32, ink: Option<[f32; 4]>) -> Vec<u8>let bounds = if warped { [l, t, r, b] } else { [0.0; 4] };write_tysh(&TySh { transform: layer.transform, text, warp, bounds })}++#[cfg(test)]+mod transform_safety_tests {+ use super::*;++ #[test]+ fn unsafe_affine_terms_are_not_editable_type() {+ let mut t = TySh { transform: Affine::IDENTITY, text: Descriptor::new("TxLr"), warp: None, bounds: [0.0; 4] };+ for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 1.315776645269349e62, 1.4759871577491642e307] {+ for i in 0..6 {+ t.transform = Affine::IDENTITY;+ t.transform.m[i] = bad;+ assert!(parse_tysh(&write_tysh(&t)).is_none(), "term {i}: {bad}");+ }+ }+ t.transform = Affine { m: [0.0, -2.01242653341062, 2.286521576443544, 0.0, 586.63, 2452.60] };+ assert_eq!(parse_tysh(&write_tysh(&t)).unwrap().transform, t.transform);+ }+}diff --git a/docs/file-format-parity.md b/docs/file-format-parity.mdindex daa8827c3..427497afc 100644--- a/docs/file-format-parity.md+++ b/docs/file-format-parity.md@@ -1,6 +1,6 @@# File-format parity-> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-12 · **Change:** minor (`.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026+> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-12 · **Change:** minor (Photoshop mixed-order TIFF type geometry, #4758; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026Every format Photoshop 2026 (27.11.0) reads or writes, with PhotoCraft's support, fidelity andtests. Photoshop's list comes from its `Info.plist` `CFBundleDocumentTypes`, the PiPL read/write@@ -24,7 +24,7 @@ XL are missing (gap G10). Remaining: 300–500 h including PSD fidelity.| PSD | R/W | yes | yes | 1/8/16/32-bit; Bitmap, Gray, Indexed, RGB, CMYK, Multichannel, Lab, Duotone; layers, groups, masks, vector masks, adjustment and fill layers, effects, text, shapes, smart objects (SoLd/lnk2; CS2 PlLd/lnkD read with their warp, kept as is or re-saved as SoLd once edited), smart filters (14 mapped, rest verbatim), slices, comps, Advanced Blending. Oracle floors: Photoshop-authored 133/256, io 146/170, psd-tools 236/309; round trip ≥ 169/170, 308/309, 258/256. Known failures: #1281, #2469 (#2374, text layers, closed 2026-10-10; #2465, CS2 `PlLd`-only smart objects, fixed 2026-10-12) || PSB | R/W | yes | yes | Auto-switches above 2 GB (REL-212-2); 4–5 GB fixtures generated (FILE-216-2); > 4 GB fails on Windows (#375) || Cloud PSD (.psdc) | R/W | no | no | Out of scope (Adobe cloud) |-| TIFF | R/W | yes | yes | 8/16/32f, Gray/RGB/CMYK, BigTIFF, every IFD, banded parallel decode; layered TIFF both byte orders (FILE-215-7: extra alpha channels not written) |+| TIFF | R/W | yes | yes | 8/16/32f, Gray/RGB/CMYK, BigTIFF, every IFD, banded parallel decode; layered TIFF both byte orders, including Photoshop mixed-order type blocks (#4758); undecodable type keeps saved pixels (FILE-215-7: extra alpha channels not written) || JPEG | R/W | yes | yes | 8-bit Gray/RGB/CMYK, ICC/EXIF/XMP; Save keeps the opened file's quality (estimated from its quantisation tables, #2399); no JPEG Options dialog (quality 0–12, baseline/progressive) (FILE-215-19) || PNG | R/W | yes | yes | 8/16-bit, ICC/text; APNG first frame only; alpha channels on open (#2225) || GIF | R/W | yes | yes | File › Open keeps the first frame; New Video Layer from File and Video Frames to Layers take every frame, with the timeline rate from the delays (#572). Per-frame delays and keeping the frames in `.pcraft` are not done |