Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Layered TIFF: the review changes of #672 (keep unknown blocks with their byte order, io behind the engine, fixture attribution) (#835)

ljkx4cb7cf393140
diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs
index 74326ef4f..23539fa2e 100644
--- a/crates/engine/src/file_cmds.rs
+++ b/crates/engine/src/file_cmds.rs
@@ -120,6 +120,13 @@ const OPENABLE: &[&str] = &[
"hif", "dng", "cr2", "nef", "nrw", "arw", "pef", "svg", "svgz",
];
+/// Whether saving `doc` as a TIFF writes Photoshop layer data (anything beyond a lone
+/// Background layer). The UI asks before such a save when the "ask before saving layered TIFF"
+/// preference is on; see `photocraft_io::tiff_layers`.
+pub fn tiff_would_write_layers(doc: &Document) -> bool {
+ photocraft_io::tiff_layers::would_write_layers(doc)
+}
+
pub(crate) fn file_name(path: &str) -> String {
path.rsplit(['/', '\\']).next().unwrap_or(path).to_string()
}
diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs
index 23e3002d0..5d8fc59f8 100644
--- a/crates/io/src/flat.rs
+++ b/crates/io/src/flat.rs
@@ -314,13 +314,20 @@ pub fn export_flat(doc: &Document, format: Format, opts: &ExportOptions) -> Resu
warnings.push(format!("colours converted to sRGB; {format:?} can't embed the document's colour profile"));
}
}
- for w in codecs::fidelity_warnings_with(&img, format, &opts.encode) {
+ encode_image(&img, format, opts, warnings)
+}
+
+/// Encodes a flat codec image as `format`: the fidelity warnings, then the codec. The end of
+/// every flat export, and of a layered TIFF (whose composite is a flat image to other readers),
+/// so export-wide policies on the image's metadata apply to both.
+pub(crate) fn encode_image(img: &Image, format: Format, opts: &ExportOptions, mut warnings: Vec<String>) -> Result<ExportResult, IoError> {
+ for w in codecs::fidelity_warnings_with(img, format, &opts.encode) {
if w.is_fatal() {
return Err(IoError::Unsupported(w.to_string()));
}
warnings.push(w.to_string());
}
- let bytes = codecs::encode(&img, format, &opts.encode)?;
+ let bytes = codecs::encode(img, format, &opts.encode)?;
Ok(ExportResult { bytes, warnings })
}
diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs
index 48fb32e63..73360392b 100644
--- a/crates/io/src/lib.rs
+++ b/crates/io/src/lib.rs
@@ -207,7 +207,8 @@ pub fn export(doc: &Document, name_or_ext: &str, opts: &ExportOptions) -> Result
}
if ext == "psd" || ext == "psb" {
let o = PsdExportOptions { force_psb: opts.force_psb || ext == "psb", ..Default::default() };
- let (file, warnings) = document_to_psd_with(doc, &o);
+ let (mut file, mut warnings) = document_to_psd_with(doc, &o);
+ warnings.extend(tiff_layers::strip_foreign_order_blocks(&mut file));
// Never write a header the reader would refuse (e.g. a zero-sized canvas).
file.header.validate()?;
let bytes = file.to_bytes()?;
diff --git a/crates/io/src/tiff_layers.rs b/crates/io/src/tiff_layers.rs
index 6ad712c19..bb5770e5f 100644
--- a/crates/io/src/tiff_layers.rs
+++ b/crates/io/src/tiff_layers.rs
@@ -17,7 +17,7 @@ use photocraft_psd::resources::ids;
use photocraft_psd::tiff::{ByteOrder, ImageSourceData, resources_from_bytes, resources_to_bytes};
use photocraft_psd::{ColorMode as PsdMode, Compression, Header, ImageData, ImageResource, ResolutionInfo};
-use crate::flat::{csample, image_to_document, layout_for, single_layer, try_buffer};
+use crate::flat::{csample, encode_image, image_to_document, layout_for, single_layer, try_buffer};
use crate::psd_export::{PsdExportOptions, document_to_psd_with};
use crate::psd_import::psd_to_document;
use crate::{ExportOptions, ExportResult, ImportResult, IoError};
@@ -225,12 +225,34 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions) -> Result<Exp
photoshop_layers: Some(layers),
..Default::default()
};
- for w in codecs::fidelity_warnings_with(&img, Format::Tiff, &opts.encode) {
- if w.is_fatal() {
- return Err(IoError::Unsupported(w.to_string()));
+ encode_image(&img, Format::Tiff, opts, warnings)
+}
+
+/// Removes the blocks a document kept verbatim from a little-endian TIFF because their layout
+/// is unknown ([`photocraft_psd::TaggedBlock::is_foreign_order`]) before `file` is written as a
+/// PSD: their bytes are in the wrong order for a PSD and cannot be converted. Returns a warning
+/// per block dropped. A save back to TIFF keeps them (see [`photocraft_psd::tiff`]).
+pub fn strip_foreign_order_blocks(file: &mut photocraft_psd::PsdFile) -> Vec<String> {
+ let mut warnings = Vec::new();
+ let mut strip = |blocks: &mut Vec<photocraft_psd::TaggedBlock>, owner: &str| {
+ blocks.retain(|b| {
+ let keep = !b.is_foreign_order();
+ if !keep {
+ warnings.push(format!(
+ "{owner}: {} block ({} bytes) kept from a little-endian TIFF cannot be written to PSD and was dropped",
+ b.key_str(),
+ b.data.len()
+ ));
+ }
+ keep
+ });
+ };
+ if let Some(info) = &mut file.layer_info {
+ for l in &mut info.layers {
+ let name = l.name();
+ strip(&mut l.blocks, &format!("layer \"{name}\""));
}
- warnings.push(w.to_string());
}
- let bytes = codecs::encode(&img, Format::Tiff, &opts.encode)?;
- Ok(ExportResult { bytes, warnings })
+ strip(&mut file.global_blocks, "document");
+ warnings
}
diff --git a/crates/psd/src/tagged.rs b/crates/psd/src/tagged.rs
index 7ea003f12..9545a4c99 100644
--- a/crates/psd/src/tagged.rs
+++ b/crates/psd/src/tagged.rs
@@ -134,6 +134,20 @@ impl TaggedBlock {
TaggedBlock { signature: *b"8BIM", key, data, padding: None }
}
+ /// `true` for `MIB8` / `46B8`: the signatures [`crate::tiff`] gives a block whose data was
+ /// kept verbatim from a little-endian TIFF because its layout is unknown. Such a block is
+ /// written back exactly into a little-endian TIFF, and cannot go into a big-endian file
+ /// (a PSD) without being dropped: see [`Self::is_foreign_order`].
+ pub fn is_foreign_order_signature(b: &[u8]) -> bool {
+ b.starts_with(b"MIB8") || b.starts_with(b"46B8")
+ }
+
+ /// Whether this block's data is in little-endian layout (see
+ /// [`Self::is_foreign_order_signature`]).
+ pub fn is_foreign_order(&self) -> bool {
+ Self::is_foreign_order_signature(&self.signature)
+ }
+
/// Key as a string (lossy).
pub fn key_str(&self) -> String {
String::from_utf8_lossy(&self.key).into_owned()
@@ -384,8 +398,10 @@ fn parse_section(d: &[u8]) -> Result<SectionDivider> {
Ok(SectionDivider { kind, blend_mode, sub_type })
}
+/// `8BIM` / `8B64`, or the markers `MIB8` / `46B8` that [`crate::tiff`] gives a block kept
+/// verbatim from a little-endian TIFF when its layout is unknown (its data is in that order).
fn is_sig(b: &[u8]) -> bool {
- b.starts_with(b"8BIM") || b.starts_with(b"8B64")
+ b.starts_with(b"8BIM") || b.starts_with(b"8B64") || TaggedBlock::is_foreign_order_signature(b)
}
/// Reads tagged blocks until the reader is exhausted. Bytes that do not form
diff --git a/crates/psd/src/tiff.rs b/crates/psd/src/tiff.rs
index f76c01df9..d91e0821c 100644
--- a/crates/psd/src/tiff.rs
+++ b/crates/psd/src/tiff.rs
@@ -18,9 +18,12 @@
//! as in a PSD, and RLE row-count tables follow the container. [`ImageSourceData::from_bytes`]
//! normalizes either order to the big-endian PSD model, and [`ImageSourceData::to_bytes`] writes
//! either order, by transcoding every structure it knows field by field ([`transcode`]).
-//! Blocks the transcoder does not know are kept verbatim when no byte swap is needed, and dropped
-//! with a warning otherwise (a byte-swapped block passed through unchanged would be read as
-//! garbage by every other application).
+//! A block the transcoder does not know is never dropped on the way in: its bytes are kept
+//! verbatim with the signature `MIB8` (`46B8` for `8B64`) marking that they are in little-endian
+//! layout ([`TaggedBlock::is_foreign_order`]), so a later save to a little-endian TIFF writes it
+//! back exactly. Only a save to the *other* byte order has to drop such a block, with a warning:
+//! a byte-swapped block passed through unchanged would be read as garbage by every other
+//! application (and would end the block list for readers that stop at a bad signature).
use crate::descriptor::MAX_DEPTH;
use crate::error::{PsdError, Result};
@@ -164,7 +167,8 @@ impl ImageSourceData {
for b in &self.global_blocks {
let mut b = b.clone();
if b.padding.is_none() {
- b = padded_block(b.key, b.data);
+ // Padded to 4 like the others; the signature stays (a foreign-order marker included).
+ b.padding = Some(vec![0; (4 - b.data.len() % 4) % 4]);
}
blocks.push(b);
}
@@ -290,8 +294,14 @@ pub mod transcode {
Ok(t.finish())
}
+ /// A block signature as stored in `little` or big-endian data. Big-endian data (the model)
+ /// also carries the `MIB8` / `46B8` markers of blocks kept from a little-endian file.
fn is_sig(b: &[u8], little: bool) -> bool {
- if little { b.starts_with(b"MIB8") || b.starts_with(b"46B8") } else { b.starts_with(b"8BIM") || b.starts_with(b"8B64") }
+ if little {
+ b.starts_with(b"MIB8") || b.starts_with(b"46B8")
+ } else {
+ b.starts_with(b"8BIM") || b.starts_with(b"8B64") || TaggedBlock::is_foreign_order_signature(b)
+ }
}
fn height(top: i32, bottom: i32) -> usize {
@@ -654,7 +664,38 @@ pub mod transcode {
fn block(&mut self) -> Result<()> {
let before = self.out.len();
- self.key()?;
+ // A `MIB8` / `46B8` marker in big-endian data: a block kept verbatim from a
+ // little-endian file. Written back as it was into little-endian output (its `8BIM`
+ // signature reversed, as every signature there), copied as is otherwise.
+ if !self.from.is_little() && TaggedBlock::is_foreign_order_signature(self.r.peek_rest()) {
+ let sig = self.r.array::<4>()?;
+ let mut key = self.r.array::<4>()?;
+ let long = uses_long_length(self.version, &{
+ let mut k = key;
+ if self.to.is_little() {
+ k.reverse();
+ }
+ k
+ });
+ let len = self.r.len_field(long)?;
+ let data = self.r.bytes_u64(len)?;
+ if self.to.is_little() {
+ key.reverse();
+ }
+ self.out.extend_from_slice(&sig);
+ self.out.extend_from_slice(&key);
+ let n = self.out.len();
+ self.out.extend_from_slice(if long { &[0u8; 8] } else { &[0u8; 4] });
+ self.patch_len(n, long, len)?;
+ self.out.extend_from_slice(data);
+ let rest = self.r.peek_rest();
+ let pad = (0..=3usize).find(|&k| k == rest.len() || (k < rest.len() && is_sig(&rest[k..], self.from.is_little()))).unwrap_or(0);
+ let pad_bytes = self.r.bytes(pad)?;
+ self.out.extend_from_slice(pad_bytes);
+ return Ok(());
+ }
+ let sig_at = self.out.len();
+ let sig = self.key()?;
let key = self.key()?;
let long = uses_long_length(self.version, &key);
let len = self.r.len_field(long)?;
@@ -687,6 +728,14 @@ pub mod transcode {
self.out.extend_from_slice(data);
self.out.extend_from_slice(pad_bytes);
}
+ // Little-endian in, big-endian model: keep the bytes as they are, marked.
+ Ok(false) if self.from.is_little() => {
+ let marker: &[u8; 4] = if &sig == b"8B64" { b"46B8" } else { b"MIB8" };
+ self.out[sig_at..sig_at + 4].copy_from_slice(marker);
+ self.patch_len(len_at, long, data.len() as u64)?;
+ self.out.extend_from_slice(data);
+ self.out.extend_from_slice(pad_bytes);
+ }
Ok(false) => {
self.out.truncate(before);
self.warnings.push(format!(
@@ -696,6 +745,14 @@ pub mod transcode {
));
}
Err(e) if self.same_order() => return Err(PsdError::invalid(format!("{} block: {e}", String::from_utf8_lossy(&key)))),
+ Err(e) if self.from.is_little() => {
+ let marker: &[u8; 4] = if &sig == b"8B64" { b"46B8" } else { b"MIB8" };
+ self.out[sig_at..sig_at + 4].copy_from_slice(marker);
+ self.patch_len(len_at, long, data.len() as u64)?;
+ self.out.extend_from_slice(data);
+ self.out.extend_from_slice(pad_bytes);
+ self.warnings.push(format!("{} block ({} bytes) kept as stored, in little-endian layout: {e}", String::from_utf8_lossy(&key), data.len()));
+ }
Err(e) => {
self.out.truncate(before);
self.warnings.push(format!("{} block ({} bytes) dropped: {e}", String::from_utf8_lossy(&key), data.len()));
@@ -2082,21 +2139,46 @@ mod tests {
let (back, w) = ImageSourceData::from_bytes(&big).unwrap();
assert!(w.is_empty());
assert_eq!(back.global_blocks, d.global_blocks);
+ // Big-endian data of unknown layout cannot go into a little-endian file.
let (little, w) = d.to_bytes(ByteOrder::Little).unwrap();
assert_eq!(w.iter().filter(|w| w.starts_with("Zzzz block (5 bytes) dropped")).count(), 1, "{w:?}");
let (back, w) = ImageSourceData::from_bytes(&little).unwrap();
assert!(w.is_empty());
assert_eq!(back.global_blocks.iter().map(|b| b.key).collect::<Vec<_>>(), vec![*b"Patt", *b"FMsk"]);
assert_eq!(known(&back).layer_info, known(&d).layer_info);
- // A little-endian file with an unknown block: the block is dropped on read, with a warning.
+ }
+
+ #[test]
+ fn unknown_blocks_from_a_little_endian_file_are_kept_with_their_byte_order() {
+ let d = sample_layers();
+ let (little, _) = d.to_bytes(ByteOrder::Little).unwrap();
+ // A little-endian file with a block of unknown layout, among known ones.
let mut raw = little.clone();
raw.extend_from_slice(b"MIB8zzzZ");
+ raw.extend_from_slice(&6u32.to_le_bytes());
+ raw.extend_from_slice(&[9, 8, 7, 6, 5, 4, 0, 0]);
+ raw.extend_from_slice(b"MIB8diyl");
raw.extend_from_slice(&4u32.to_le_bytes());
- raw.extend_from_slice(&[9, 9, 9, 9]);
+ raw.extend_from_slice(&7u32.to_le_bytes());
let (back, w) = ImageSourceData::from_bytes(&raw).unwrap();
- assert_eq!(w.len(), 1);
- assert!(w[0].starts_with("Zzzz block (4 bytes) dropped"), "{}", w[0]);
+ assert!(w.is_empty(), "{w:?}");
assert_eq!(known(&back).layer_info, known(&d).layer_info);
+ let kept = back.global_blocks.iter().find(|b| &b.key == b"Zzzz").expect("kept");
+ assert!(kept.is_foreign_order());
+ assert_eq!(kept.signature, *b"MIB8");
+ assert_eq!(kept.data, [9, 8, 7, 6, 5, 4]);
+ // The known block after it was still converted.
+ assert_eq!(back.global_blocks.iter().find(|b| &b.key == b"lyid").unwrap().data, 7u32.to_be_bytes());
+ // Written back to a little-endian TIFF, the bytes are exactly what was read.
+ let (again, w) = back.to_bytes(ByteOrder::Little).unwrap();
+ assert!(w.is_empty(), "{w:?}");
+ let tail = &raw[raw.len() - 18 - 16..];
+ assert!(again.windows(tail.len()).any(|x| x == tail), "foreign-order block restored verbatim");
+ assert_eq!(ImageSourceData::from_bytes(&again).unwrap().0.global_blocks, back.global_blocks);
+ // The big-endian (PSD) model keeps the marker, so a PSD writer can tell it apart.
+ let (big, _) = back.to_bytes(ByteOrder::Big).unwrap();
+ assert!(big.windows(8).any(|x| x == b"MIB8Zzzz"));
+ assert_eq!(ImageSourceData::from_bytes(&big).unwrap().0.global_blocks, back.global_blocks);
}
#[test]
diff --git a/crates/ui-egui/src/tiff_options_ui.rs b/crates/ui-egui/src/tiff_options_ui.rs
index 3c55e8fd8..550961e71 100644
--- a/crates/ui-egui/src/tiff_options_ui.rs
+++ b/crates/ui-egui/src/tiff_options_ui.rs
@@ -29,7 +29,7 @@ pub fn wants_prompt(app: &PhotocraftApp, path: &str) -> bool {
if !is_tiff_path(path) || !app.session.prefs().file_handling.ask_before_saving_layered_tiff {
return false;
}
- app.session.active().is_some_and(|st| photocraft_io::tiff_layers::would_write_layers(&st.doc))
+ app.session.active().is_some_and(|st| photocraft_engine::file_cmds::tiff_would_write_layers(&st.doc))
}
/// Parks the save behind the prompt.
diff --git a/docs/scorecard.md b/docs/scorecard.md
index c6fe8b0df..30f6d6ce4 100644
--- a/docs/scorecard.md
+++ b/docs/scorecard.md
@@ -7,7 +7,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js
| Area | Done | Partial | Missing | Key numbers |
|---|---:|---:|---:|---|
| [Performance](#performance) | 3 | 22 | 13 | 47 scenarios: 3 within budget, 22 over budget or failing, 15 tracked only, 6 not run, 7 not measurable yet (baseline 2026-10-05) |
-| [File compatibility](#file-compatibility) | 4 | 10 | 13 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 229/309, round trip ≥ 307/309; photoshop oracles: oracle ≥ 133/256, round trip ≥ 258/256 |
+| [File compatibility](#file-compatibility) | 3 | 11 | 13 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 229/309, round trip ≥ 307/309; photoshop oracles: oracle ≥ 133/256, round trip ≥ 258/256 |
| [Tools](#tools) | 8 | 14 | 8 | |
| [Workspace and UI](#workspace-and-ui) | 0 | 5 | 18 | settings that do nothing: 56 of 140 (target 0) |
| [Type](#type) | 0 | 3 | 6 | |
@@ -95,7 +95,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t
| FILE-215-4 | Adjustments (Hue/Sat + Colorize, Curves, Levels, Shadows/Highlights) apply as Smart Filters | partial | [#215](https://github.com/storytold/photocraft/issues/215) | PSD Levels/Curves/Shadows-Highlights smart filters render (adjust_cmds.rs adjust_as_filter); Image › Adjustments on a smart object doesn't add one yet |
| FILE-215-5 | Smart Filter rows: collapse, mask thumb, blend icon, drag reorder, context menu, live preview | partial | [#215](https://github.com/storytold/photocraft/issues/215) | smart_ui.rs:31 rows + visibility + editor; no collapse, drag or context menu |
| FILE-215-6 | Smart Object corner skew and perspective (quad or homography transform) | missing | [#215](https://github.com/storytold/photocraft/issues/215) | doc lib.rs:312 SmartObject.transform is an Affine |
-| FILE-215-7 | Layered TIFF read and write (tag 37724), honouring the ask-before-saving pref | done | [#215](https://github.com/storytold/photocraft/issues/215) | psd tiff.rs (ImageSourceData, both byte orders), io tiff_layers.rs, ui tiff_options_ui.rs (Discard Layers and Save a Copy); extra alpha channels are not written (one transparency sample) |
+| FILE-215-7 | Layered TIFF read and write (tag 37724), honouring the ask-before-saving pref | partial | [#215](https://github.com/storytold/photocraft/issues/215) | psd tiff.rs (ImageSourceData, both byte orders), io tiff_layers.rs, ui tiff_options_ui.rs (Discard Layers and Save a Copy); extra alpha channels and a Quick Mask are not written (the TIFF codec holds one transparency sample) |
| FILE-215-8 | Large and BigTIFF import with banded decode across all IFDs | done | [#215](https://github.com/storytold/photocraft/issues/215) | codecs tiff_ifd.rs (bounds-checked IFD chain + SubIFD walk, classic and BigTIFF, cycle-safe; tiff_info / decode_tiff_page), tiff.rs banded parallel strip/tile decode, planar 1 and 2, BigTIFF write (tiff_bigtiff or > 4 GiB); io import_tiff_page; 30 MP RGB8 Deflate 345 -> 32 ms; no page picker in the UI yet |
| FILE-215-9 | SVG opens and places as shape layers or a vector Smart Object | done | [#215](https://github.com/storytold/photocraft/issues/215) | io svg.rs: paths, groups, text outlines as shape layers (gradients approximated; clip/mask/filter/pattern/image subtrees rasterised); smart_cmds.rs renders an SVG source at its placement scale |
| FILE-215-10 | Multi-page PDF save, PDF presentation, layer comps to PDF, vector/text output, PDF import | missing | [#215](https://github.com/storytold/photocraft/issues/215) | Only print_cmds.rs:133 print_pdf (raster print page) |
diff --git a/scorecard/file_compat.toml b/scorecard/file_compat.toml
index 54ed00a96..3b5546298 100644
--- a/scorecard/file_compat.toml
+++ b/scorecard/file_compat.toml
@@ -50,9 +50,9 @@ note = "doc lib.rs:312 SmartObject.transform is an Affine"
[[item]]
id = "FILE-215-7"
target = "Layered TIFF read and write (tag 37724), honouring the ask-before-saving pref"
-status = "done"
+status = "partial"
issue = 215
-note = "psd tiff.rs (ImageSourceData, both byte orders), io tiff_layers.rs, ui tiff_options_ui.rs (Discard Layers and Save a Copy); extra alpha channels are not written (one transparency sample)"
+note = "psd tiff.rs (ImageSourceData, both byte orders), io tiff_layers.rs, ui tiff_options_ui.rs (Discard Layers and Save a Copy); extra alpha channels and a Quick Mask are not written (the TIFF codec holds one transparency sample)"
[[item]]
id = "FILE-215-8"