Merge PR #4771: Fix mixed-order layered TIFF type geometry and unsafe text fallback

This commit is contained in:
David Mann committed 2026-10-21 11:28:23 +02:00
commit 27b8d133d8
7 files changed
+221 -34

No files matched your search

+28 -21
View File
@@ -361,28 +361,35 @@ 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 type data with a safe transform can become a text layer. A retained
// foreign-order block must never be handed to the big-endian reader (#4758). Canonical
// data the typed reader can't decode stays a type layer as before (usually without
// text), so its TySh is saved back verbatim instead of being dropped with the raster.
let parsed = (!block.is_foreign_order())
.then(|| {
photocraft_text::psd::text_layer_from_tysh(&block.data, self.dpi).or_else(|| {
let (text, transform) = blocks::parse_tysh(&block.data).unwrap_or_default();
photocraft_text::psd::transform_is_safe(&transform).then(|| TextLayer { text, transform, ..Default::default() })
})
})
.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}\": type data in another byte order or with unsafe type geometry; kept as pixels"));
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),
+3 -1
View File
@@ -560,9 +560,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()
});
}
+15 -1
View File
@@ -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();
+86
View File
@@ -0,0 +1,86 @@
//! 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));
}
}
#[test]
fn canonical_type_the_typed_reader_rejects_stays_type_and_saves_its_block() {
let doc = document();
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();
// A text descriptor version the typed reader doesn't know; the matrix is ordinary.
block.data[52..56].copy_from_slice(&17u32.to_be_bytes());
let raw = block.data.clone();
let (opened, warnings) = psd_to_document(&psd);
assert!(!warnings.iter().any(|w| w.contains("unsafe type geometry")), "{warnings:?}");
let LayerContent::Text(t) = &opened.layers[0].content else { panic!("canonical type must stay a type layer") };
let LayerContent::Text(before) = &doc.layers[0].content else { panic!("source type") };
assert_eq!(t.transform, before.transform);
let (saved, _) = document_to_psd_with(&opened, &PsdExportOptions::default());
assert_eq!(saved.layers()[0].block(b"TySh").map(|b| &b.data), Some(&raw), "PSD save must keep the type block");
}
+59 -9
View File
@@ -859,15 +859,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()?;
@@ -1165,6 +1157,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()
@@ -1808,6 +1825,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.
+28
View File
@@ -32,6 +32,12 @@ pub struct TySh {
pub bounds: [f32; 4],
}
/// Whether a type transform can reach rendering or egui. Pixel coordinates use i32 throughout
/// the document, so non-finite and unrepresentable affine terms are rejected (#4758).
pub fn transform_is_safe(t: &Affine) -> bool {
t.m.iter().all(|v| v.is_finite() && v.abs() <= f64::from(i32::MAX))
}
/// Parses a `TySh` block.
pub fn parse_tysh(data: &[u8]) -> Option<TySh> {
let f = |at: usize| data.get(at..at + 8).map(|b| f64::from_be_bytes(b.try_into().unwrap_or([0; 8])));
@@ -39,6 +45,9 @@ pub fn parse_tysh(data: &[u8]) -> Option<TySh> {
for (i, v) in m.iter_mut().enumerate() {
*v = f(2 + i * 8)?;
}
if !transform_is_safe(&Affine { m }) {
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()) {
@@ -1662,6 +1671,25 @@ pub fn build_tysh(layer: &TextLayer, dpi: f32, ink: Option<[f32; 4]>) -> Vec<u8>
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);
}
}
#[cfg(test)]
mod nonfinite_tests {
use super::*;
+2 -2
View File
@@ -1,6 +1,6 @@
# File-format parity
> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-15 · **Change:** minor (DDS textures save: uncompressed or BC1–BC3, optional mip chain, DDS Options in Save As (#1327); earlier: PNG `sTER` stereo pairing kept on save, #6063; PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; earlier: CMYK Invert, Posterize and Threshold on the inks; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.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-15 · **Change:** minor (Photoshop mixed-order TIFF type geometry, #4758; DDS textures save: uncompressed or BC1–BC3, optional mip chain, DDS Options in Save As (#1327); earlier: PNG `sTER` stereo pairing kept on save, #6063; PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; earlier: CMYK Invert, Posterize and Threshold on the inks; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.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
Every format Photoshop 2026 (27.11.0) reads or writes, with PhotoCraft's support, fidelity and
tests. 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 plus Filter Gallery with Chrome, rest verbatim), slices, comps, Advanced Blending. Oracle floors: Photoshop-authored 188/258, io 148/170, psd-tools 249/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); palette PNGs open in Indexed Color mode with their transparent entry (#4804); Save keeps a stereo PNG's `sTER` pairing (#6063) |
| 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 |