TIFF Options: compression, image pyramid and Save Transparency (#8827) (#10932)

Offer TIFF compression, image pyramid and transparency options on Save As and Save a Copy, with matching CLI and automation parameters.

Follow-up: preserve the unsaved state when a copy discards layers over the document's own file, and check the other export formats for the same issue.

Closes #8827.
This commit is contained in:
Yuki-init authored and GitHub committed 2026-11-03 15:39:15 +01:00
1 parent 2fff1f8688
commit e3a84b628d
36 files changed
+1670 -109

No files matched your search

+18
View File
@@ -55,6 +55,14 @@ pub(crate) struct ExportArgs {
/// Compress TIFF output: none (the default), lzw or zip
#[arg(long, value_name = "none|lzw|zip", value_parser = tiff_compression)]
pub(crate) tiff_compression: Option<TiffCompression>,
/// TIFF Save Transparency: on keeps the transparency (ahead of any alpha or spot channels),
/// off composites the image over white. Without it: kept unless the document has alpha or
/// spot channels
#[arg(long, value_name = "on|off", value_parser = on_off)]
pub(crate) tiff_transparency: Option<bool>,
/// Also write a TIFF image pyramid: half-size copies after the full image
#[arg(long)]
pub(crate) tiff_pyramid: bool,
/// A TGA's bits per pixel: 32 writes the alpha channel (or else the transparency) as its
/// alpha, 24 none. Without it: 32 with an alpha channel or transparency, else 24
#[arg(long, value_name = "24|32", value_parser = tga_bits)]
@@ -268,6 +276,8 @@ enum ValueError {
TiffCompression,
#[error("expected baseline, optimized or progressive")]
JpegFormat,
#[error("expected on or off")]
OnOff,
/// Why a `--bridge` value, or a PHOTOCRAFT_CONTROL_PORT value for `mcp`, is refused.
#[error("expected a port, 0-65535 (--bridge also takes 127.0.0.1:<PORT>)")]
Bridge,
@@ -322,6 +332,14 @@ fn tiff_compression(s: &str) -> Result<TiffCompression, ValueError> {
}
}
fn on_off(s: &str) -> Result<bool, ValueError> {
match s {
"on" => Ok(true),
"off" => Ok(false),
_ => Err(ValueError::OnOff),
}
}
fn jpeg_format(s: &str) -> Result<JpegFormat, ValueError> {
JpegFormat::parse(s).ok_or(ValueError::JpegFormat)
}
+8 -1
View File
@@ -8,7 +8,13 @@ use crate::{Result, args::ExportArgs};
impl From<&ExportArgs> for ExportOptions {
fn from(a: &ExportArgs) -> Self {
// TIFF output is flat unless asked: scripted conversions keep predictable sizes.
let mut o = ExportOptions { tiff_layers: a.tiff_layers, tga_bits: a.tga_bits, pcraft_full_composite: a.pcraft_full_composite, ..Default::default() };
let mut o = ExportOptions {
tiff_layers: a.tiff_layers,
tiff_transparency: a.tiff_transparency,
tga_bits: a.tga_bits,
pcraft_full_composite: a.pcraft_full_composite,
..Default::default()
};
if let Some(q) = a.quality {
o.encode.jpeg_quality = q;
// Asking for a quality asks for a lossy WebP; the default WebP stays lossless.
@@ -19,6 +25,7 @@ impl From<&ExportArgs> for ExportOptions {
if let Some(c) = a.tiff_compression {
o.encode.tiff_compression = c;
}
o.encode.tiff_pyramid = a.tiff_pyramid;
if let Some(f) = a.jpeg_format {
o.encode.jpeg_format = f;
}
+32
View File
@@ -1530,3 +1530,35 @@ fn batch_skips_deselect_with_nothing_selected() {
assert_eq!((info["width"].as_u64(), info["height"].as_u64()), (Some(6), Some(8)), "the step after Deselect ran: {info}");
let _ = std::fs::remove_dir_all(&dir);
}
/// TIFF Options from the command line (#8827): `--tiff-compression`, `--tiff-transparency on|off`
/// and `--tiff-pyramid`; a bad value is a usage error that writes nothing.
#[test]
fn tiff_options_choose_compression_transparency_and_pyramid() {
let d = tmp("tiff-options");
let a = d.join("a.png");
write_png(&a, 200, 100, 3);
// (flags, compression tag, alpha, directories)
for (flags, compression, alpha, dirs) in [
(&[][..], 1, true, 1),
(&["--tiff-compression", "lzw"][..], 5, true, 1),
(&["--tiff-transparency", "off", "--tiff-compression", "zip"][..], 8, false, 1),
(&["--tiff-transparency", "on", "--tiff-pyramid"][..], 1, true, 3),
] {
let out = d.join("a.tif");
ok(bin().arg("convert").arg(&a).arg(&out).args(flags));
let bytes = std::fs::read(&out).unwrap();
let info = photocraft_codecs::tiff_info(&bytes).unwrap();
assert_eq!(info.pages.len(), dirs, "{flags:?}");
assert!(info.pages.iter().all(|p| p.compression == compression), "{flags:?}: {:?}", info.pages);
assert_eq!(photocraft_codecs::decode(&bytes).unwrap().layout().has_alpha(), alpha, "{flags:?}");
}
for (flag, bad, expected) in [("--tiff-transparency", "maybe", "expected on or off"), ("--tiff-compression", "jpeg", "expected none, lzw or zip")] {
let out = d.join("bad.tif");
let o = bin().arg("convert").arg(&a).arg(&out).args([flag, bad]).output().unwrap();
let err = String::from_utf8_lossy(&o.stderr);
assert_eq!(o.status.code(), Some(2), "{flag} {bad}");
assert!(err.contains(flag) && err.contains(expected), "{flag} {bad}: {err}");
assert!(!out.exists(), "{flag} {bad} wrote a file");
}
}
+19
View File
@@ -948,3 +948,22 @@ fn a_panicking_clipboard_read_is_reported_not_a_crash() {
let mut set = guarded_clipboard_set(|_: u32, _: u32, _: &[u8]| panic!("clipboard writer bug"));
assert!(set(1, 1, &[0; 4]).unwrap_err().contains("Copy failed"));
}
/// #8827: what TIFF Options sets in `ExportSettings` reaches the file the app writes: the
/// compression, Save Transparency and Save Image Pyramid.
#[test]
fn tiff_options_reach_the_written_file() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 200, "height": 100, "background": "transparent"})).unwrap();
let doc = s.active().unwrap().doc.clone();
let settings = photocraft_ui_egui::ExportSettings {
tiff_compression: photocraft_codecs::TiffCompression::Lzw,
tiff_transparency: Some(false),
tiff_pyramid: true,
..Default::default()
};
let bytes = photocraft_io::export(&doc, "t.tif", &export_options(&settings)).unwrap().bytes;
let info = photocraft_codecs::tiff_info(&bytes).unwrap();
assert_eq!(info.pages.iter().map(|p| (p.width, p.compression)).collect::<Vec<_>>(), [(200, 5), (100, 5), (50, 5)]);
assert!(!photocraft_codecs::decode(&bytes).unwrap().layout().has_alpha());
}
+6
View File
@@ -174,6 +174,12 @@ impl Headless {
};
opts.encode.dpx_bits = photocraft_engine::file_cmds::dpx_bits_param(&p, "doc.save").map_err(|e| bad(e.to_string()))?;
opts.encode.dds = photocraft_engine::file_cmds::dds_param(&p, "doc.save").map_err(|e| bad(e.to_string()))?.unwrap_or_default();
if let Some(c) = photocraft_engine::file_cmds::tiff_compression_param(&p, "doc.save").map_err(|e| bad(e.to_string()))? {
opts.encode.tiff_compression = c;
}
let tiff_bool = |key| photocraft_engine::file_cmds::tiff_bool_param(&p, key, "doc.save").map_err(|e| bad(e.to_string()));
opts.tiff_transparency = tiff_bool("tiffTransparency")?;
opts.encode.tiff_pyramid = tiff_bool("tiffPyramid")?.unwrap_or(false);
match p.get("quality") {
None | Some(Value::Null) => {}
Some(v) => {
+33 -2
View File
@@ -183,6 +183,17 @@ pub struct SaveParams {
/// TIFF: keep the layers (Photoshop layer data). Off by default: a flat TIFF.
#[serde(default, rename = "tiffLayers")]
pub tiff_layers: bool,
/// TIFF: image compression, "none" (the default), "lzw" or "zip".
#[serde(default, rename = "tiffCompression")]
pub tiff_compression: Option<String>,
/// TIFF: Save Transparency. On keeps the transparency, ahead of any alpha or spot channels;
/// off composites the image over white. Unset: kept unless the document has alpha or spot
/// channels.
#[serde(default, rename = "tiffTransparency")]
pub tiff_transparency: Option<bool>,
/// TIFF: Save Image Pyramid, half-size copies after the full image.
#[serde(default, rename = "tiffPyramid")]
pub tiff_pyramid: bool,
/// TGA: 24 or 32 bits per pixel. 32 writes the alpha channel (or else the transparency) as the
/// alpha, 24 none. Unset: 32 with an alpha channel or transparency, else 24.
#[serde(default, rename = "tgaBits")]
@@ -1122,6 +1133,10 @@ impl PhotocraftMcp {
Some((_, Some(bits))) => Some(bits),
Some((b, None)) => return Ok(fail(format!("`dpxBits` must be 8, 10, 12 or 16, got {b}"))),
};
let tiff_compression = match photocraft_engine::file_cmds::tiff_compression_param(&json!({"tiffCompression": p.tiff_compression}), "save") {
Ok(c) => c,
Err(e) => return Ok(fail(e.to_string())),
};
if let Some(q) = p.quality.filter(|q| !(1..=100).contains(q)) {
return Ok(fail(format!("`quality` must be a whole number from 1 to 100, got {q}")));
}
@@ -1133,8 +1148,9 @@ impl PhotocraftMcp {
if let Some(b) = self.bridge_client() {
// The bridge forwards to the running app's `app.save`, which takes only an optional
// path (without one it writes back to the document's own layered file, as headless
// does), the Targa bits and the DDS options, so the other options are headless-only. Saying so beats
// saving with defaults while the caller believes their quality or format was applied.
// does), the Targa bits, the DDS options and the TIFF compression, transparency and
// pyramid, so the other options are headless-only. Saying so beats saving with
// defaults while the caller believes their quality or format was applied.
let unsupported: Vec<&str> = [
p.format.is_some().then_some("format"),
p.quality.is_some().then_some("quality"),
@@ -1162,17 +1178,32 @@ impl PhotocraftMcp {
if p.dds_mipmaps {
params["ddsMipmaps"] = json!(true);
}
// The app's TIFF Options answer, as its Save As takes it.
if let Some(c) = &p.tiff_compression {
params["tiffCompression"] = json!(c);
}
if let Some(t) = p.tiff_transparency {
params["tiffTransparency"] = json!(t);
}
if p.tiff_pyramid {
params["tiffPyramid"] = json!(true);
}
return to_result(b.call("app.save", params).await);
}
let Some(r) = self
.headless_op(move |h| {
let mut opts = photocraft_io::ExportOptions {
tiff_layers: p.tiff_layers,
tiff_transparency: p.tiff_transparency,
tga_bits,
pcraft_full_composite: p.pcraft_full_composite.unwrap_or(false),
..Default::default()
};
opts.encode.dpx_bits = dpx_bits;
if let Some(c) = tiff_compression {
opts.encode.tiff_compression = c;
}
opts.encode.tiff_pyramid = p.tiff_pyramid;
opts.encode.dds = photocraft_io::DdsOptions { compression: dds_compression.unwrap_or_default(), mipmaps: p.dds_mipmaps };
if let Some(q) = p.quality {
opts.encode.jpeg_quality = q;
@@ -80,3 +80,28 @@ fn a_flat_export_is_a_copy_and_leaves_the_document_dirty() {
assert!(!headless.session.active().unwrap().is_dirty());
std::fs::remove_dir_all(dir).unwrap();
}
/// The control channel's `doc.save` takes the TIFF Options (#8827): compression, Save
/// Transparency and Save Image Pyramid; a bad value is an error and writes nothing.
#[test]
fn doc_save_takes_tiff_options() {
let dir = tmp("tiff-options");
let mut headless = Headless::trusted_local();
headless.handle("doc.new", json!({"width": 200, "height": 100, "background": "transparent"})).unwrap();
let path = dir.join("o.tif");
let p = path.to_str().unwrap();
headless.handle("doc.save", json!({"path": p, "tiffCompression": "zip", "tiffTransparency": false, "tiffPyramid": true})).unwrap();
let bytes = std::fs::read(&path).unwrap();
let info = photocraft_codecs::tiff_info(&bytes).unwrap();
assert_eq!(info.pages.len(), 3);
assert!(info.pages.iter().all(|pg| pg.compression == 8));
assert!(!photocraft_codecs::decode(&bytes).unwrap().layout().has_alpha());
let bad = dir.join("bad.tif");
for params in [json!({"tiffCompression": "jpeg"}), json!({"tiffPyramid": 1}), json!({"tiffTransparency": "no"})] {
let mut params = params;
params["path"] = json!(bad.to_str().unwrap());
assert!(headless.handle("doc.save", params.clone()).is_err(), "{params}");
}
assert!(!bad.exists());
let _ = std::fs::remove_dir_all(&dir);
}
+47
View File
@@ -466,6 +466,53 @@ async fn headless_doc_save_writes_dds_options() {
cleanup(&dir);
}
/// TIFF Options (#8827) reach the app's `app.save` through the bridge; a bad compression is
/// refused before anything is sent.
#[tokio::test(flavor = "multi_thread")]
async fn bridge_doc_save_forwards_tiff_options() {
let (addr, app) = fake_app().await;
let client = connect(PhotocraftMcp::bridge(&addr, CONTROL_TOKEN).unwrap()).await;
let saved = json_of(&call(&client, "doc_save", json!({"path": "out.tif", "tiffCompression": "lzw", "tiffTransparency": false, "tiffPyramid": true})).await);
assert_eq!(saved, json!({"saved": {"path": "out.tif", "tiffCompression": "lzw", "tiffTransparency": false, "tiffPyramid": true}}));
for bad in [json!({"path": "out.tif", "tiffCompression": "jpeg"}), json!({"path": "out.tif", "tiffPyramid": "yes"})] {
let r = call(&client, "doc_save", bad.clone()).await;
assert_eq!(r.is_error, Some(true), "{bad}: {}", text(&r));
}
client.cancel().await.unwrap();
app.abort();
}
/// Headless `doc_save`/`doc_export` write the TIFF Options asked for (#8827): compression,
/// Save Transparency and Save Image Pyramid.
#[tokio::test(flavor = "multi_thread")]
async fn headless_doc_save_writes_tiff_options() {
let dir = tmp("tiff-options");
let client = connect(headless_in(&dir)).await;
call(&client, "doc_new", json!({"width": 200, "height": 100, "background": "transparent"})).await;
// (params, compression tag, alpha, directories)
for (tool, params, compression, alpha, dirs) in [
("doc_export", json!({"path": "plain.tif"}), 1, true, 1),
("doc_export", json!({"path": "lzw.tif", "tiffCompression": "lzw"}), 5, true, 1),
("doc_save", json!({"path": "zip.tif", "tiffCompression": "zip", "tiffTransparency": false}), 8, false, 1),
("doc_save", json!({"path": "pyr.tif", "tiffPyramid": true, "tiffTransparency": true}), 1, true, 3),
] {
let r = call(&client, tool, params.clone()).await;
assert_ne!(r.is_error, Some(true), "{params}: {}", text(&r));
let bytes = std::fs::read(dir.join(params["path"].as_str().unwrap())).unwrap();
let info = photocraft_codecs::tiff_info(&bytes).unwrap();
assert!(info.pages.iter().all(|p| p.compression == compression), "{params}: {:?}", info.pages);
assert_eq!(info.pages.len(), dirs, "{params}");
assert_eq!(photocraft_codecs::decode(&bytes).unwrap().layout().has_alpha(), alpha, "{params}");
}
for bad in [json!({"path": "bad.tif", "tiffCompression": "jpeg"}), json!({"path": "bad.tif", "tiffTransparency": "off"})] {
let r = call(&client, "doc_export", bad.clone()).await;
assert_eq!(r.is_error, Some(true), "{bad}: {}", text(&r));
}
assert!(!dir.join("bad.tif").exists());
client.cancel().await.unwrap();
cleanup(&dir);
}
#[tokio::test(flavor = "multi_thread")]
async fn bridge_response_budget_drops_connection_without_retrying_the_operation() {
use photocraft_automation::{BridgeClient, budgets::MAX_RESPONSE_BYTES};
+141
View File
@@ -260,8 +260,13 @@ struct TagSet<'a> {
extra_samples: &'a [u16],
photoshop_resources: Option<&'a [u8]>,
photoshop_layers: Option<&'a [u8]>,
/// An image pyramid level: written with `NewSubfileType` 1 (reduced resolution).
reduced: bool,
}
/// TIFF `NewSubfileType` (254).
const TAG_NEW_SUBFILE_TYPE: u16 = 254;
/// Writes one image directory. (The `tiff` encoder only compresses through `write_data`, which
/// takes every sample at once.)
fn write_one<C, K>(enc: &mut TiffEncoder<&mut Cursor<Vec<u8>>, K>, w: u32, h: u32, data: &[C::Inner], tags: &TagSet<'_>) -> tiff::TiffResult<()>
@@ -287,6 +292,9 @@ where
im.y_resolution(Rational { n: (y * 1000.0).round() as u32, d: 1000 });
}
let d = im.encoder();
if tags.reduced {
d.write_tag(Tag::Unknown(TAG_NEW_SUBFILE_TYPE), 1u32)?;
}
if !tags.extra_samples.is_empty() {
d.write_tag(Tag::ExtraSamples, tags.extra_samples)?;
}
@@ -374,6 +382,117 @@ fn write_image<K: TiffKind>(enc: &mut TiffEncoder<&mut Cursor<Vec<u8>>, K>, img:
}
}
/// Writes the image pyramid after the full image: each level half the size of the one before
/// (rounded up), colour and alpha only, until the longer side is at most
/// [`crate::TIFF_PYRAMID_MIN`]. An image already that small gets no levels.
fn write_pyramid<K: TiffKind>(enc: &mut TiffEncoder<&mut Cursor<Vec<u8>>, K>, img: &Image, tags: &TagSet<'_>) -> tiff::TiffResult<()> {
let mut level: Option<Image> = None;
loop {
let prev = level.as_ref().unwrap_or(img);
let (w, h) = prev.dimensions();
if w.max(h) <= crate::TIFF_PYRAMID_MIN {
return Ok(());
}
let next = half_size(prev).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e.to_string()))?;
write_image::<K>(enc, &next, tags)?;
level = Some(next);
}
}
/// `img` at half its size, rounded up, by averaging each 2×2 block (an odd last row or column
/// averages what it has). Colour is weighted by alpha, so transparent pixels don't darken
/// the edges of what they surround. Extra samples are not carried over. Rows are worked in
/// parallel on native targets.
pub(super) fn half_size(img: &Image) -> Result<Image, CodecError> {
let (w, h) = img.dimensions();
let (nw, nh) = (w.div_ceil(2).max(1), h.div_ceil(2).max(1));
let layout = img.layout();
let sample = img.sample_type();
let ch = layout.channels();
let bps = sample.bytes();
let src_row = (w as usize).checked_mul(ch).and_then(|n| n.checked_mul(bps)).ok_or_else(|| CodecError::encode(F, "image row size overflows"))?;
let out_row = (nw as usize).checked_mul(ch).and_then(|n| n.checked_mul(bps)).ok_or_else(|| CodecError::encode(F, "pyramid row size overflows"))?;
let len = out_row.checked_mul(nh as usize).ok_or_else(|| CodecError::encode(F, "pyramid level size overflows"))?;
if img.data().len() < src_row.saturating_mul(h as usize) {
return Err(CodecError::encode(F, "image buffer is shorter than its dimensions"));
}
let mut out = super::bands::zeroed(len)?;
let level = Level { data: img.data(), w: w as usize, h: h as usize, ch, sample, src_row, alpha: layout.has_alpha() };
#[cfg(not(target_arch = "wasm32"))]
{
use rayon::prelude::*;
out.par_chunks_mut(out_row.max(1)).enumerate().for_each(|(y, row)| level.row(y, row));
}
#[cfg(target_arch = "wasm32")]
out.chunks_mut(out_row.max(1)).enumerate().for_each(|(y, row)| level.row(y, row));
let mut img2 = Image::from_raw(nw, nh, layout, sample, out)?;
img2.icc = img.icc.clone();
Ok(img2)
}
/// The source of one [`half_size`] level.
struct Level<'a> {
data: &'a [u8],
w: usize,
h: usize,
ch: usize,
sample: SampleType,
src_row: usize,
/// The last channel is alpha.
alpha: bool,
}
impl Level<'_> {
/// Source row `y` as numbers (empty past the bottom).
fn samples(&self, y: usize) -> Vec<f64> {
let Some(row) = (y < self.h).then(|| self.data.get(y * self.src_row..(y + 1) * self.src_row)).flatten() else { return Vec::new() };
match self.sample {
SampleType::U8 => row.iter().map(|&v| f64::from(v)).collect(),
SampleType::U16 => row.as_chunks::<2>().0.iter().map(|b| f64::from(u16::from_ne_bytes(*b))).collect(),
SampleType::F32 => row.as_chunks::<4>().0.iter().map(|b| f64::from(f32::from_ne_bytes(*b))).collect(),
SampleType::F16 => row.as_chunks::<2>().0.iter().map(|b| f64::from(half::f16::from_bits(u16::from_ne_bytes(*b)).to_f32())).collect(),
}
}
/// Writes output row `y` into `out`.
fn row(&self, y: usize, out: &mut [u8]) {
let rows = [self.samples(y * 2), self.samples(y * 2 + 1)];
let ch = self.ch;
let bps = self.sample.bytes();
let mut sums = vec![0f64; ch];
for (x, px) in out.chunks_exact_mut(ch * bps).enumerate() {
sums.iter_mut().for_each(|s| *s = 0.0);
let (mut n, mut weight) = (0f64, 0f64);
for row in rows.iter().filter(|r| !r.is_empty()) {
for sx in [x * 2, x * 2 + 1].into_iter().filter(|&sx| sx < self.w) {
let Some(p) = row.get(sx * ch..(sx + 1) * ch) else { continue };
let a = if self.alpha { p.last().copied().unwrap_or(1.0) } else { 1.0 };
for (c, (sum, v)) in sums.iter_mut().zip(p).enumerate() {
*sum += if self.alpha && c + 1 == ch { *v } else { v * a };
}
n += 1.0;
weight += a;
}
}
for (c, (sum, dst)) in sums.iter().zip(px.chunks_exact_mut(bps)).enumerate() {
let v = if self.alpha && c + 1 == ch {
sum / n.max(1.0)
} else if weight > 0.0 {
sum / weight
} else {
0.0
};
match self.sample {
SampleType::U8 => dst.copy_from_slice(&[v.round().clamp(0.0, 255.0) as u8]),
SampleType::U16 => dst.copy_from_slice(&(v.round().clamp(0.0, 65535.0) as u16).to_ne_bytes()),
SampleType::F32 => dst.copy_from_slice(&(v as f32).to_ne_bytes()),
SampleType::F16 => dst.copy_from_slice(&half::f16::from_f32(v as f32).to_bits().to_ne_bytes()),
}
}
}
}
}
/// Classic TIFF offsets are 32-bit: a file that may grow past this is written as BigTIFF.
const CLASSIC_LIMIT: u64 = u32::MAX as u64;
@@ -476,12 +595,28 @@ fn encode_ready(img: &Image, opts: &EncodeOptions) -> Result<Vec<u8>, CodecError
// Document content, not metadata: written whenever present.
photoshop_resources: img.meta.photoshop_resources.as_deref().filter(|r| !r.is_empty()),
photoshop_layers: img.meta.photoshop_layers.as_deref().filter(|l| !l.is_empty()),
reduced: false,
};
// A pyramid level holds the colour and alpha only, with the profile so it shows the same.
let alpha_kind: &[u16] = if img.layout().has_alpha() { &[2] } else { &[] };
let level_tags = TagSet {
icc: tags.icc,
exif: None,
xmp: None,
dpi: None,
text: Vec::new(),
extra_samples: alpha_kind,
photoshop_resources: None,
photoshop_layers: None,
reduced: true,
};
// BigTIFF when asked, or when the file could pass the 4 GiB a classic TIFF can address. A
// classic write that still runs out of 32-bit offsets (compression grew the data) is redone
// as BigTIFF.
let estimate = estimated_size(img, &tags);
// The pyramid adds at most a third of the image (1/4 + 1/16 + …).
let estimate = if opts.tiff_pyramid { estimate.saturating_add(img.data().len() as u64 / 3) } else { estimate };
let write = |big: bool| -> tiff::TiffResult<Vec<u8>> {
// An uncompressed file is allocated once at its estimated size: grown as written, the
// buffer would double near the end and copy the file (#6607). Compressed output is
@@ -497,9 +632,15 @@ fn encode_ready(img: &Image, opts: &EncodeOptions) -> Result<Vec<u8>, CodecError
if big {
let mut enc = TiffEncoder::new_big(&mut cursor)?.with_compression(compression).with_predictor(predictor);
write_image::<TiffKindBig>(&mut enc, img, &tags)?;
if opts.tiff_pyramid {
write_pyramid::<TiffKindBig>(&mut enc, img, &level_tags)?;
}
} else {
let mut enc = TiffEncoder::new(&mut cursor)?.with_compression(compression).with_predictor(predictor);
write_image::<TiffKindStandard>(&mut enc, img, &tags)?;
if opts.tiff_pyramid {
write_pyramid::<TiffKindStandard>(&mut enc, img, &level_tags)?;
}
}
// Growth (or an estimate that was too high) can leave spare capacity: give it back
// instead of holding it while the file is saved.
+2 -1
View File
@@ -45,7 +45,8 @@ pub use crate::image::{
MAX_EXTRA_SAMPLES, Metadata, SampleType,
};
pub use crate::options::{
DdsCompression, DdsOptions, DecodeOptions, DpxBits, EncodeOptions, ExrCompression, JpegFormat, Limits, PngCompression, PngStereo, TiffCompression,
DdsCompression, DdsOptions, DecodeOptions, DpxBits, EncodeOptions, ExrCompression, JpegFormat, Limits, PngCompression, PngStereo, TIFF_PYRAMID_MIN,
TiffCompression,
};
pub use crate::orientation::{exif_orientation, upright_exif, upright_xmp};
pub use crate::resolution::{exif_resolution, export_exif, export_xmp, photoshop_resolution, xmp_resolution};
+10
View File
@@ -286,6 +286,10 @@ pub struct DdsOptions {
pub mipmaps: bool,
}
/// The longer side, in pixels, at which a TIFF image pyramid stops: the last level written is
/// the first one no longer than this ([`EncodeOptions::tiff_pyramid`]).
pub const TIFF_PYRAMID_MIN: u32 = 64;
/// Options for [`crate::encode`].
#[derive(Debug, Clone)]
pub struct EncodeOptions {
@@ -310,6 +314,11 @@ pub struct EncodeOptions {
/// Always write TIFF as BigTIFF (8-byte offsets). Without it a TIFF is written as BigTIFF
/// only when it could pass the 4 GiB a classic TIFF can address.
pub tiff_bigtiff: bool,
/// TIFF: after the full image, write Photoshop's "Save Image Pyramid" levels: copies at half,
/// a quarter, … of the size, each marked reduced-resolution (`NewSubfileType` 1), down to
/// [`crate::TIFF_PYRAMID_MIN`] px on the longer side. Readers that don't know pyramids open
/// the full image, which comes first.
pub tiff_pyramid: bool,
pub exr_compression: ExrCompression,
/// DPX bits per sample. `None` follows the image: 8 for 8-bit, 16 otherwise.
pub dpx_bits: Option<DpxBits>,
@@ -334,6 +343,7 @@ impl Default for EncodeOptions {
webp_quality: 80,
tiff_compression: TiffCompression::None,
tiff_bigtiff: false,
tiff_pyramid: false,
exr_compression: ExrCompression::Zip16,
dpx_bits: None,
dds: DdsOptions::default(),
+1
View File
@@ -31,6 +31,7 @@ mod tiff_exif;
mod tiff_lab;
mod tiff_pages;
mod tiff_photoshop;
mod tiff_pyramid;
mod tiff_regressions;
mod tiff_ycbcr;
mod webp_frames;
+17
View File
@@ -105,3 +105,20 @@ fn decode_30mp() {
let d = strips(W, H, 8, 3, 2, 64, &rgb);
time("RGB 8 BigTIFF strips, none", &build(le, true, &[d], &[0]).bytes);
}
/// Save Image Pyramid's cost on top of a plain encode (#8827): RGB/8 and RGBA/16.
#[test]
#[ignore = "benchmark: run in release with --ignored --nocapture"]
fn encode_with_pyramid() {
for (layout, sample, spp) in [(ChannelLayout::Rgb, SampleType::U8, 3), (ChannelLayout::Rgba, SampleType::U16, 4)] {
let raw = pixels(spp);
let data = if sample == SampleType::U16 { raw.iter().flat_map(|&v| (u16::from(v) * 257).to_ne_bytes()).collect() } else { raw };
let img = Image::from_raw(W, H, layout, sample, data).unwrap();
for pyramid in [false, true] {
let opts = EncodeOptions { tiff_pyramid: pyramid, ..Default::default() };
let t = Instant::now();
let bytes = encode(&img, Format::Tiff, &opts).unwrap();
println!("{layout:?} {sample:?} pyramid {pyramid}: {:.0} ms, {} MB", t.elapsed().as_secs_f64() * 1000.0, bytes.len() >> 20);
}
}
}
+184
View File
@@ -0,0 +1,184 @@
//! TIFF "Save Image Pyramid" (#8827): reduced-resolution levels after the full image, each half
//! the size of the one before, that every reader skips when it opens the file.
use photocraft_codecs::*;
fn pyramid() -> EncodeOptions {
EncodeOptions { tiff_pyramid: true, ..Default::default() }
}
/// An image of `layout`/`sample` where every sample is `v` (on the 0–1 scale).
fn solid(w: u32, h: u32, layout: ChannelLayout, sample: SampleType, v: f32) -> Image {
let n = w as usize * h as usize * layout.channels();
let data: Vec<u8> = match sample {
SampleType::U8 => vec![(v * 255.0).round() as u8; n],
SampleType::U16 => (0..n).flat_map(|_| ((v * 65535.0).round() as u16).to_ne_bytes()).collect(),
SampleType::F32 => (0..n).flat_map(|_| v.to_ne_bytes()).collect(),
SampleType::F16 => (0..n).flat_map(|_| f16::from_f32(v).to_bits().to_ne_bytes()).collect(),
};
Image::from_raw(w, h, layout, sample, data).unwrap()
}
fn sizes(bytes: &[u8]) -> Vec<(TiffPageKind, u32, u32)> {
tiff_info(bytes).unwrap().pages.iter().map(|p| (p.kind, p.width, p.height)).collect()
}
#[test]
fn levels_halve_down_to_the_minimum() {
use TiffPageKind::*;
let img = solid(300, 200, ChannelLayout::Rgb, SampleType::U8, 0.5);
let bytes = encode(&img, Format::Tiff, &pyramid()).unwrap();
// 300 → 150 → 75 → 38: the first level no longer than 64 px is the last.
assert_eq!(sizes(&bytes), [(Page, 300, 200), (ReducedResolution, 150, 100), (ReducedResolution, 75, 50), (ReducedResolution, 38, 25)]);
// Opening the file opens the full image, and the levels are not extra pages.
let back = decode(&bytes).unwrap();
assert_eq!(back.dimensions(), (300, 200));
assert_eq!(back.data(), img.data());
assert!(!back.warnings.iter().any(|w| matches!(w, DecodeWarning::MorePages { .. })), "{:?}", back.warnings);
}
#[test]
fn off_by_default_and_none_for_small_images() {
let img = solid(300, 200, ChannelLayout::Rgb, SampleType::U8, 0.5);
assert_eq!(sizes(&encode(&img, Format::Tiff, &EncodeOptions::default()).unwrap()).len(), 1);
let small = solid(64, 10, ChannelLayout::Rgb, SampleType::U8, 0.5);
assert_eq!(sizes(&encode(&small, Format::Tiff, &pyramid()).unwrap()).len(), 1);
// A 1-px-wide strip still halves its long side.
let strip = solid(1, 200, ChannelLayout::Gray, SampleType::U8, 0.5);
let s = sizes(&encode(&strip, Format::Tiff, &pyramid()).unwrap());
assert_eq!(s.iter().map(|&(_, w, h)| (w, h)).collect::<Vec<_>>(), [(1, 200), (1, 100), (1, 50)]);
}
#[test]
fn every_depth_layout_and_compression() {
let layouts =
[ChannelLayout::Gray, ChannelLayout::GrayA, ChannelLayout::Rgb, ChannelLayout::Rgba, ChannelLayout::Cmyk, ChannelLayout::CmykA, ChannelLayout::Lab];
for layout in layouts {
for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {
for compression in [TiffCompression::None, TiffCompression::Lzw, TiffCompression::Deflate, TiffCompression::PackBits] {
let img = solid(120, 70, layout, sample, 0.6);
let opts = EncodeOptions { tiff_compression: compression, ..pyramid() };
let bytes = encode(&img, Format::Tiff, &opts).unwrap_or_else(|e| panic!("{layout:?} {sample:?} {compression:?}: {e}"));
let info = tiff_info(&bytes).unwrap();
assert_eq!(info.pages.len(), 2, "{layout:?} {sample:?} {compression:?}");
let level = decode_tiff_page(&bytes, 1, &DecodeOptions::default()).unwrap();
assert_eq!(level.dimensions(), (60, 35));
assert_eq!(level.layout(), decode(&bytes).unwrap().layout(), "{layout:?} {sample:?}");
// A solid image stays the same colour at every level.
let full = decode(&bytes).unwrap().convert(level.layout(), SampleType::F32);
let level = level.convert(level.layout(), SampleType::F32);
let (a, b) = (full.to_f32_samples().unwrap(), level.to_f32_samples().unwrap());
for (c, v) in b.iter().take(level.layout().channels()).enumerate() {
assert!((v - a[c]).abs() < 1e-3, "{layout:?} {sample:?} channel {c}: {v} vs {}", a[c]);
}
}
}
}
}
/// A 128×128 image of 2×2 `tile`s (top left, top right, bottom left, bottom right; alpha last),
/// and the first pixel of its first reduced level.
fn first_level_pixel(layout: ChannelLayout, tile: [&[u8]; 4]) -> Vec<u8> {
let mut data = Vec::new();
for _ in 0..64 {
for x in 0..128 {
data.extend_from_slice(tile[x % 2]);
}
for x in 0..128 {
data.extend_from_slice(tile[2 + x % 2]);
}
}
let img = Image::from_raw(128, 128, layout, SampleType::U8, data).unwrap();
let bytes = encode(&img, Format::Tiff, &pyramid()).unwrap();
let level = decode_tiff_page(&bytes, 1, &DecodeOptions::default()).unwrap();
assert_eq!(level.dimensions(), (64, 64), "{layout:?}");
assert_eq!(level.layout(), layout);
level.data()[..layout.channels()].to_vec()
}
#[test]
fn colour_is_weighted_by_alpha() {
// One opaque pixel and three transparent ones of another colour: the level keeps the opaque
// colour at a quarter alpha. Unweighted, the transparent colour would bleed in (pink, not red).
assert_eq!(first_level_pixel(ChannelLayout::Rgba, [&[255, 0, 0, 255], &[255, 255, 255, 0], &[255, 255, 255, 0], &[255, 255, 255, 0]]), [255, 0, 0, 64]);
// Gray and CMYK reach the same path with other channel counts.
assert_eq!(first_level_pixel(ChannelLayout::GrayA, [&[40, 255], &[255, 0], &[255, 0], &[255, 0]]), [40, 64]);
assert_eq!(first_level_pixel(ChannelLayout::CmykA, [&[200, 10, 30, 90, 255], &[0; 5], &[0; 5], &[0; 5]]), [200, 10, 30, 90, 64]);
}
#[test]
fn colour_is_weighted_between_translucent_pixels() {
// Two half-transparent pixels of different colours (red, blue) and two clear ones: the level
// averages the two by their alpha (purple), where copying either pixel would give red or blue.
let tile: [&[u8]; 4] = [&[255, 0, 0, 128], &[0, 0, 255, 128], &[0; 4], &[0; 4]];
assert_eq!(first_level_pixel(ChannelLayout::Rgba, tile), [128, 0, 128, 64]);
}
#[test]
fn layered_and_tagged_data_stay_on_the_full_image() {
let mut img = solid(200, 100, ChannelLayout::Rgb, SampleType::U8, 0.25);
img.icc = Some(photocraft_cms_free_profile());
img.meta.photoshop_layers = Some(vec![1, 2, 3, 4]);
img.meta.extra_samples = vec![ExtraSample { kind: 0, data: vec![9; 200 * 100] }];
let bytes = encode(&img, Format::Tiff, &pyramid()).unwrap();
let info = tiff_info(&bytes).unwrap();
assert_eq!(info.pages.len(), 3);
// Only the full image carries the layers and the extra samples.
assert_eq!(info.pages[0].samples_per_pixel, 4);
assert!(info.pages[1..].iter().all(|p| p.samples_per_pixel == 3));
assert_eq!(tiff_photoshop_tags(&bytes).1, Some(&[1u8, 2, 3, 4][..]));
let level = decode_tiff_page(&bytes, 1, &DecodeOptions::default()).unwrap();
assert_eq!(level.icc, img.icc, "levels keep the profile so they show the same colours");
assert!(level.meta.extra_samples.is_empty());
}
/// Any bytes a decoder keeps as the ICC profile: the codec stores it without parsing.
fn photocraft_cms_free_profile() -> Vec<u8> {
(0..=255u8).collect()
}
#[test]
fn levels_average_exactly_at_every_depth() {
// One 2×2 block of gray values 0, 0.25, 0.5, 1 averages to 0.4375; a 2×2 block with half
// transparent pixels keeps only the opaque colour and averages the alpha.
for sample in [SampleType::U16, SampleType::F32] {
let vals = [0.0f32, 0.25, 0.5, 1.0];
let mut img = solid(130, 2, ChannelLayout::Gray, sample, 0.0);
let w = 130;
for (i, v) in vals.iter().enumerate() {
let (x, y) = (i % 2, i / 2);
let at = (y * w + x) * sample.bytes();
let bytes: Vec<u8> = match sample {
SampleType::U16 => ((v * 65535.0).round() as u16).to_ne_bytes().to_vec(),
_ => v.to_ne_bytes().to_vec(),
};
img.data_mut()[at..at + bytes.len()].copy_from_slice(&bytes);
}
let bytes = encode(&img, Format::Tiff, &pyramid()).unwrap();
let level = decode_tiff_page(&bytes, 1, &DecodeOptions::default()).unwrap().convert(ChannelLayout::Gray, SampleType::F32);
let v = level.to_f32_samples().unwrap()[0];
assert!((v - 0.4375).abs() < 1e-4, "{sample:?}: {v}");
}
let mut data = Vec::new();
for _ in 0..2 {
for x in 0..130u32 {
// RGBA16: opaque blue on even columns, transparent red on odd.
let px: [u16; 4] = if x % 2 == 0 { [0, 0, 65535, 65535] } else { [65535, 0, 0, 0] };
data.extend(px.iter().flat_map(|v| v.to_ne_bytes()));
}
}
let img = Image::from_raw(130, 2, ChannelLayout::Rgba, SampleType::U16, data).unwrap();
let bytes = encode(&img, Format::Tiff, &pyramid()).unwrap();
let level = decode_tiff_page(&bytes, 1, &DecodeOptions::default()).unwrap();
assert_eq!(level.to_u16_samples().unwrap()[..4], [0, 0, 65535, 32768]);
}
#[test]
fn bigtiff_files_carry_the_pyramid_too() {
let img = solid(300, 200, ChannelLayout::Rgba, SampleType::U8, 0.5);
let bytes = encode(&img, Format::Tiff, &EncodeOptions { tiff_bigtiff: true, ..pyramid() }).unwrap();
let info = tiff_info(&bytes).unwrap();
assert!(info.big_tiff);
assert_eq!(info.pages.iter().map(|p| (p.kind, p.width)).collect::<Vec<_>>().len(), 4);
assert_eq!(decode_tiff_page(&bytes, 3, &DecodeOptions::default()).unwrap().dimensions(), (38, 25));
}
+6 -5
View File
@@ -54,7 +54,8 @@ use processing::{conditional_mode_change, fit_image, flatten_all_effects, flatte
use save::save_a_copy;
pub(crate) use save::{SaveOpts, encode, save_doc};
pub use save::{
dds_param, dpx_bits_param, jpeg_format_param, jpeg_quality, pcraft_full_composite_param, tga_bits_param, tiff_compression_param, tiff_would_write_layers,
dds_param, dpx_bits_param, jpeg_format_param, jpeg_quality, pcraft_full_composite_param, tga_bits_param, tiff_bool_param, tiff_compression_param,
tiff_would_write_layers,
};
mod batch_naming;
@@ -254,7 +255,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Save a Copy…",
&["File"],
Some("Cmd+Alt+S"),
r##"{"path":str (format from the extension),"quality":0..12? (JPEG),"jpegFormat":"baseline|optimized|progressive"? (JPEG; default baseline),"layers":bool=true,"overwrite":bool=false (replace the document's own file),"tiffLayers":bool=false (TIFF: keep the layers; flat by default),"tiffCompression":"none|lzw|zip"? (TIFF: image compression; unset, none),"tgaBits":24|32? (TGA: 32 writes the alpha channel, or else the transparency, as the alpha; unset, 32 with an alpha channel or transparency, else 24),"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"pcraftFullComposite":bool? (.pcraft: request the flattened document at its canvas size as composite/full.png; it may be omitted; check the manifest's full_composite member; unset, Preferences › File Handling)}"##,
r##"{"path":str (format from the extension),"quality":0..12? (JPEG),"jpegFormat":"baseline|optimized|progressive"? (JPEG; default baseline),"layers":bool=true,"overwrite":bool=false (replace the document's own file),"tiffLayers":bool=false (TIFF: keep the layers; flat by default),"tiffCompression":"none|lzw|zip"? (TIFF: image compression; unset, none),"tiffTransparency":bool? (TIFF: Save Transparency; off composites over white; unset, kept unless the document has alpha or spot channels),"tiffPyramid":bool=false (TIFF: Save Image Pyramid, half-size copies after the image),"tgaBits":24|32? (TGA: 32 writes the alpha channel, or else the transparency, as the alpha; unset, 32 with an alpha channel or transparency, else 24),"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"pcraftFullComposite":bool? (.pcraft: request the flattened document at its canvas size as composite/full.png; it may be omitted; check the manifest's full_composite member; unset, Preferences › File Handling)}"##,
native_doc,
save_a_copy
),
@@ -331,7 +332,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Batch…",
&["File", "Automate"],
None,
r##"{"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action; a Save, Save As or Save a Copy step marks the document written to output, in this command's format and options: as the save found it if it was closed or another document is active at the end, else as the action leaves it; with no such step, the active document at the end),"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"same|png|jpg|psd|tiff|…"="same","quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"naming":string? (blank keeps source names; {name}, {serial} padded to 3 digits, {date} as YYYY-MM-DD UTC; extension added automatically),"startingSerial":1..4294967295=1 (input position, including failed inputs),"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"calledActions":[{"name","steps"}…]? (the actions Play Action steps call; default: the session's)} → {files, errors} (an input whose output name was already written in the run goes to errors)"##,
r##"{"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action; a Save, Save As or Save a Copy step marks the document written to output, in this command's format and options: as the save found it if it was closed or another document is active at the end, else as the action leaves it; with no such step, the active document at the end),"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"same|png|jpg|psd|tiff|…"="same","quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"naming":string? (blank keeps source names; {name}, {serial} padded to 3 digits, {date} as YYYY-MM-DD UTC; extension added automatically),"startingSerial":1..4294967295=1 (input position, including failed inputs),"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tiffTransparency":bool?,"tiffPyramid":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"calledActions":[{"name","steps"}…]? (the actions Play Action steps call; default: the session's)} → {files, errors} (an input whose output name was already written in the run goes to errors)"##,
native,
batch
),
@@ -340,7 +341,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Image Processor…",
&["File", "Scripts"],
None,
r##"{"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"jpg|png|psd|tiff|…"="jpg","quality":0..12=8,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"width":px?,"height":px? (fit, never enlarge),"convertToSrgb":bool=false} → {files, errors} (an input whose output name was already written in the run goes to errors)"##,
r##"{"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"jpg|png|psd|tiff|…"="jpg","quality":0..12=8,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tiffTransparency":bool?,"tiffPyramid":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"width":px?,"height":px? (fit, never enlarge),"convertToSrgb":bool=false} → {files, errors} (an input whose output name was already written in the run goes to errors)"##,
native,
image_processor
),
@@ -368,7 +369,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Layers to Files…",
&["File", "Export"],
None,
r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"visibleOnly":bool=true,"trim":bool=false,"quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain)} → {files}"##,
r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"visibleOnly":bool=true,"trim":bool=false,"quality":0..12?,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tiffTransparency":bool?,"tiffPyramid":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain)} → {files}"##,
native_doc,
layers_to_files
),
+22
View File
@@ -26,6 +26,11 @@ pub(crate) struct SaveOpts {
pub dpx_bits: Option<photocraft_io::DpxBits>,
/// TIFF: the image compression (`"tiffCompression": "none" | "lzw" | "zip"`); unset, none.
pub tiff_compression: Option<photocraft_codecs::TiffCompression>,
/// TIFF: Save Transparency (`"tiffTransparency": bool`); unset, the transparency is kept
/// unless the document has alpha or spot channels ([`photocraft_io::ExportOptions::tiff_transparency`]).
pub tiff_transparency: Option<bool>,
/// TIFF: Save Image Pyramid (`"tiffPyramid": bool`); unset, off.
pub tiff_pyramid: bool,
/// DDS: the compression and whether to write the mip chain (`"ddsCompression"`,
/// `"ddsMipmaps"`); unset, uncompressed without mipmaps.
pub dds: photocraft_io::DdsOptions,
@@ -49,6 +54,8 @@ impl Default for SaveOpts {
tga_bits: None,
dpx_bits: None,
tiff_compression: None,
tiff_transparency: None,
tiff_pyramid: false,
dds: photocraft_io::DdsOptions::default(),
image_previews: true,
psd_maximize_compatibility: true,
@@ -73,6 +80,8 @@ impl SaveOpts {
tga_bits: tga_bits_param(p, cmd)?,
dpx_bits: dpx_bits_param(p, cmd)?,
tiff_compression: tiff_compression_param(p, cmd)?,
tiff_transparency: tiff_bool_param(p, "tiffTransparency", cmd)?,
tiff_pyramid: tiff_bool_param(p, "tiffPyramid", cmd)?.unwrap_or(false),
dds: dds_param(p, cmd)?.unwrap_or_default(),
image_previews: file_handling.image_previews != crate::prefs::Ask::Never,
psd_maximize_compatibility: file_handling.maximize_psd_compatibility != crate::prefs::Ask::Never,
@@ -133,6 +142,17 @@ pub fn tiff_compression_param(p: &Value, cmd: &str) -> Result<Option<photocraft_
}
}
/// A TIFF Options checkbox in `p`: `"tiffTransparency"` (Save Transparency) or `"tiffPyramid"`
/// (Save Image Pyramid), `true` or `false`; absent or null: unset. Anything else is a bad
/// parameter of command `cmd` (#8827).
pub fn tiff_bool_param(p: &Value, key: &str, cmd: &str) -> Result<Option<bool>> {
match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(Value::Bool(b)) => Ok(Some(*b)),
Some(v) => Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("`{key}` must be true or false, got {v}") }),
}
}
/// The JPEG format in `p` (`"jpegFormat": "baseline" | "optimized" | "progressive"`; absent or
/// null: Baseline). Anything else is a bad parameter of command `cmd`. Shared like
/// [`tga_bits_param`].
@@ -195,6 +215,7 @@ pub(crate) fn encode(doc: &Document, path: &str, save: impl Into<SaveOpts>) -> R
let save = save.into();
let mut opts = photocraft_io::ExportOptions {
tiff_layers: save.tiff_layers,
tiff_transparency: save.tiff_transparency,
tga_bits: save.tga_bits,
image_previews: save.image_previews,
psd_maximize_compatibility: save.psd_maximize_compatibility,
@@ -212,6 +233,7 @@ pub(crate) fn encode(doc: &Document, path: &str, save: impl Into<SaveOpts>) -> R
if let Some(c) = save.tiff_compression {
opts.encode.tiff_compression = c;
}
opts.encode.tiff_pyramid = save.tiff_pyramid;
opts.encode.dds = save.dds;
if let Some(q) = save.quality {
let q = jpeg_quality(q);
+30
View File
@@ -2026,6 +2026,36 @@ fn save_a_copy_writes_the_tiff_compression_asked_for() {
}
}
/// #8827: `tiffPyramid` writes reduced-resolution levels after the image and `tiffTransparency`
/// false composites a transparent document over white. Bad values are refused before anything is
/// written.
#[test]
fn save_a_copy_writes_the_tiff_pyramid_and_transparency_asked_for() {
let dir = tmp("tiff-options");
let mut s = Session::new();
s.execute("file.new", json!({"width": 200, "height": 100, "background": "transparent"})).unwrap();
let out = join(&dir, "p.tif");
s.execute("file.saveACopy", json!({"path": out, "tiffPyramid": true})).unwrap();
let bytes = std::fs::read(&out).unwrap();
let sizes: Vec<(u32, u32)> = photocraft_codecs::tiff_info(&bytes).unwrap().pages.iter().map(|p| (p.width, p.height)).collect();
assert_eq!(sizes, [(200, 100), (100, 50), (50, 25)]);
for (t, alpha) in [(None, true), (Some(true), true), (Some(false), false)] {
let mut p = json!({"path": out});
if let Some(t) = t {
p["tiffTransparency"] = json!(t);
}
s.execute("file.saveACopy", p).unwrap();
let img = photocraft_codecs::decode(&std::fs::read(&out).unwrap()).unwrap();
assert_eq!(img.layout().has_alpha(), alpha, "{t:?}");
}
for (key, bad) in [("tiffPyramid", json!("yes")), ("tiffPyramid", json!(1)), ("tiffTransparency", json!("off")), ("tiffTransparency", json!([]))] {
let out = join(&dir, "bad.tif");
let r = s.execute("file.saveACopy", json!({"path": out, key: bad}));
assert!(matches!(r, Err(EngineError::BadParams { .. })), "{key} {bad}: {r:?}");
assert!(!std::path::Path::new(&out).exists(), "{key} {bad}: nothing written");
}
}
#[test]
fn sanitize_keeps_windows_device_names_off_the_disk() {
assert_eq!(sanitize("nul"), "nul_");
+1 -1
View File
@@ -999,7 +999,7 @@ pub(crate) fn export_flat_with(doc: &Document, format: Format, opts: &ExportOpti
img = dds_image(doc, img, &mut warnings)?;
}
if format == Format::Tiff {
warnings.extend(crate::tiff_layers::stamp_flat_channels(doc, &mut img));
warnings.extend(crate::tiff_layers::flat_transparency_and_channels(doc, &mut img, opts.tiff_transparency));
}
encode_image(&img, format, opts, warnings)
}
+8
View File
@@ -370,6 +370,13 @@ pub struct ExportOptions {
/// Save As sets it from its Layers option, which keeps them as Photoshop does. `false` is
/// Photoshop's "Discard Layers and Save a Copy".
pub tiff_layers: bool,
/// TIFF: Photoshop's "Save Transparency" for the composite (the merged image other readers
/// see; each layer of a layered TIFF keeps its own transparency either way). `Some(true)`
/// stores the transparency as the first extra sample (unassociated alpha), ahead of any
/// alpha and spot channels; `Some(false)` composites the image over white and stores no
/// transparency. `None`, the default, keeps it unless the document has alpha or spot
/// channels, which are then written as with it off.
pub tiff_transparency: Option<bool>,
/// Which part of the document's XMP packet and free-form text a flat export embeds.
/// PSD/PSB always keep XMP; `.pcraft` keeps both. Everything by default, as Save As does;
/// Export As offers None.
@@ -405,6 +412,7 @@ impl Default for ExportOptions {
encode: EncodeOptions::default(),
force_psb: false,
tiff_layers: false,
tiff_transparency: None,
xmp: XmpEmbed::All,
tga_bits: None,
image_previews: true,
+87 -36
View File
@@ -355,11 +355,13 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocr
// on the encoded file size is not used here: PSB-style data is written only past 30000 px,
// when asked for, or when a length really overflows 32 bits.
let user_channels = !doc.channels.is_empty() || doc.quick_mask.is_some();
// Save Transparency (see `ExportOptions::tiff_transparency`): off, the composite is matted.
let save_transparency = opts.tiff_transparency.unwrap_or(!user_channels);
let force_psb = opts.force_psb || big;
let psd_opts = PsdExportOptions {
force_psb,
size_limit_psb: false,
merged_matte: user_channels,
merged_matte: !save_transparency,
merged_compression: Compression::Raw,
maximize_compatibility: true,
document_path: opts.document_path.clone(),
@@ -384,7 +386,7 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocr
let mut has_alpha = file.layer_info.as_ref().is_some_and(|l| l.merged_alpha);
// The layers move out of the model rather than being copied, and are freed once written
// (#6607); the model keeps its header, resources and composite for the image below.
let (layers, w) = match tiff_image_source(doc, &mut file).into_bytes(order) {
let (layers, w) = match tiff_image_source(doc, &mut file, save_transparency && has_alpha).into_bytes(order) {
Err(photocraft_psd::PsdError::LimitExceeded(_)) if !force_psb => {
let psb_opts = PsdExportOptions { force_psb: true, ..psd_opts };
let (psb, w) = crate::with_span(ctl, 0.0, TIFF_MODEL_DONE, |ctl| crate::psd_export::document_to_psd_interruptible(doc, &psb_opts, ctl));
@@ -393,7 +395,7 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocr
warnings.push("layer data exceeds 4 GB; written with PSB-sized lengths, which some readers do not open".into());
file = psb;
has_alpha = file.layer_info.as_ref().is_some_and(|l| l.merged_alpha);
tiff_image_source(doc, &mut file).into_bytes(order)?
tiff_image_source(doc, &mut file, save_transparency && has_alpha).into_bytes(order)?
}
r => r?,
};
@@ -413,19 +415,22 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocr
if extra_n > kept {
warnings.push(format!("{extra_n} extra channels; TIFF keeps the first {kept}"));
}
// With spot or alpha channels, the IFD image is colour + those channels. The merged
// transparency plane stays out of the IFD (see above); a file with no extra channels keeps
// it, so a plain transparent TIFF still opens with alpha.
let write_alpha = has_alpha && kept == 0;
// The IFD image is colour, then the transparency with Save Transparency on, then the spot and
// alpha channels. With it on, the samples are the PSD merged image's channels in order, so
// the PSD model's channel resources (which list the transparency first) are kept as they are.
let write_alpha = has_alpha && save_transparency;
// One identifier per extra sample actually stored. The PSD model's 1053 lists the merged
// transparency too, which the IFD leaves out next to extra samples, so it is not copied.
resources.retain(|r| r.id != crate::channel_map::ALPHA_IDENTIFIERS);
if kept > 0 {
resources.push(ImageResource::new(crate::channel_map::ALPHA_IDENTIFIERS, crate::channel_map::alpha_identifiers(false, kept)));
// transparency too, which the IFD leaves out without it, so it is not copied then.
if !write_alpha {
resources.retain(|r| r.id != crate::channel_map::ALPHA_IDENTIFIERS);
if kept > 0 {
resources.push(ImageResource::new(crate::channel_map::ALPHA_IDENTIFIERS, crate::channel_map::alpha_identifiers(false, kept)));
}
}
// Resource 1022 names a channel of the PSD merged image, which counts the transparency plane.
// The IFD below does not, so the id moves back by one.
// An IFD without it does not, so the id moves back by one.
if has_alpha
&& !write_alpha
&& kept > 0
&& let Some(r) = resources.iter_mut().find(|r| r.id == crate::channel_map::QUICK_MASK_INFO)
&& r.data.len() >= 2
@@ -443,8 +448,10 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocr
}
// Past MAX_EXTRA_SAMPLES the TIFF stores only the first `kept` channels: the name and
// DisplayInfo resources describe just those, and a Quick Mask among the rest is dropped.
// With the transparency written, those lists hold it ahead of the channels, and the
// channels sit one sample later in the IFD.
if extra_n > kept {
keep_first_channels(&mut resources, kept, cc);
keep_first_channels(&mut resources, kept + usize::from(write_alpha), cc);
}
let resources = resources_to_bytes(&resources)?;
let ifd_channels = cc + usize::from(write_alpha);
@@ -478,26 +485,34 @@ pub(crate) fn export_layered(doc: &Document, opts: &ExportOptions, ctl: &photocr
/// The layer data (`ImageSourceData`) of a layered TIFF saved from `file`, adjusted the way
/// Photoshop writes it. The layers, global mask and global blocks move out of `file` (the
/// export's own model), which keeps its header, resources and merged image.
fn tiff_image_source(doc: &Document, file: &mut photocraft_psd::PsdFile) -> ImageSourceData {
/// export's own model), which keeps its header, resources and merged image. `ifd_alpha`: the
/// composite in the IFD keeps its transparency as the first extra sample (Save Transparency).
fn tiff_image_source(doc: &Document, file: &mut photocraft_psd::PsdFile, ifd_alpha: bool) -> ImageSourceData {
// Photoshop pairs alpha-name resources with samples past the colour channels and ignores
// the ExtraSamples kind. The merged transparency must not occupy that first slot when a
// spot is also stored. Layer transparency stays in each layer's channel −1.
// the ExtraSamples kind. Layer transparency stays in each layer's channel −1.
let spot_extras = file.header.channels as usize > {
let cc = doc.pixel_format().mode.color_channels();
let alpha = file.layer_info.as_ref().is_some_and(|l| l.merged_alpha);
cc + usize::from(alpha)
};
let mut isd = ImageSourceData::take_from_psd(file);
// Positive layer count: the merged image's first extra sample is not transparency
// (Photoshop's own spot TIFF does this; a negative count would claim the spot plane is alpha).
if spot_extras && let Some(info) = &mut isd.layer_info {
info.merged_alpha = false;
}
// A merged-transparency marker kept from an opened file (Photoshop's `MTrn`) would make the
// first spot read back as transparency. The PSD export already drops it over an opaque
// composite; a transparent one keeps it there, but the TIFF leaves that sample out here.
if spot_extras {
if ifd_alpha && spot_extras {
// Save Transparency next to spot or alpha channels, as Photoshop (27.11) writes it: a
// positive layer count and an `MTrn` block first in the layer data mark the first extra
// sample as the merged transparency.
if let Some(info) = &mut isd.layer_info {
info.merged_alpha = false;
}
} else if !ifd_alpha {
// Positive layer count: the merged image's first extra sample, if any, is not
// transparency (Photoshop's own spot TIFF does this; a negative count would claim the
// spot plane is alpha).
if let Some(info) = &mut isd.layer_info {
info.merged_alpha = false;
}
// A merged-transparency marker kept from an opened file (Photoshop's `MTrn`) would make
// the first spot read back as transparency. The PSD export already drops it over an
// opaque composite; a transparent one keeps it there, but the IFD leaves that sample out.
isd.global_blocks.retain(|b| !b.is_merged_transparency_marker());
}
if let Some(info) = &mut isd.layer_info {
@@ -523,6 +538,10 @@ fn tiff_image_source(doc: &Document, file: &mut photocraft_psd::PsdFile) -> Imag
if !isd.global_blocks.iter().any(|b| &b.key == b"FMsk") {
isd.global_blocks.push(photocraft_psd::TaggedBlock::new(*b"FMsk", FILTER_MASK_DEFAULT.to_vec()));
}
// Photoshop writes the marker first, ahead of `Patt`.
if ifd_alpha && spot_extras && !isd.global_blocks.iter().any(|b| b.is_merged_transparency_marker()) {
isd.global_blocks.insert(0, photocraft_psd::TaggedBlock::new(*b"MTrn", Vec::new()));
}
isd
}
@@ -796,7 +815,11 @@ fn matte_and_drop_alpha(img: &mut Image) -> bool {
let white_f: f32 = if cmyk { 0.0 } else { 1.0 };
// Lab's white is L* 100 with a* and b* 0, which PhotoCraft holds mid-range (`(0 + 128) / 255`).
let lab = img.layout().is_lab();
let mut out = Vec::with_capacity(img.data().len() / stride * keep);
// Out of memory keeps the transparency (the caller warns) rather than aborting the app.
let mut out = Vec::new();
if out.try_reserve_exact(img.data().len() / stride * keep).is_err() {
return false;
}
for px in img.data().chunks_exact(stride) {
let Some(color) = px.get(..keep) else { return false };
let Some(alpha) = px.get(keep..keep.saturating_add(bps)) else { return false };
@@ -905,12 +928,27 @@ fn ne_f32(b: &[u8]) -> Option<f32> {
Some(f32::from_ne_bytes(arr))
}
/// A flat TIFF's composite under Save Transparency (`ExportOptions::tiff_transparency`), then
/// its alpha and spot channels ([`stamp_flat_channels`]). Off, the image is matted over white
/// and keeps no transparency; on, it keeps it next to the channels; unset, it keeps it only
/// when there are no channels.
pub(crate) fn flat_transparency_and_channels(doc: &Document, img: &mut Image, save_transparency: Option<bool>) -> Vec<String> {
let mut warnings = Vec::new();
if save_transparency == Some(false) && img.layout().has_alpha() && !matte_and_drop_alpha(img) {
warnings.push("the image transparency could not be composited over white and was kept".into());
}
warnings.extend(stamp_flat_channels(doc, img, save_transparency == Some(true)));
warnings
}
/// Writes alpha and spot channels (and a Quick Mask) into a flat TIFF: extra samples in the
/// IFD, plus Photoshop resources for the name, ink colour and solidity. At most
/// [`codecs::MAX_EXTRA_SAMPLES`] are kept. A TIFF with no extra channels is left unchanged.
/// When any are written, the composite's own transparency is left out of the IFD: readers pair
/// the channel resources with every sample past the colour channels, in order.
pub(crate) fn stamp_flat_channels(doc: &Document, img: &mut Image) -> Vec<String> {
/// `keep_transparency` (Save Transparency on) keeps the composite's transparency as the first
/// extra sample, ahead of the channels; off, the image is matted over white first.
pub(crate) fn stamp_flat_channels(doc: &Document, img: &mut Image, keep_transparency: bool) -> Vec<String> {
let total = doc.channels.len().saturating_add(usize::from(doc.quick_mask.is_some()));
if total == 0 {
return Vec::new();
@@ -953,7 +991,7 @@ pub(crate) fn stamp_flat_channels(doc: &Document, img: &mut Image) -> Vec<String
// alpha plane is not an extra sample (it would be named as the first spot). The
// composite transparency is gone after this; say so, because the user did not pick
// that option themselves.
if img.layout().has_alpha() {
if img.layout().has_alpha() && !keep_transparency {
if !matte_and_drop_alpha(img) {
warnings.push("extra channels were not written: the composite transparency could not be separated from them".into());
return warnings;
@@ -963,8 +1001,14 @@ pub(crate) fn stamp_flat_channels(doc: &Document, img: &mut Image) -> Vec<String
.into(),
);
}
let quick_id = if quick_last { u16::try_from(color_channels.saturating_add(picked.len()).saturating_sub(1)).ok() } else { None };
match channel_resources(img.meta.photoshop_resources.as_deref(), &names, &picked, quick_id) {
// Resource 1022 counts every sample past the colour channels, the transparency included.
let first = color_channels.saturating_add(usize::from(img.layout().has_alpha()));
let quick_id = if quick_last { u16::try_from(first.saturating_add(picked.len()).saturating_sub(1)).ok() } else { None };
// Save Transparency on: the transparency is the first extra sample, and Photoshop pairs the
// channel resources with every sample past the colour channels, so they list it first
// ("Transparency"), as the layered path and the PSD writer do.
let transparency = img.layout().has_alpha();
match channel_resources(img.meta.photoshop_resources.as_deref(), &names, &picked, quick_id, transparency) {
Ok(bytes) => img.meta.photoshop_resources = Some(bytes),
Err(e) => warnings.push(format!("spot channel options were not written to the TIFF: {e}")),
}
@@ -973,7 +1017,13 @@ pub(crate) fn stamp_flat_channels(doc: &Document, img: &mut Image) -> Vec<String
}
/// Existing Photoshop resources with the channel-name, display-info and quick-mask blocks replaced.
fn channel_resources(existing: Option<&[u8]>, names: &[&str], channels: &[&AlphaChannel], quick_id: Option<u16>) -> Result<Vec<u8>, IoError> {
fn channel_resources(
existing: Option<&[u8]>,
names: &[&str],
channels: &[&AlphaChannel],
quick_id: Option<u16>,
transparency: bool,
) -> Result<Vec<u8>, IoError> {
let mut resources = match existing.filter(|b| !b.is_empty()) {
Some(b) => resources_from_bytes(b)?.0,
None => Vec::new(),
@@ -981,10 +1031,11 @@ fn channel_resources(existing: Option<&[u8]>, names: &[&str], channels: &[&Alpha
resources.retain(|r| {
!matches!(r.id, 1006 | 1045 | crate::channel_map::DISPLAY_INFO | crate::channel_map::QUICK_MASK_INFO | crate::channel_map::ALPHA_IDENTIFIERS)
});
resources.push(ImageResource::new(1006, crate::psd_export::pascal_names_resource(names)));
resources.push(ImageResource::new(1045, crate::psd_export::unicode_names_resource(names)));
resources.push(ImageResource::new(crate::channel_map::DISPLAY_INFO, crate::channel_map::display_info(channels, false)));
resources.push(ImageResource::new(crate::channel_map::ALPHA_IDENTIFIERS, crate::channel_map::alpha_identifiers(false, names.len())));
let listed: Vec<&str> = transparency.then_some("Transparency").into_iter().chain(names.iter().copied()).collect();
resources.push(ImageResource::new(1006, crate::psd_export::pascal_names_resource(&listed)));
resources.push(ImageResource::new(1045, crate::psd_export::unicode_names_resource(&listed)));
resources.push(ImageResource::new(crate::channel_map::DISPLAY_INFO, crate::channel_map::display_info(channels, transparency)));
resources.push(ImageResource::new(crate::channel_map::ALPHA_IDENTIFIERS, crate::channel_map::alpha_identifiers(transparency, names.len())));
if let Some(id) = quick_id {
let mut data = id.to_be_bytes().to_vec();
data.push(0);
+1
View File
@@ -81,6 +81,7 @@ mod tiff_banded_import;
mod tiff_corpus;
mod tiff_layers;
mod tiff_pages;
mod tiff_save_options;
mod tiff_type_geometry;
mod vector;
mod xcf;
+365
View File
@@ -0,0 +1,365 @@
//! TIFF Options (#8827): Save Transparency on and off, flat and layered, with and without spot
//! channels, and Save Image Pyramid. Unset Save Transparency is covered in `tiff_layers`.
use crate::common::*;
use photocraft_color::{Color, ColorMode, PixelFormat, SampleType};
use photocraft_doc::{AlphaChannel, Document, Layer, LayerContent};
use photocraft_geom::{Rect, Size};
use photocraft_io::*;
use photocraft_psd::tiff::ImageSourceData;
use photocraft_raster::Surface;
/// A 4×4 document whose one layer is opaque red in its middle and transparent around it, with a
/// "White" spot channel inked in its left half when `spot`.
fn art(depth: SampleType, spot: bool) -> Document {
let mut doc = Document::new("t", Size::new(4, 4), ColorMode::Rgb, depth);
let fmt = doc.pixel_format();
let mut s = Surface::new(fmt);
s.fill_rect(Rect::new(1, 1, 3, 3), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0]));
doc.layers.push(Layer::new("Layer 1", LayerContent::Raster(s)));
if spot {
let gray = PixelFormat::new(ColorMode::Grayscale, depth, false);
let mut plate = Surface::new(gray);
plate.fill_rect(Rect::new(0, 0, 2, 4), &photocraft_raster::from_rgba(&gray, [1.0, 1.0, 1.0, 1.0]));
let mut white = AlphaChannel::new("White", plate);
white.spot = Some((Color::rgb(0.8, 0.2, 0.2), 1.0));
doc.channels.push(white);
}
doc
}
fn save(doc: &Document, layers: bool, transparency: Option<bool>) -> ExportResult {
export(doc, "t.tif", &ExportOptions { tiff_layers: layers, tiff_transparency: transparency, ..Default::default() }).expect("export")
}
fn extra_samples_tag(bytes: &[u8]) -> Vec<u16> {
let mut dec = tiff::decoder::Decoder::new(std::io::Cursor::new(bytes)).unwrap();
dec.get_tag_u16_vec(tiff::tags::Tag::ExtraSamples).unwrap_or_default()
}
/// A TIFF's channel resources: the names in 1006, and the byte lengths of DisplayInfo (1077)
/// and the alpha identifiers (1053).
fn channel_resources(bytes: &[u8]) -> (Vec<String>, usize, usize) {
let tag = photocraft_codecs::tiff_photoshop_tags(bytes).0.expect("resources");
let (resources, _) = photocraft_psd::tiff::resources_from_bytes(tag).expect("parse resources");
let data = |id: u16| resources.iter().find(|r| r.id == id).map(|r| r.data.clone()).unwrap_or_default();
let pascal = data(1006);
let (mut at, mut names) = (0usize, Vec::new());
while let Some(&len) = pascal.get(at) {
names.push(String::from_utf8_lossy(&pascal[at + 1..at + 1 + usize::from(len)]).into_owned());
at += 1 + usize::from(len);
}
(names, data(1077).len(), data(1053).len())
}
/// The first sample of pixel (0, 0) and its alpha, on the 0–1 scale.
fn corner(img: &photocraft_codecs::Image) -> (f32, Option<f32>) {
let f = img.convert(img.layout(), photocraft_codecs::SampleType::F32);
let s = f.to_f32_samples().unwrap();
(s[0], img.layout().has_alpha().then(|| s[img.layout().channels() - 1]))
}
fn layer_alpha(doc: &Document, x: i32, y: i32) -> f32 {
let LayerContent::Raster(s) = &doc.layers[0].content else { panic!("raster") };
// Alpha is the last channel (index 4 in CMYK).
s.pixel(x, y).last().copied().unwrap_or(1.0)
}
#[test]
fn off_mattes_the_composite_on_white_and_layers_keep_theirs() {
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
for spot in [false, true] {
for layers in [false, true] {
let case = format!("{depth:?} spot {spot} layers {layers}");
let doc = art(depth, spot);
let r = save(&doc, layers, Some(false));
assert!(!r.warnings.iter().any(|w| w.contains("Save Transparency")), "{case}: the user chose it: {:?}", r.warnings);
let img = photocraft_codecs::decode(&r.bytes).unwrap();
assert!(!img.layout().has_alpha(), "{case}");
assert_eq!(img.meta.extra_samples.len(), usize::from(spot), "{case}");
assert_eq!(extra_samples_tag(&r.bytes), if spot { vec![0] } else { vec![] }, "{case}");
assert!((corner(&img).0 - 1.0).abs() < 1e-4, "{case}: transparent corner is white");
let back = import("t.tif", &r.bytes).unwrap().document;
assert_eq!(back.channels.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), if spot { vec!["White"] } else { vec![] }, "{case}");
if layers {
assert_eq!(layer_alpha(&back, 0, 0), 0.0, "{case}: the layer keeps its transparency");
let (isd, _) = ImageSourceData::from_bytes(photocraft_codecs::tiff_photoshop_tags(&r.bytes).1.unwrap()).unwrap();
assert!(!isd.layer_info.unwrap().merged_alpha, "{case}: no merged transparency is claimed");
assert!(!isd.global_blocks.iter().any(|b| b.is_merged_transparency_marker()), "{case}");
}
}
}
}
}
#[test]
fn on_keeps_transparency_ahead_of_spot_channels() {
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
for layers in [false, true] {
let case = format!("{depth:?} layers {layers}");
let doc = art(depth, true);
let r = save(&doc, layers, Some(true));
assert!(!r.warnings.iter().any(|w| w.contains("composited over white")), "{case}: {:?}", r.warnings);
let img = photocraft_codecs::decode(&r.bytes).unwrap();
assert!(img.layout().has_alpha(), "{case}");
assert_eq!(img.meta.extra_samples.len(), 1, "{case}");
// Transparency (unassociated alpha) first, then the spot.
assert_eq!(extra_samples_tag(&r.bytes), vec![2, 0], "{case}");
assert_eq!(corner(&img).1, Some(0.0), "{case}");
let back = import("t.tif", &r.bytes).unwrap().document;
let names: Vec<&str> = back.channels.iter().map(|c| c.name.as_str()).collect();
assert_eq!(names, ["White"], "{case}: the transparency is not opened as a channel");
assert!(back.channels[0].spot.is_some(), "{case}");
assert_eq!(back.channels[0].surface.pixel(0, 0)[0], 1.0, "{case}: inked");
assert_eq!(back.channels[0].surface.pixel(3, 0)[0], 0.0, "{case}: bare");
assert_eq!(layer_alpha(&back, 0, 0), 0.0, "{case}");
assert_eq!(layer_alpha(&back, 1, 1), 1.0, "{case}");
// Photoshop pairs the channel resources with every sample past the colour channels,
// so both paths list the transparency first: a name, a DisplayInfo record and an id.
let (names, display, ids) = channel_resources(&r.bytes);
assert_eq!(names, ["Transparency", "White"], "{case}");
assert_eq!(display, 4 + 2 * 13, "{case}: DisplayInfo records");
assert_eq!(ids, 2 * 4, "{case}: identifiers");
if layers {
// As Photoshop writes it: a positive layer count and `MTrn` first.
let (isd, _) = ImageSourceData::from_bytes(photocraft_codecs::tiff_photoshop_tags(&r.bytes).1.unwrap()).unwrap();
assert!(!isd.layer_info.as_ref().unwrap().merged_alpha, "{case}");
assert_eq!(&isd.global_blocks[0].key, b"MTrn", "{case}");
// The marker is kept for the next save, as from Photoshop's own file.
let mut want = doc.clone();
want.metadata.psd_global_blocks = vec![(*b"8BIM", *b"MTrn", std::sync::Arc::new(Vec::new()))];
assert_docs_eq(&want, &back);
}
}
}
}
/// Channel names outside ASCII survive a save with Save Transparency on, flat and layered: the
/// Unicode names (1045) carry them, after the transparency's entry.
#[test]
fn on_keeps_non_ascii_channel_names() {
let mut doc = art(SampleType::U8, true);
doc.channels[0].name = "Blå".into();
let gray = PixelFormat::new(ColorMode::Grayscale, SampleType::U8, false);
doc.channels.push(AlphaChannel::new("Máscara 2", Surface::new(gray)));
for layers in [false, true] {
let r = save(&doc, layers, Some(true));
let back = import("t.tif", &r.bytes).unwrap().document;
assert_eq!(back.channels.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["Blå", "Máscara 2"], "layers {layers}");
assert!(back.channels[0].spot.is_some(), "layers {layers}: the spot keeps its ink");
}
}
#[test]
fn on_keeps_a_quick_mask_in_place() {
let mut doc = art(SampleType::U8, true);
let gray = PixelFormat::new(ColorMode::Grayscale, SampleType::U8, false);
let mut q = Surface::new(gray);
q.fill_rect(Rect::new(2, 2, 4, 4), &photocraft_raster::from_rgba(&gray, [1.0, 1.0, 1.0, 1.0]));
doc.quick_mask = Some(AlphaChannel::new("Quick Mask", q));
for layers in [false, true] {
let r = save(&doc, layers, Some(true));
assert_eq!(extra_samples_tag(&r.bytes), vec![2, 0, 0], "layers {layers}");
let back = import("t.tif", &r.bytes).unwrap().document;
assert_eq!(back.channels.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["White"], "layers {layers}");
let quick = back.quick_mask.as_ref().unwrap_or_else(|| panic!("layers {layers}: quick mask"));
assert_eq!(quick.surface.pixel(3, 3)[0], 1.0, "layers {layers}");
assert_eq!(quick.surface.pixel(0, 0)[0], 0.0, "layers {layers}");
}
}
/// Past 16 channels a layered TIFF keeps the first 16. With Save Transparency on, the name and
/// DisplayInfo lists hold the transparency ahead of them, so trimming keeps 17 entries and
/// every channel still opens under its own name (they used to shift by one).
#[test]
fn on_past_sixteen_channels_keeps_each_channels_name() {
let mut doc = art(SampleType::U8, false);
let gray = PixelFormat::new(ColorMode::Grayscale, SampleType::U8, false);
for i in 1..=18 {
doc.channels.push(AlphaChannel::new(format!("Alpha {i}"), Surface::new(gray)));
}
let r = save(&doc, true, Some(true));
assert!(r.warnings.iter().any(|w| w.contains("18 extra channels") && w.contains("first 16")), "{:?}", r.warnings);
let img = photocraft_codecs::decode(&r.bytes).unwrap();
assert!(img.layout().has_alpha());
assert_eq!(img.meta.extra_samples.len(), 16);
let back = import("t.tif", &r.bytes).unwrap().document;
let want: Vec<String> = (1..=16).map(|i| format!("Alpha {i}")).collect();
assert_eq!(back.channels.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), want.iter().map(String::as_str).collect::<Vec<_>>());
}
#[test]
fn on_without_transparency_writes_no_alpha() {
// An opaque document has no transparency to save.
let mut doc = art(SampleType::U8, false);
doc.layers[0].locks.transparency = true;
let fmt = doc.pixel_format();
if let LayerContent::Raster(s) = &mut doc.layers[0].content {
s.fill_rect(Rect::new(0, 0, 4, 4), &photocraft_raster::from_rgba(&fmt, [0.0, 0.0, 1.0, 1.0]));
}
for layers in [false, true] {
let r = save(&doc, layers, Some(true));
let img = photocraft_codecs::decode(&r.bytes).unwrap();
assert!(!img.layout().has_alpha() || corner(&img).1 == Some(1.0), "layers {layers}");
}
}
#[test]
fn pyramid_levels_follow_the_full_image_and_open_the_same_document() {
// Big enough to need a level: 100 px halves to 50.
let mut doc = Document::new("t", Size::new(100, 100), ColorMode::Rgb, SampleType::U8);
let fmt = doc.pixel_format();
let mut s = Surface::new(fmt);
s.fill_rect(Rect::new(10, 10, 60, 30), &photocraft_raster::from_rgba(&fmt, [1.0, 0.5, 0.0, 1.0]));
doc.layers.push(Layer::new("Layer 1", LayerContent::Raster(s)));
let gray = PixelFormat::new(ColorMode::Grayscale, SampleType::U8, false);
let mut plate = Surface::new(gray);
plate.fill_rect(Rect::new(0, 0, 50, 100), &photocraft_raster::from_rgba(&gray, [1.0, 1.0, 1.0, 1.0]));
doc.channels.push(AlphaChannel::new("Alpha 1", plate));
for layers in [false, true] {
let opts = |pyramid| ExportOptions {
tiff_layers: layers,
encode: photocraft_codecs::EncodeOptions { tiff_pyramid: pyramid, ..Default::default() },
..Default::default()
};
let with = export(&doc, "t.tif", &opts(true)).unwrap();
let without = export(&doc, "t.tif", &opts(false)).unwrap();
let info = photocraft_codecs::tiff_info(&with.bytes).unwrap();
let kinds: Vec<_> = info.pages.iter().map(|p| (p.kind, p.width)).collect();
assert_eq!(kinds, [(photocraft_codecs::TiffPageKind::Page, 100), (photocraft_codecs::TiffPageKind::ReducedResolution, 50)], "layers {layers}");
// The level holds the image at half size: level (15, 10) covers full-size (30..32, 20..22),
// inside the orange fill; (40, 40) is outside it, composited over white (the alpha
// channel keeps the transparency out of the file).
let level = photocraft_codecs::decode_tiff_page(&with.bytes, 1, &photocraft_codecs::DecodeOptions::default()).unwrap();
assert_eq!(level.dimensions(), (50, 50), "layers {layers}");
let level = level.convert(level.layout(), photocraft_codecs::SampleType::F32);
let px = level.to_f32_samples().unwrap();
for ((x, y), want) in [((15, 10), [1.0f32, 0.5, 0.0]), ((40, 40), [1.0, 1.0, 1.0])] {
let i = (y * 50 + x) * level.layout().channels();
for (c, want) in want.iter().enumerate() {
assert!((px[i + c] - want).abs() < 0.01, "layers {layers} ({x}, {y}) channel {c}: {}", px[i + c]);
}
}
let a = import("t.tif", &with.bytes).unwrap();
let b = import("t.tif", &without.bytes).unwrap();
assert!(!a.warnings.iter().any(|w| w.contains("page")), "layers {layers}: {:?}", a.warnings);
assert_docs_eq(&b.document, &a.document);
}
}
/// `PHOTOCRAFT_TIFF_INTEROP=<dir>` writes every TIFF Options combination there, to check with
/// other readers (libtiff `tiffinfo`, ImageMagick, vips):
///
/// ```sh
/// PHOTOCRAFT_TIFF_INTEROP=/tmp/tiff cargo test -p photocraft-io --test it -- tiff_save_options::write_interop_samples --ignored
/// ```
#[test]
#[ignore = "writes sample files for other readers; set PHOTOCRAFT_TIFF_INTEROP"]
fn write_interop_samples() {
let Some(dir) = std::env::var_os("PHOTOCRAFT_TIFF_INTEROP") else { return };
let dir = std::path::PathBuf::from(dir);
std::fs::create_dir_all(&dir).unwrap();
for (mode, mname) in [(ColorMode::Rgb, "rgb"), (ColorMode::Cmyk, "cmyk"), (ColorMode::Grayscale, "gray")] {
for (depth, dname) in [(SampleType::U8, "8"), (SampleType::U16, "16"), (SampleType::F32, "32")] {
if mode == ColorMode::Cmyk && depth == SampleType::F32 {
continue;
}
let mut doc = Document::new("t", Size::new(300, 200), mode, depth);
let fmt = doc.pixel_format();
let mut s = Surface::new(fmt);
s.fill_rect(Rect::new(40, 30, 260, 170), &photocraft_raster::from_rgba(&fmt, [0.9, 0.2, 0.1, 1.0]));
doc.layers.push(Layer::new("Layer 1", LayerContent::Raster(s)));
for spot in [false, true] {
if spot {
let gray = PixelFormat::new(ColorMode::Grayscale, depth, false);
let mut plate = Surface::new(gray);
plate.fill_rect(Rect::new(0, 0, 150, 200), &photocraft_raster::from_rgba(&gray, [1.0, 1.0, 1.0, 1.0]));
let mut white = AlphaChannel::new("White", plate);
white.spot = Some((Color::rgb(0.8, 0.2, 0.2), 1.0));
doc.channels = vec![white];
}
for layers in [false, true] {
for (t, tname) in [(None, "unset"), (Some(true), "on"), (Some(false), "off")] {
for (c, cname) in [
(photocraft_codecs::TiffCompression::None, "none"),
(photocraft_codecs::TiffCompression::Lzw, "lzw"),
(photocraft_codecs::TiffCompression::Deflate, "zip"),
] {
for pyramid in [false, true] {
let opts = ExportOptions {
tiff_layers: layers,
tiff_transparency: t,
encode: photocraft_codecs::EncodeOptions { tiff_compression: c, tiff_pyramid: pyramid, ..Default::default() },
..Default::default()
};
let r = export(&doc, "t.tif", &opts).unwrap();
let name = format!(
"{mname}{dname}-{}-{}-t{tname}-{cname}{}.tif",
if spot { "spot" } else { "plain" },
if layers { "layered" } else { "flat" },
if pyramid { "-pyramid" } else { "" }
);
std::fs::write(dir.join(name), r.bytes).unwrap();
}
}
}
}
}
}
}
}
/// Save Transparency in every colour mode a TIFF holds: off mattes on the mode's white (paper
/// for CMYK, L* 100 for Lab), on keeps the transparency; flat and, where the mode keeps layers,
/// layered.
#[test]
fn every_colour_mode_saves_or_mattes_its_transparency() {
for mode in [ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Grayscale, ColorMode::Lab] {
for depth in [SampleType::U8, SampleType::U16] {
let mut doc = Document::new("t", Size::new(4, 4), mode, depth);
let fmt = doc.pixel_format();
let mut s = Surface::new(fmt);
s.fill_rect(Rect::new(1, 1, 3, 3), &photocraft_raster::from_rgba(&fmt, [0.2, 0.4, 0.6, 1.0]));
doc.layers.push(Layer::new("Layer 1", LayerContent::Raster(s)));
for layers in [false, true] {
for t in [Some(true), Some(false)] {
let case = format!("{mode:?} {depth:?} layers {layers} {t:?}");
let r = save(&doc, layers, t);
let img = photocraft_codecs::decode(&r.bytes).unwrap_or_else(|e| panic!("{case}: {e}"));
assert_eq!(img.layout().has_alpha(), t == Some(true), "{case}");
let back = import("t.tif", &r.bytes).unwrap().document;
assert_eq!(back.mode, mode, "{case}");
if t == Some(false) {
// The merged image (what other readers show) is matted on the mode's own
// white, flat or layered: CMYK paper is no ink, Lab white L* 100 with a*
// and b* at their midpoint.
let white: &[f32] = match mode {
ColorMode::Cmyk => &[0.0, 0.0, 0.0, 0.0],
ColorMode::Lab => &[1.0, 128.0 / 255.0, 128.0 / 255.0],
ColorMode::Grayscale => &[1.0],
_ => &[1.0, 1.0, 1.0],
};
let f = img.convert(img.layout(), photocraft_codecs::SampleType::F32);
let merged = f.to_f32_samples().unwrap();
assert_eq!(img.layout().channels(), white.len(), "{case}");
assert!(merged.iter().zip(white).all(|(a, b)| (a - b).abs() < 1e-2), "{case}: merged {:?} vs {white:?}", &merged[..white.len()]);
// Only the transparent corner is matted: the opaque centre at (1, 1)
// (sample 5 of the 4-px-wide image) keeps its colour.
let centre = &merged[5 * white.len()..6 * white.len()];
assert!(centre.iter().zip(white).any(|(a, b)| (a - b).abs() >= 1e-2), "{case}: centre {centre:?} is matte white");
// The corner was transparent: now the mode's white, read back opaque.
let LayerContent::Raster(s) = &back.layers[0].content else { panic!("raster") };
let want = photocraft_raster::from_rgba(&back.pixel_format(), [1.0, 1.0, 1.0, 1.0]);
if !layers {
let px = s.pixel(0, 0);
assert!(px.iter().zip(&want).all(|(a, b)| (a - b).abs() < 1e-2), "{case}: {px:?} vs {want:?}");
}
} else {
assert_eq!(layer_alpha(&back, 0, 0), 0.0, "{case}");
}
assert_eq!(layer_alpha(&back, 1, 1), 1.0, "{case}");
}
}
}
}
}
+1
View File
@@ -188,6 +188,7 @@ impl PhotocraftApp {
discard: None,
file_dialog: None,
tiff_options: None,
tiff_remembered: Default::default(),
save_dirs: HashMap::new(),
disk_stamps: HashMap::new(),
targa_options: None,
+15 -8
View File
@@ -281,13 +281,14 @@ impl PhotocraftApp {
jpeg_options_ui::park(self, path.clone(), copy, "file.saveAs")?;
return Ok(serde_json::json!({"path": path, "warnings": []}));
}
// A layered TIFF asks about its layers first (Preferences › File Handling); the save
// A TIFF asks for TIFF Options (compression, pyramid, transparency, layers); the save
// continues from the prompt, which records the step once answered.
if tiff_options_ui::wants_prompt(self, &path) {
tiff_options_ui::park(self, path.clone())?;
if choices.tiff.is_none() && tiff_options_ui::wants_prompt(self, &path) {
tiff_options_ui::park(self, path.clone(), false, "file.saveAs")?;
return Ok(serde_json::json!({"path": path, "warnings": []}));
}
self.save_as_step(path, None, choices)
let tiff_layers = choices.tiff.and_then(|t| t.layers);
self.save_as_step(path, tiff_layers, choices)
}
/// File › Save back to the document's own file, recorded as a `file.save` step with the
@@ -320,14 +321,15 @@ impl PhotocraftApp {
}
/// Re-label the Save As just journaled for `path` as File › Save (see [`Self::save_dialog_flow`]),
/// keeping its Targa, DDS or JPEG answer so playback writes the file the same way. A save
/// parked behind Targa, DDS or JPEG Options hasn't been journaled yet: it is recorded as
/// keeping its Targa, DDS, JPEG or TIFF answer so playback writes the file the same way. A save
/// parked behind Targa, DDS, JPEG or TIFF Options hasn't been journaled yet: it is recorded as
/// File › Save once answered.
pub(crate) fn journal_as_plain_save(&mut self, path: &str) {
let parked = [
self.targa_options.as_mut().map(|p| (&p.path, &mut p.record)),
self.dds_options.as_mut().map(|p| (&p.path, &mut p.record)),
self.jpeg_options.as_mut().map(|p| (&p.path, &mut p.record)),
self.tiff_options.as_mut().map(|p| (&p.path, &mut p.record)),
];
if let Some((_, record)) = parked.into_iter().flatten().find(|(p, record)| p.as_str() == path && **record == "file.saveAs") {
*record = "file.save";
@@ -339,7 +341,12 @@ impl PhotocraftApp {
&& last.0 == "file.saveAs"
&& last.1.get("path").and_then(Value::as_str) == Some(path)
&& let Some(step) = last.1.as_object()
&& step.keys().all(|k| matches!(k.as_str(), "path" | "tgaBits" | "ddsCompression" | "ddsMipmaps" | "quality" | "jpegFormat"))
&& step.keys().all(|k| {
matches!(
k.as_str(),
"path" | "tgaBits" | "ddsCompression" | "ddsMipmaps" | "quality" | "jpegFormat" | "tiffCompression" | "tiffTransparency" | "tiffPyramid"
)
})
{
let mut step = step.clone();
step.remove("path");
@@ -591,7 +598,7 @@ impl PhotocraftApp {
self.tiff_options.is_some() || self.targa_options.is_some() || self.dds_options.is_some() || self.jpeg_options.is_some()
}
/// Writes a save that waited on a format prompt (Targa, DDS or JPEG Options) once answered:
/// Writes a save that waited on a format prompt (Targa, DDS, JPEG or TIFF Options) once answered:
/// journals `step` as its command (`file.saveAs` for Save As, `file.saveACopy` for Save a
/// Copy, `file.save` for a plain Save), so an action being recorded keeps it with this answer
/// (#2032, #4373), reports a failure in the status bar, and releases a close prompt waiting on
@@ -578,6 +578,9 @@ fn saving_from_the_prompt_closes_after_an_unconfirmed_write() {
#[path = "tests/tiff_tests.rs"]
mod tiff_tests;
#[path = "tests/tiff_options_tests.rs"]
mod tiff_options_tests;
#[path = "tests/targa_tests.rs"]
mod targa_tests;
@@ -0,0 +1,308 @@
//! TIFF Options on Save As and Save a Copy (#8827): Image Compression, Save Image Pyramid, Save
//! Transparency and the layers choice; the scripted params that skip it; recording and playback.
use super::*;
use crate::{FileDialogAnswer, tiff_options_ui};
use egui_kittest::kittest::Queryable;
use photocraft_codecs::TiffCompression;
use std::{cell::RefCell, rc::Rc};
type Writes = Rc<RefCell<Vec<(String, Vec<u8>)>>>;
/// What a write was asked for: compression, Save Transparency, pyramid, layers.
fn asked(compression: &str, transparency: Option<bool>, pyramid: bool, layers: bool) -> Vec<u8> {
serde_json::to_vec(&(compression, transparency, pyramid, layers)).unwrap()
}
/// A harness with one 8×8 document (`background`: "white" or "transparent") whose exports record
/// their TIFF settings, showing TIFF Options and answering a save dialog with `to`.
fn tiff_app(background: &str, to: &str) -> (Prompted, Writes) {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 8, "height": 8, "background": background})).unwrap();
app.sync_views();
let writes: Writes = Rc::default();
let written = writes.clone();
app.services.file_dialog = Some(crate::file_dialog::fake(vec![Some(FileDialogAnswer::SaveTo(to.into()))]).0);
app.services.export = Some(Box::new(|_, _, s| {
Ok((asked(tiff_options_ui::compression_name(s.tiff_compression), s.tiff_transparency, s.tiff_pyramid, s.tiff_layers), Vec::new()))
}));
app.services.write = Some(Box::new(move |path, bytes| {
written.borrow_mut().push((path.to_string(), bytes.to_vec()));
Ok(())
}));
let builder = egui_kittest::Harness::builder().with_size(egui::vec2(800.0, 600.0));
let builder = if std::env::var_os("PHOTOCRAFT_TIFF_SNAPSHOTS").is_some() { builder.wgpu() } else { builder };
let h = builder.build_ui_state(
|ui, app| {
show(app, ui.ctx());
tiff_options_ui::show(app, ui.ctx());
app.poll_file_dialog(ui.ctx(), None);
},
app,
);
PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);
h.ctx.set_os(egui::os::OperatingSystem::Windows);
(h, writes)
}
/// `PHOTOCRAFT_TIFF_SNAPSHOTS=<dir>` saves the dialog as a PNG to look at.
fn capture(h: &mut Prompted, name: &str) {
if let Some(dir) = std::env::var_os("PHOTOCRAFT_TIFF_SNAPSHOTS") {
let dir = std::path::PathBuf::from(dir);
std::fs::create_dir_all(&dir).unwrap();
h.render().unwrap().save(dir.join(format!("{name}.png"))).unwrap();
}
}
/// A flat TIFF (one Background) asks too: compression and pyramid, but no transparency or layers
/// to choose. The answer is written, recorded and remembered for the next TIFF.
#[test]
fn save_as_to_a_flat_tiff_asks_for_compression_and_pyramid() {
let _gpu = photocraft_testkit::gpu_lock();
let (mut h, writes) = tiff_app("white", "unused.tif");
h.state_mut().run("actions.record", json!({})).unwrap();
h.state_mut().save_as(Some("p.tif".into())).unwrap();
h.run_steps(2);
capture(&mut h, "tiff-options-flat");
let p = h.state().tiff_options.as_ref().expect("prompt");
assert_eq!((p.compression, p.pyramid, p.has_transparency, p.layered, p.copy), (TiffCompression::None, false, false, false, false));
assert!(h.query_by_label("Save Transparency").is_none(), "nothing transparent to save");
assert!(h.query_by_label("Discard Layers and Save a Copy").is_none());
assert!(writes.borrow().is_empty(), "nothing is written before the answer");
h.get_by_label("LZW").click();
h.get_by_label("Save Image Pyramid").click();
h.run_steps(2);
h.key_press(Key::Enter);
h.run_steps(3);
assert_eq!(writes.borrow().as_slice(), &[("p.tif".to_string(), asked("lzw", None, true, true))]);
assert!(h.state().tiff_options.is_none());
assert_eq!(h.state().session.active().unwrap().path.as_deref(), Some("p.tif"));
// The next TIFF starts where this one ended.
h.state_mut().save_as(Some("q.tif".into())).unwrap();
h.run_steps(2);
assert_eq!(h.state().tiff_options.as_ref().map(|p| (p.compression, p.pyramid)), Some((TiffCompression::Lzw, true)));
h.get_by_label("ZIP").click();
h.run_steps(2);
h.key_press(Key::Enter);
h.run_steps(3);
h.state_mut().run("actions.stop", json!({})).unwrap();
assert_eq!(
h.state().session.actions.list[0].steps,
[
("file.saveAs".into(), json!({"path": "p.tif", "tiffCompression": "lzw", "tiffPyramid": true})),
("file.saveAs".into(), json!({"path": "q.tif", "tiffCompression": "zip", "tiffPyramid": true})),
]
);
// Playback writes the same files without asking.
writes.borrow_mut().clear();
let played = h.state_mut().run("actions.play", json!({"action": 0})).unwrap();
assert!(played.get("failed").is_none(), "{played}");
h.run_steps(2);
assert!(h.state().tiff_options.is_none());
assert_eq!(writes.borrow().as_slice(), &[("p.tif".to_string(), asked("lzw", None, true, true)), ("q.tif".to_string(), asked("zip", None, true, true))]);
}
/// A document without a Background offers Save Transparency, on to start; with an alpha or spot
/// channel it starts off, as an unset Save Transparency writes. Its layers can be discarded,
/// which saves a copy.
#[test]
fn layered_transparent_documents_choose_transparency_and_layers() {
let _gpu = photocraft_testkit::gpu_lock();
let (mut h, writes) = tiff_app("transparent", "unused.tif");
h.state_mut().run("layer.new.layer", json!({})).unwrap();
h.state_mut().save_as(Some("t.tif".into())).unwrap();
h.run_steps(4);
capture(&mut h, "tiff-options-layered");
let p = h.state().tiff_options.as_ref().expect("prompt");
assert_eq!((p.has_transparency, p.transparency, p.layered), (true, true, true));
assert!(h.query_by_label("Including layers will increase file size.").is_some(), "the preference is on by default");
h.get_by_label("Save Transparency").click();
h.run_steps(2);
h.key_press(Key::Enter);
h.run_steps(3);
assert_eq!(writes.borrow().as_slice(), &[("t.tif".to_string(), asked("none", Some(false), false, true))]);
assert_eq!(h.state().session.active().unwrap().path.as_deref(), Some("t.tif"));
// An alpha channel: Save Transparency starts off. Discarding the layers writes a copy.
h.state_mut().run("select.all", json!({})).unwrap();
h.state_mut().run("select.saveSelection", json!({})).unwrap();
assert!(!h.state().session.active().unwrap().doc.channels.is_empty(), "an alpha channel");
h.state_mut().save_as(Some("u.tif".into())).unwrap();
h.run_steps(4);
assert_eq!(h.state().tiff_options.as_ref().map(|p| p.transparency), Some(false));
h.get_by_label("Discard Layers and Save a Copy").click();
h.run_steps(2);
assert!(h.query_by_label("Including layers will increase file size.").is_none(), "no layers, no note");
h.key_press(Key::Enter);
h.run_steps(3);
assert_eq!(writes.borrow().last().unwrap(), &("u.tif".to_string(), asked("none", Some(false), false, false)));
assert_eq!(h.state().session.active().unwrap().path.as_deref(), Some("t.tif"), "a copy: the document keeps its file");
}
/// "Don't show again" turns off the layered-file note for the next save.
#[test]
fn dont_show_again_clears_the_layered_tiff_preference() {
let _gpu = photocraft_testkit::gpu_lock();
let (mut h, _) = tiff_app("transparent", "unused.tif");
h.state_mut().run("layer.new.layer", json!({})).unwrap();
h.state_mut().save_as(Some("t.tif".into())).unwrap();
h.run_steps(4);
h.get_by_label("Don't show again").click();
h.run_steps(2);
h.key_press(Key::Enter);
h.run_steps(3);
assert!(!h.state().session.prefs().file_handling.ask_before_saving_layered_tiff);
h.state_mut().save_as(Some("t.tif".into())).unwrap();
h.run_steps(4);
assert!(h.state().tiff_options.is_some(), "TIFF Options still asks");
assert!(h.query_by_label("Including layers will increase file size.").is_none());
}
/// Save a Copy asks too, and its answer replays as a `file.saveACopy` step.
#[test]
fn save_a_copy_asks_and_replays() {
let _gpu = photocraft_testkit::gpu_lock();
let (mut h, writes) = tiff_app("white", "copy.tif");
h.state_mut().run("actions.record", json!({})).unwrap();
let ctx = h.ctx.clone();
crate::menus::invoke(h.state_mut(), &ctx, "file.saveACopy", json!({})).unwrap();
h.run_steps(3);
assert_eq!(h.state().tiff_options.as_ref().map(|p| p.copy), Some(true));
h.get_by_label("ZIP").click();
h.run_steps(2);
h.key_press(Key::Enter);
h.run_steps(3);
h.state_mut().run("actions.stop", json!({})).unwrap();
assert_eq!(writes.borrow().as_slice(), &[("copy.tif".to_string(), asked("zip", None, false, true))]);
assert_eq!(h.state().session.active().unwrap().path, None, "a copy");
assert_eq!(h.state().session.actions.list[0].steps, [("file.saveACopy".into(), json!({"path": "copy.tif", "tiffCompression": "zip"}))]);
writes.borrow_mut().clear();
let played = h.state_mut().run("actions.play", json!({"action": 0})).unwrap();
assert!(played.get("failed").is_none(), "{played}");
assert_eq!(writes.borrow().as_slice(), &[("copy.tif".to_string(), asked("zip", None, false, true))]);
}
/// File › Save confirming the document's own TIFF asks TIFF Options, and an action being
/// recorded keeps it as a plain Save (no path) with the answer: played back, it writes the TIFF
/// the action is played on, not the one it was recorded on (#3531).
#[test]
fn recorded_plain_save_of_a_tiff_writes_the_file_it_is_played_on() {
let _gpu = photocraft_testkit::gpu_lock();
let (mut h, writes) = tiff_app("white", "own.tif");
let ctx = h.ctx.clone();
crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", json!({"path": "own.tif", "tiffCompression": "none"})).unwrap();
h.state_mut().run("actions.record", json!({})).unwrap();
crate::menus::invoke(h.state_mut(), &ctx, "file.save", json!({})).unwrap();
h.run_steps(4);
assert!(h.state().tiff_options.is_some(), "confirming its own TIFF asks TIFF Options");
h.get_by_label("LZW").click();
h.run_steps(2);
h.key_press(Key::Enter);
h.run_steps(3);
h.state_mut().run("actions.stop", json!({})).unwrap();
assert_eq!(h.state().session.actions.list[0].steps, [("file.save".into(), json!({"tiffCompression": "lzw"}))]);
crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", json!({"path": "other.tif", "tiffCompression": "none"})).unwrap();
writes.borrow_mut().clear();
let played = h.state_mut().run("actions.play", json!({"action": 0})).unwrap();
assert!(played.get("failed").is_none(), "{played}");
assert!(h.state().tiff_options.is_none(), "playback doesn't ask");
assert_eq!(writes.borrow().as_slice(), &[("other.tif".to_string(), asked("lzw", None, false, true))]);
}
/// A scripted plain Save that passes the TIFF answers skips the prompt and is recorded the same
/// way: `file.save` with the answers and no path, so playback writes the file it is played on.
#[test]
fn recorded_scripted_plain_save_of_a_tiff_has_no_path() {
let _gpu = photocraft_testkit::gpu_lock();
let (mut h, writes) = tiff_app("white", "own.tif");
let ctx = h.ctx.clone();
crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", json!({"path": "own.tif", "tiffCompression": "none"})).unwrap();
h.state_mut().run("actions.record", json!({})).unwrap();
crate::menus::invoke(h.state_mut(), &ctx, "file.save", json!({"tiffCompression": "lzw", "tiffTransparency": false, "tiffPyramid": true})).unwrap();
h.run_steps(3);
assert!(h.state().tiff_options.is_none(), "the script answered");
h.state_mut().run("actions.stop", json!({})).unwrap();
assert_eq!(
h.state().session.actions.list[0].steps,
[("file.save".into(), json!({"tiffCompression": "lzw", "tiffTransparency": false, "tiffPyramid": true}))]
);
crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", json!({"path": "other.tif", "tiffCompression": "none"})).unwrap();
writes.borrow_mut().clear();
let played = h.state_mut().run("actions.play", json!({"action": 0})).unwrap();
assert!(played.get("failed").is_none(), "{played}");
assert_eq!(writes.borrow().as_slice(), &[("other.tif".to_string(), asked("lzw", Some(false), true, true))]);
}
/// OK writes the waiting document with its own save settings, even after another tab became
/// active: its path is what linked smart objects resolve against.
#[test]
fn confirm_uses_the_waiting_documents_settings_not_the_active_tabs() {
let _gpu = photocraft_testkit::gpu_lock();
let (mut h, _) = tiff_app("white", "unused.tif");
let seen: Rc<RefCell<Vec<Option<std::path::PathBuf>>>> = Rc::default();
let saw = seen.clone();
h.state_mut().services.export = Some(Box::new(move |_, _, s| {
saw.borrow_mut().push(s.document_path.clone());
Ok((Vec::new(), Vec::new()))
}));
h.state_mut().save_as(Some("a.tif".into())).unwrap();
h.run_steps(4);
h.key_press(Key::Enter);
h.run_steps(3);
let a = h.state().active_doc_id().unwrap();
assert_eq!(h.state().session.active().unwrap().path.as_deref(), Some("a.tif"));
h.state_mut().run("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap();
h.state_mut().sync_views();
let b = h.state().active_doc_id().unwrap();
h.state_mut().refocus(a).unwrap();
h.state_mut().save_as(Some("b.tif".into())).unwrap();
h.run_steps(4);
assert!(h.state().tiff_options.is_some());
h.state_mut().refocus(b).unwrap();
seen.borrow_mut().clear();
h.key_press(Key::Enter);
h.run_steps(3);
assert_eq!(seen.borrow().as_slice(), &[Some(std::path::PathBuf::from("a.tif"))]);
}
/// Scripted saves that pass TIFF answers skip the prompt; a bad one is an error, not a save.
#[test]
fn scripted_tiff_answers_skip_the_prompt() {
let _gpu = photocraft_testkit::gpu_lock();
let (mut h, writes) = tiff_app("transparent", "unused.tif");
let ctx = h.ctx.clone();
crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", json!({"path": "s.tif", "tiffCompression": "zip", "tiffTransparency": true, "tiffPyramid": true}))
.unwrap();
h.run_steps(2);
assert!(h.state().tiff_options.is_none());
assert_eq!(writes.borrow().as_slice(), &[("s.tif".to_string(), asked("zip", Some(true), true, true))]);
for bad in [json!({"path": "b.tif", "tiffCompression": "jpeg"}), json!({"path": "b.tif", "tiffPyramid": "yes"})] {
assert!(crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", bad.clone()).is_err(), "{bad}");
}
assert_eq!(writes.borrow().len(), 1);
assert!(h.state().tiff_options.is_none());
// Automation saves never prompt, and take the answers too.
let choices = crate::FormatChoices::from_params(&json!({"tiffCompression": "lzw"}), "app.save").unwrap();
h.state_mut().services.automation_write = Some(Box::new({
let w = writes.clone();
move |path, bytes| {
w.borrow_mut().push((path.to_string(), bytes.to_vec()));
Ok(())
}
}));
h.state_mut().save_automation_with(Some("a.tif".into()), choices).unwrap();
assert_eq!(writes.borrow().last().unwrap(), &("a.tif".to_string(), asked("lzw", None, false, true)));
}
/// Cancel writes nothing.
#[test]
fn cancel_writes_nothing() {
let _gpu = photocraft_testkit::gpu_lock();
let (mut h, writes) = tiff_app("white", "unused.tif");
h.state_mut().save_as(Some("p.tif".into())).unwrap();
h.run_steps(2);
h.key_press(Key::Escape);
h.run_steps(3);
assert!(h.state().tiff_options.is_none());
assert!(writes.borrow().is_empty());
assert_eq!(h.state().session.active().unwrap().path, None);
}
+231 -39
View File
@@ -1,22 +1,118 @@
//! TIFF Options: the prompt File › Save As shows before writing a layered TIFF, as Photoshop
//! does when "Ask Before Saving Layered TIFF Files" is on in Preferences › File Handling.
//! TIFF Options: what File › Save As and Save a Copy ask before writing a TIFF, as Photoshop's
//! TIFF Options dialog does (#8827): Image Compression (None, LZW, ZIP), Save Image Pyramid,
//! Save Transparency (offered when the document has no Background layer) and, for a document a
//! TIFF stores with its layers, "Discard Layers and Save a Copy". Photoshop's JPEG compression,
//! Pixel Order and Byte Order aren't offered: the TIFF encoder writes interleaved samples in the
//! machine's byte order without JPEG.
//!
//! With "Ask Before Saving Layered TIFF Files" on (Preferences › File Handling), a layered save
//! also notes that layers increase the file size; "Don't show again" clears the preference.
//!
//! The save is parked in [`Prompt`] while the modal is up (egui is immediate-mode) and written
//! once answered: with the layers (Photoshop layer data in the file), or flattened ("Discard
//! Layers and Save a Copy"). "Don't show again" clears the preference. Cancel drops the save.
//! once answered, journalled as the `record` command passed to [`park`] with its path,
//! `tiffLayers` (layered documents) and [`TiffChoice::record`]'s params. Cancel drops the save.
//! Scripts skip the prompt by passing any of `tiffCompression`, `tiffTransparency`,
//! `tiffPyramid` or `tiffLayers`. The answer is remembered for the next TIFF save of the session.
use photocraft_codecs::TiffCompression;
use serde_json::Value;
use crate::{ExportSettings, PhotocraftApp};
/// A TIFF Options answer, from the prompt or from a command's params.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct TiffChoice {
pub compression: TiffCompression,
/// Save Transparency; `None` for the default (see [`ExportSettings::tiff_transparency`]).
pub transparency: Option<bool>,
/// Save Image Pyramid.
pub pyramid: bool,
/// `Some(false)`: "Discard Layers and Save a Copy". `None` keeps what the save would do.
pub layers: Option<bool>,
}
impl TiffChoice {
/// `settings` writing this choice.
pub fn apply(self, settings: ExportSettings) -> ExportSettings {
ExportSettings {
tiff_compression: self.compression,
tiff_transparency: self.transparency,
tiff_pyramid: self.pyramid,
tiff_layers: self.layers.unwrap_or(settings.tiff_layers),
..settings
}
}
/// Adds `tiffCompression`, and `tiffTransparency` and `tiffPyramid` when set, to a recorded
/// save step, so replaying it doesn't ask again. `tiffLayers` is recorded by the save itself.
pub fn record(self, step: &mut Value) {
step["tiffCompression"] = compression_name(self.compression).into();
if let Some(t) = self.transparency {
step["tiffTransparency"] = t.into();
}
if self.pyramid {
step["tiffPyramid"] = true.into();
}
}
}
/// The `tiffCompression` name of `c` (PackBits, which the dialog doesn't offer, as none).
pub fn compression_name(c: TiffCompression) -> &'static str {
match c {
TiffCompression::Lzw => "lzw",
TiffCompression::Deflate => "zip",
TiffCompression::None | TiffCompression::PackBits => "none",
}
}
/// The TIFF Options a command or control call gives (`tiffCompression`, `tiffTransparency`,
/// `tiffPyramid`, `tiffLayers`), which skip the prompt. None given: `None`. A bad value is an
/// error, as in the engine's saves.
pub fn choice_param(params: &Value, cmd: &str) -> Result<Option<TiffChoice>, String> {
use photocraft_engine::file_cmds::{tiff_bool_param, tiff_compression_param};
let compression = tiff_compression_param(params, cmd).map_err(|e| e.to_string())?;
let transparency = tiff_bool_param(params, "tiffTransparency", cmd).map_err(|e| e.to_string())?;
let pyramid = tiff_bool_param(params, "tiffPyramid", cmd).map_err(|e| e.to_string())?;
let layers = match params.get("tiffLayers") {
None | Some(Value::Null) => None,
Some(Value::Bool(b)) => Some(*b),
Some(v) => return Err(format!("{cmd}: `tiffLayers` must be true or false, got {v}")),
};
let any = compression.is_some() || transparency.is_some() || pyramid.is_some() || layers.is_some();
Ok(any.then(|| TiffChoice { compression: compression.unwrap_or_default(), transparency, pyramid: pyramid.unwrap_or(false), layers }))
}
/// What the last TIFF Options answer of the session chose, where the next prompt starts.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Remembered {
pub compression: TiffCompression,
pub pyramid: bool,
}
/// A save waiting on the TIFF Options answer.
pub struct Prompt {
/// The document that requested the save, even if tabs change while this is open.
doc: photocraft_doc::DocId,
/// Where the document goes.
pub path: String,
pub compression: TiffCompression,
pub pyramid: bool,
/// Save Transparency, offered when [`Self::has_transparency`].
pub transparency: bool,
/// The document has no Background layer, so its composite can be transparent.
pub has_transparency: bool,
/// The TIFF would carry the document's layers: "Discard Layers and Save a Copy" is offered.
pub layered: bool,
/// "Discard Layers and Save a Copy".
pub discard_layers: bool,
/// Show the layered-file note ("Ask Before Saving Layered TIFF Files").
pub layer_note: bool,
/// Clears `ask_before_saving_layered_tiff` when the save goes ahead.
pub dont_ask_again: bool,
/// Save a Copy: the document keeps its path and unsaved changes.
pub copy: bool,
/// The step the answered save is recorded as: `file.saveAs` (#2032) or `file.saveACopy` (#4373).
pub record: &'static str,
}
/// `true` when `path` is a TIFF name (`.tif` / `.tiff`).
@@ -25,36 +121,70 @@ pub fn is_tiff_path(path: &str) -> bool {
name.rsplit_once('.').is_some_and(|(stem, ext)| !stem.is_empty() && (ext.eq_ignore_ascii_case("tif") || ext.eq_ignore_ascii_case("tiff")))
}
/// Whether saving the active document to `path` should go through the prompt: a TIFF that
/// would carry layer data, with the preference on.
/// Whether saving the active document to `path` asks for TIFF Options: any TIFF.
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_engine::file_cmds::tiff_would_write_layers(&st.doc))
is_tiff_path(path) && app.session.active().is_some()
}
/// Parks the save behind the prompt.
pub fn park(app: &mut PhotocraftApp, path: String) -> Result<(), String> {
/// Parks the save of the active document to `path` behind the prompt. A prompt already waiting
/// is never replaced.
pub fn park(app: &mut PhotocraftApp, path: String, copy: bool, record: &'static str) -> Result<(), String> {
if app.save_options_open() {
return Err(crate::SAVE_OPTIONS_OPEN.into());
}
let doc = app.active_doc_id()?;
app.tiff_options = Some(Prompt { doc, path, discard_layers: false, dont_ask_again: false });
let st = app.session.active().ok_or("no document")?;
let layered = photocraft_engine::file_cmds::tiff_would_write_layers(&st.doc);
let has_transparency = st.doc.background().is_none();
// Starts where an unset Save Transparency writes: kept unless there are alpha or spot channels.
let transparency = st.doc.channels.is_empty() && st.doc.quick_mask.is_none();
let layer_note = layered && app.session.prefs().file_handling.ask_before_saving_layered_tiff;
let Remembered { compression, pyramid } = app.tiff_remembered;
app.tiff_options = Some(Prompt {
doc,
path,
compression,
pyramid,
transparency,
has_transparency,
layered,
discard_layers: false,
layer_note,
dont_ask_again: false,
copy,
record,
});
Ok(())
}
pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
let Some(p) = &mut app.tiff_options else { return };
let (mut ok, mut cancel) = (false, false);
let (mut discard, mut dont_ask) = (p.discard_layers, p.dont_ask_again);
let modal = egui::Modal::new(egui::Id::unique("tiff-options")).show(ctx, |ui| {
ui.set_max_width(420.0);
ui.label(egui::RichText::new(tl!("TIFF Options")).font(crate::theme::semibold(15.0)));
ui.add_space(4.0);
crate::widgets::hairline(ui);
ui.add_space(8.0);
ui.label(tl!("Including layers will increase file size."));
crate::widgets::section_label(ui, tl!("Image Compression"));
ui.radio_value(&mut p.compression, TiffCompression::None, tl!("None"));
ui.radio_value(&mut p.compression, TiffCompression::Lzw, tl!("LZW"));
ui.radio_value(&mut p.compression, TiffCompression::Deflate, tl!("ZIP"));
ui.add_space(8.0);
crate::widgets::checkbox(ui, &mut discard, tl!("Discard Layers and Save a Copy"));
crate::widgets::checkbox(ui, &mut dont_ask, tl!("Don't show again"));
crate::widgets::checkbox(ui, &mut p.pyramid, tl!("Save Image Pyramid"));
if p.has_transparency {
crate::widgets::checkbox(ui, &mut p.transparency, tl!("Save Transparency"));
}
if p.layered {
ui.add_space(8.0);
crate::widgets::section_label(ui, tl!("Layers"));
crate::widgets::checkbox(ui, &mut p.discard_layers, tl!("Discard Layers and Save a Copy"));
if p.layer_note && !p.discard_layers {
ui.add_space(4.0);
ui.label(tl!("Including layers will increase file size."));
crate::widgets::checkbox(ui, &mut p.dont_ask_again, tl!("Don't show again"));
}
}
ui.add_space(12.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.spacing_mut().item_spacing.x = 10.0;
@@ -63,30 +193,9 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
});
});
cancel |= modal.should_close();
p.discard_layers = discard;
p.dont_ask_again = dont_ask;
// A focused button takes Enter as its click without consuming the key: Enter on Cancel cancels.
if ok || (!cancel && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter))) {
let Some(p) = app.tiff_options.take() else { return };
if p.dont_ask_again {
app.session.edit_prefs(|prefs| prefs.file_handling.ask_before_saving_layered_tiff = false);
}
let settings = ExportSettings { tiff_layers: !p.discard_layers, ..app.save_settings() };
let step = serde_json::json!({"path": p.path, "tiffLayers": !p.discard_layers});
let written = app.with_document(p.doc, |app| app.write_document(p.path, &settings, p.discard_layers));
if written.is_ok() {
// An action being recorded keeps the Save As with this answer (#2032).
app.session.journal.push(("file.saveAs".into(), step));
}
match written {
Err(e) => {
app.ui.status = crate::i18n::fmt(tl!("Save failed: {error}"), &[("error", &e)]);
app.ui.status_error = true;
}
Ok(Some(_)) if !p.discard_layers => crate::discard_ui::saved_document(app, ctx, p.doc),
// A background save releases the close prompt when it finishes (`jobs_ui`).
Ok(_) => {}
}
confirm(app, ctx);
} else if cancel {
app.tiff_options = None;
app.ui.status = tl!("Save cancelled").into();
@@ -94,9 +203,41 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
}
}
/// The answer the prompt gives as it stands.
pub fn choice(p: &Prompt) -> TiffChoice {
TiffChoice {
compression: p.compression,
transparency: p.has_transparency.then_some(p.transparency),
pyramid: p.pyramid,
layers: p.layered.then_some(!p.discard_layers),
}
}
/// OK: writes the waiting save with the prompt's answer, and journals it.
pub fn confirm(app: &mut PhotocraftApp, ctx: &egui::Context) {
let Some(p) = app.tiff_options.take() else { return };
if p.layer_note && p.dont_ask_again && !p.discard_layers {
app.session.edit_prefs(|prefs| prefs.file_handling.ask_before_saving_layered_tiff = false);
}
app.tiff_remembered = Remembered { compression: p.compression, pyramid: p.pyramid };
let choice = choice(&p);
// A plain Save writes whichever file the action is played on (#3531): no path.
let mut step = if p.record == "file.save" { serde_json::json!({}) } else { serde_json::json!({"path": p.path}) };
if let Some(layers) = choice.layers {
step["tiffLayers"] = layers.into();
}
choice.record(&mut step);
// The waiting document's own settings (its path resolves linked smart objects), even if
// another tab is active now. Closed meanwhile, the write below reports it.
let settings = app.with_document(p.doc, |app| Ok(app.save_settings())).unwrap_or_else(|_| app.save_settings());
let settings = choice.apply(settings);
app.write_answered_save(ctx, p.doc, p.path, &settings, p.copy || p.discard_layers, (p.record, step));
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn tiff_names() {
@@ -108,4 +249,55 @@ mod tests {
assert!(!is_tiff_path("tif"));
assert!(!is_tiff_path("a.png"));
}
#[test]
fn choice_params() {
assert_eq!(choice_param(&json!({}), "file.saveAs"), Ok(None));
assert_eq!(choice_param(&json!({"tiffCompression": null, "tiffPyramid": null}), "file.saveAs"), Ok(None));
assert_eq!(
choice_param(&json!({"tiffCompression": "lzw"}), "file.saveAs"),
Ok(Some(TiffChoice { compression: TiffCompression::Lzw, ..Default::default() }))
);
assert_eq!(
choice_param(&json!({"tiffTransparency": false, "tiffPyramid": true, "tiffLayers": false}), "file.saveAs"),
Ok(Some(TiffChoice { compression: TiffCompression::None, transparency: Some(false), pyramid: true, layers: Some(false) }))
);
for bad in [
json!({"tiffCompression": "jpeg"}),
json!({"tiffCompression": 1}),
json!({"tiffTransparency": "yes"}),
json!({"tiffTransparency": 1}),
json!({"tiffPyramid": [true]}),
json!({"tiffLayers": "false"}),
] {
assert!(choice_param(&bad, "file.saveAs").is_err(), "{bad}");
}
}
#[test]
fn recorded_steps_replay_the_same_answer() {
for choice in [
TiffChoice::default(),
TiffChoice { compression: TiffCompression::Deflate, transparency: Some(true), pyramid: true, layers: None },
TiffChoice { compression: TiffCompression::Lzw, transparency: Some(false), pyramid: false, layers: None },
] {
let mut step = json!({"path": "a.tif"});
choice.record(&mut step);
assert_eq!(choice_param(&step, "file.saveAs"), Ok(Some(choice)), "{step}");
}
}
#[test]
fn apply_sets_the_export_settings() {
let base = ExportSettings::default();
let s = TiffChoice { compression: TiffCompression::Deflate, transparency: Some(false), pyramid: true, layers: Some(false) }.apply(base.clone());
assert_eq!((s.tiff_compression, s.tiff_transparency, s.tiff_pyramid, s.tiff_layers), (TiffCompression::Deflate, Some(false), true, false));
let io = s.io_options();
assert_eq!(
(io.encode.tiff_compression, io.tiff_transparency, io.encode.tiff_pyramid, io.tiff_layers),
(TiffCompression::Deflate, Some(false), true, false)
);
// No layers answer keeps what the save would do.
assert!(TiffChoice::default().apply(base).tiff_layers);
}
}
+3 -1
View File
@@ -674,8 +674,10 @@ pub struct PhotocraftApp {
pub(crate) discard: Option<discard_ui::Prompt>,
/// The Open or Save dialog in progress, and the action waiting on it (see `file_dialog`).
pub(crate) file_dialog: Option<file_dialog::Pending>,
/// A Save As to a layered TIFF parked behind the TIFF Options prompt (see `tiff_options_ui`).
/// A Save As or Save a Copy to a TIFF parked behind the TIFF Options prompt (see `tiff_options_ui`).
pub(crate) tiff_options: Option<tiff_options_ui::Prompt>,
/// The last TIFF Options compression and pyramid answer, where the next prompt starts. Session-only.
pub(crate) tiff_remembered: tiff_options_ui::Remembered,
/// Where each document was last saved or exported to through a dialog (#1826): its next Save
/// As or export dialog starts there rather than beside the document. Session-only.
pub(crate) save_dirs: HashMap<photocraft_doc::DocId, std::path::PathBuf>,
@@ -589,8 +589,9 @@ fn save_a_copy(app: &mut PhotocraftApp) -> Result<Value, String> {
let suggested = format!("{stem}{}.psd", app.session.prefs().file_handling.copy_suffix());
// The copy is of the document as it was when asked.
app.pick_save(&suggested, move |app, path| {
// An RGB Targa asks for its bits per pixel first, a DDS texture for its compression, and
// a JPEG for its JPEG Options; the copy is written from the prompt.
// An RGB Targa asks for its bits per pixel first, a DDS texture for its compression, a
// JPEG for its JPEG Options and a TIFF for its TIFF Options; the copy is written from the
// prompt.
let parked = app.with_document(doc.id, |app| {
if crate::targa_options_ui::wants_prompt(app, &path) {
crate::targa_options_ui::park(app, path.clone(), true, "file.saveACopy")?;
@@ -604,6 +605,10 @@ fn save_a_copy(app: &mut PhotocraftApp) -> Result<Value, String> {
crate::jpeg_options_ui::park(app, path.clone(), true, "file.saveACopy")?;
return Ok(true);
}
if crate::tiff_options_ui::wants_prompt(app, &path) {
crate::tiff_options_ui::park(app, path.clone(), true, "file.saveACopy")?;
return Ok(true);
}
Ok(false)
})?;
if parked {
+27 -3
View File
@@ -1,20 +1,22 @@
use super::{
CaptionStyle, Document, FileDialogFn, OsEvent, Value, dds_options_ui, jobs_ui, jpeg_options_ui, monitor_status, native_menu, screen_picker,
targa_options_ui,
targa_options_ui, tiff_options_ui,
};
/// The error a save gets while another save waits on its format prompt.
pub(crate) const SAVE_OPTIONS_OPEN: &str = "Answer the TIFF, Targa, DDS or JPEG Options before starting another save";
/// The format answers a save takes instead of asking: the Targa bits per pixel (`"tgaBits"`),
/// the DDS options (`"ddsCompression"`, `"ddsMipmaps"`) and JPEG Options (`"quality"` 0–12,
/// `"jpegFormat"`). `None` asks in Save As and takes the default in automation saves, which never
/// the DDS options (`"ddsCompression"`, `"ddsMipmaps"`), JPEG Options (`"quality"` 0–12,
/// `"jpegFormat"`) and TIFF Options (`"tiffCompression"`, `"tiffTransparency"`, `"tiffPyramid"`,
/// `"tiffLayers"`). `None` asks in Save As and takes the default in automation saves, which never
/// prompt.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct FormatChoices {
pub tga_bits: Option<photocraft_io::TgaBits>,
pub dds: Option<photocraft_io::DdsOptions>,
pub jpeg: Option<jpeg_options_ui::JpegChoice>,
pub tiff: Option<tiff_options_ui::TiffChoice>,
}
impl FormatChoices {
@@ -24,6 +26,7 @@ impl FormatChoices {
tga_bits: targa_options_ui::bits_param(params, cmd)?,
dds: dds_options_ui::options_param(params, cmd)?,
jpeg: jpeg_options_ui::choice_param(params, cmd)?,
tiff: tiff_options_ui::choice_param(params, cmd)?,
})
}
@@ -34,12 +37,17 @@ impl FormatChoices {
tga_bits: targa_options_ui::bits_param(params, cmd)?,
dds: dds_options_ui::options_param(params, cmd)?,
jpeg: jpeg_options_ui::recorded_choice(params, cmd)?,
tiff: tiff_options_ui::choice_param(params, cmd)?,
})
}
/// The export settings with these answers applied.
pub fn apply(self, settings: ExportSettings) -> ExportSettings {
let settings = ExportSettings { tga_bits: self.tga_bits.or(settings.tga_bits), dds: self.dds.unwrap_or(settings.dds), ..settings };
let settings = match self.tiff {
Some(t) => t.apply(settings),
None => settings,
};
match self.jpeg {
Some(j) => j.apply(settings),
None => settings,
@@ -57,6 +65,9 @@ impl FormatChoices {
if let Some(j) = self.jpeg {
j.record(step);
}
if let Some(t) = self.tiff {
t.record(step);
}
}
}
@@ -76,6 +87,13 @@ pub struct ExportSettings {
pub webp_quality: Option<u8>,
/// TIFF: keep the layers (Photoshop layer data); `false` is "Discard Layers and Save a Copy".
pub tiff_layers: bool,
/// TIFF Options › Image Compression.
pub tiff_compression: photocraft_codecs::TiffCompression,
/// TIFF Options › Save Transparency (`None`: kept unless the document has alpha or spot
/// channels; see [`photocraft_io::ExportOptions::tiff_transparency`]).
pub tiff_transparency: Option<bool>,
/// TIFF Options › Save Image Pyramid.
pub tiff_pyramid: bool,
/// Embed the document's whole XMP packet. `true` by default (Save As keeps the metadata);
/// Export As starts at Metadata: None, since the packet can carry the text of every type
/// layer and one id per placed document (#647).
@@ -119,6 +137,9 @@ impl Default for ExportSettings {
webp_lossless: true,
webp_quality: None,
tiff_layers: true,
tiff_compression: photocraft_codecs::TiffCompression::None,
tiff_transparency: None,
tiff_pyramid: false,
xmp_all: true,
tga_bits: None,
dds: photocraft_io::DdsOptions::default(),
@@ -150,6 +171,9 @@ impl ExportSettings {
opts.encode.embed_icc = self.embed_icc;
opts.encode.embed_metadata = self.embed_metadata;
opts.tiff_layers = self.tiff_layers;
opts.tiff_transparency = self.tiff_transparency;
opts.encode.tiff_compression = self.tiff_compression;
opts.encode.tiff_pyramid = self.tiff_pyramid;
opts.xmp = if self.xmp_all { photocraft_io::XmpEmbed::All } else { photocraft_io::XmpEmbed::None };
opts.tga_bits = self.tga_bits;
opts.encode.dds = self.dds;
+2 -2
View File
@@ -110,7 +110,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i
another document becomes active before the capture, the request fails with an error rather than
saving the wrong document
- `ui.focus`: bring the main window to the front
- `app.open {path}` / `app.save {path?, tgaBits?, ddsCompression?, ddsMipmaps?, quality?, jpegFormat?}` (JPEG: `quality` on the 0–12 scale, `jpegFormat` `baseline`, `optimized` or `progressive`; automation never shows JPEG Options): relative file I/O through the configured automation roots (`app.open` reads under the read root, `app.save` writes under the write root; absolute paths beneath the canonical or configured root are accepted, while `..` and paths escaping the root are refused, and both fail closed when no root was granted). Both reply with `warnings` (import/export notes such as "adjustment layer flattened"; `[]` when none), also shown to the user in the status bar and as a notice (`notices` in `ui.inspect`); `app.open` also returns the `path` and document `name` (directory `.pcraft` — the native on-disk form — loads through the read root's capability; the single-file (zip) form takes the bytes path), `app.save` the `path` written. `app.save` without `path` writes back only to the document's own PSD, PSB or `.pcraft` file, like File › Save. `tgaBits` (24 or 32) sets a TGA's bits per pixel: 32 writes the alpha channel (or else the transparency) as its alpha, 24 none; without it, 32 with an alpha channel or transparency, else 24. `ddsCompression` (`none`, `bc1`, `bc2` or `bc3`) and `ddsMipmaps` (bool) set a DDS texture's compression and mip chain; without them, uncompressed without mipmaps. Automation saves never show TGA, DDS, JPEG or TIFF options. Automation opens and saves never fire script events. Use these two rather than `file.open`, `file.save`, `file.saveAs` or `file.saveACopy`, which the control channel refuses (see [Engine commands](#engine-commands))
- `app.open {path}` / `app.save {path?, tgaBits?, ddsCompression?, ddsMipmaps?, quality?, jpegFormat?, tiffCompression?, tiffTransparency?, tiffPyramid?, tiffLayers?}` (JPEG: `quality` on the 0–12 scale, `jpegFormat` `baseline`, `optimized` or `progressive`; TIFF: `tiffCompression` `none`, `lzw` or `zip`, `tiffTransparency` and `tiffPyramid` bools; automation never shows JPEG or TIFF Options): relative file I/O through the configured automation roots (`app.open` reads under the read root, `app.save` writes under the write root; absolute paths beneath the canonical or configured root are accepted, while `..` and paths escaping the root are refused, and both fail closed when no root was granted). Both reply with `warnings` (import/export notes such as "adjustment layer flattened"; `[]` when none), also shown to the user in the status bar and as a notice (`notices` in `ui.inspect`); `app.open` also returns the `path` and document `name` (directory `.pcraft` — the native on-disk form — loads through the read root's capability; the single-file (zip) form takes the bytes path), `app.save` the `path` written. `app.save` without `path` writes back only to the document's own PSD, PSB or `.pcraft` file, like File › Save. `tgaBits` (24 or 32) sets a TGA's bits per pixel: 32 writes the alpha channel (or else the transparency) as its alpha, 24 none; without it, 32 with an alpha channel or transparency, else 24. `ddsCompression` (`none`, `bc1`, `bc2` or `bc3`) and `ddsMipmaps` (bool) set a DDS texture's compression and mip chain; without them, uncompressed without mipmaps. Automation saves never show TGA, DDS, JPEG or TIFF options. Automation opens and saves never fire script events. Use these two rather than `file.open`, `file.save`, `file.saveAs` or `file.saveACopy`, which the control channel refuses (see [Engine commands](#engine-commands))
- `app.quit`
## Engine commands
@@ -449,7 +449,7 @@ stdio, and a value that is not a port is a usage error naming the variable. Impl
| `doc.exportLayers` | `{dir, format? (png), prefix?, visibleOnly? (true), quality?, index?}` → `{files, skipped}` (plus `count` for workspace exports): one file per exported top-level layer, named like `file.export.layersToFiles` names them. `count` is present only for workspace exports and counts written files only. `skipped` is always an array (empty when nothing is omitted), in top-to-bottom order, of `{layer, name, reason}`: the session layer id, original unsanitized name, and `"hidden by visibleOnly"` or `"adjustment layer has no pixels of its own"`. Visibility takes precedence for hidden adjustments; `visibleOnly:false` exports hidden non-adjustment layers. Groups export merged; their children are not separate exports or skips. Existing filenames/numbering are unchanged. `dir` resolves beneath the write root, so the ambient command stays refused. The bytes come from the command's own core, so both paths write the same files; the write capability refuses to overwrite an existing file. Encode/write failures are errors, not skips |
| `doc.exportDataSets` | `{dir, format? (png), dataSets? (all), naming? ("{name}\|{index}\|{document}"), index?}` → `{files, count}`: the capability-scoped `file.export.dataSetsAsFiles`. The batch is planned first and colliding names are refused before any file is written, as in the command |
| `doc.importDataSets` | `{path, delimiter? (,), index?}` → `{imported}`: the capability-scoped `file.import.variableDataSets`; the CSV is read beneath the read root |
| `doc.save` | `{path?, format?, quality?, index?, tiffLayers?, tgaBits?, ddsCompression?, ddsMipmaps?, pcraftFullComposite?}` (`.pcraft` native, else export by extension; set `tiffLayers: true` to preserve TIFF layers rather than exporting a flattened TIFF; `tgaBits` 24 or 32 sets a TGA's bits per pixel, and `ddsCompression`/`ddsMipmaps` a DDS texture's compression and mip chain, as `app.save` does; `pcraftFullComposite: true` also writes the flattened document at its canvas size into a `.pcraft` file as `composite/full.png`; the save may leave it out in the cases listed in [the format guide](../book/src/formats/pcraft.md), and the manifest's `full_composite` member names it when written). Without `path` only a PSD, PSB or `.pcraft` document is written back to its own file, in its own format; anything else is an error and the file is left unchanged. A successful layered save (PSD, PSB or `.pcraft`) records the current revision as saved and makes the file the document's path, so `session.list` reports `dirty: false`; a flat export is a copy and leaves the document dirty |
| `doc.save` | `{path?, format?, quality?, index?, tiffLayers?, tiffCompression?, tiffTransparency?, tiffPyramid?, tgaBits?, ddsCompression?, ddsMipmaps?, pcraftFullComposite?}` (`.pcraft` native, else export by extension; set `tiffLayers: true` to preserve TIFF layers rather than exporting a flattened TIFF; `tiffCompression` (`none`, `lzw`, `zip`), `tiffTransparency` (bool: Save Transparency; unset, kept unless the document has alpha or spot channels) and `tiffPyramid` (bool) are TIFF Options; `tgaBits` 24 or 32 sets a TGA's bits per pixel, and `ddsCompression`/`ddsMipmaps` a DDS texture's compression and mip chain, as `app.save` does; `pcraftFullComposite: true` also writes the flattened document at its canvas size into a `.pcraft` file as `composite/full.png`; the save may leave it out in the cases listed in [the format guide](../book/src/formats/pcraft.md), and the manifest's `full_composite` member names it when written). Without `path` only a PSD, PSB or `.pcraft` document is written back to its own file, in its own format; anything else is an error and the file is left unchanged. A successful layered save (PSD, PSB or `.pcraft`) records the current revision as saved and makes the file the document's path, so `session.list` reports `dirty: false`; a flat export is a copy and leaves the document dirty |
| `doc.inspect` | `{index?}`: same JSON as `document.inspect` |
| `doc.render` | `{index?, maxSide? (1024; 0 = full), path?}`: PNG to `path`, else `{mime, base64}` |
| `doc.select` / `doc.close` | `{index}` / `{index?}` |
+3 -2
View File
@@ -1,6 +1,6 @@
# File-format parity
> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-31 · **Change:** minor (`.atn`: 144 supported events after Actions batch 12 (Groups A–I, command options, version 12 files, reference forms); the supported table and measured reference are in [atn.md](atn.md); TIFF: YCbCr images open as RGB, including JPEG-compressed scans with subsampled chroma, #10316; TIFFs up to 300,000 px a side open, decoded a group of rows at a time into the layer, #8169; embedded AI/PDF/EPS save-back retains native format with a source-bound SVG display preview; PSD Filter Gallery: Halftone Pattern dot/circle/line settings survive PSD/PSB saves (#8940); Save for Web writes WebP, lossy or lossless, #6391; Photoshop's `MTrn` merged-transparency marker, from a layered TIFF saved with Save Transparency, marks the merged transparency, #8877; layered TIFF writes the TySh text version and descriptor in PSD big-endian order while the header, matrix, warp and bounds keep container order, #9098; layered TIFF writes Photoshop's 14-byte global layer mask, so Photoshop opens the layers instead of only the composite, #9095; legacy PSD point text placed from the layout ink box after font resolution, #6094; `.atn`: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; `.asl` layer style libraries read and written, #1051; JPEG Options on File › Save, Save As and Save a Copy, FILE-215-19 partial (no Matte, progressive Scans or size preview); 32-bit Hue/Saturation unclipped and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; JPEG Options on Save As and Save a Copy, FILE-215-19; TIFF compression for scripted saves, `tiffCompression`, #5301; the Nikon D4 white level follows the sample depth (12 and 14 bit), #5978; Apply Layer Comp action mapping, #7101; Cineon write: 10-bit gray/RGB; animated WebP frames load into video layers, #1198; Photoshop mixed-order TIFF type geometry, #4758; DDS textures save: uncompressed or BC1–BC3, optional mip chain, DDS Options in Save As (#1327); PSD smart filters: 53 filters (39 more: Pinch, Polar Coordinates, Ripple, Spherize, Twirl, Wave, ZigZag, Invert, Blur, Surface Blur, Smart Sharpen, Diffuse, Wind, Offset, Mezzotint, Clouds, Difference Clouds, Fibers, Lens Flare and others) plus Hue/Saturation and Perspective Warp mapped both ways, #6296, #6298, #6300, #6302, #6304, #6314, #6316, #6267, #6268, FILE-215-2; large-file fixtures: a 20 MP layered PSD, a 150-layer layout, a 2 GB PSD and a 4.4 GB PSB generated at test time and round-tripped, FILE-216-2 done, #5107; earlier: smart objects keep Photoshop's Cylinder warp through re-renders and saves, #4112; 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; 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; Amiga IFF write: 24-plane ILBM, Save As `.iff`; PSD stores spot channels as Photoshop does, ink 0 = solid, and numbers them in 1053, #7415 split; TIFF writes and reads alpha and spot channels as extra samples with Photoshop's channel resources, PSD output unchanged, FILE-215-7, FILE-215-17's TIFF part, #7415; Photoshop's `MTrn` merged-transparency marker, from a layered TIFF saved with Save Transparency, marks the merged transpaLine truncated
> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-11-02 · **Change:** minor (TIFF Options on Save As and Save a Copy: Image Compression None/LZW/ZIP, Save Image Pyramid, Save Transparency and Discard Layers, also `tiffTransparency`/`tiffPyramid` for scripts, the CLI and MCP, #8827; `.atn`: 144 supported events after Actions batch 12 (Groups A–I, command options, version 12 files, reference forms); the supported table and measured reference are in [atn.md](atn.md); TIFF: YCbCr images open as RGB, including JPEG-compressed scans with subsampled chroma, #10316; TIFFs up to 300,000 px a side open, decoded a group of rows at a time into the layer, #8169; embedded AI/PDF/EPS save-back retains native format with a source-bound SVG display preview; PSD Filter Gallery: Halftone Pattern dot/circle/line settings survive PSD/PSB saves (#8940); Save for Web writes WebP, lossy or lossless, #6391; Photoshop's `MTrn` merged-transparency marker, from a layered TIFF saved with Save Transparency, marks the merged transparency, #8877; layered TIFF writes the TySh text version and descriptor in PSD big-endian order while the header, matrix, warp and bounds keep container order, #9098; layered TIFF writes Photoshop's 14-byte global layer mask, so Photoshop opens the layers instead of only the composite, #9095; legacy PSD point text placed from the layout ink box after font resolution, #6094; `.atn`: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; `.asl` layer style libraries read and written, #1051; JPEG Options on File › Save, Save As and Save a Copy, FILE-215-19 partial (no Matte, progressive Scans or size preview); 32-bit Hue/Saturation unclipped and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; JPEG Options on Save As and Save a Copy, FILE-215-19; TIFF compression for scripted saves, `tiffCompression`, #5301; the Nikon D4 white level follows the sample depth (12 and 14 bit), #5978; Apply Layer Comp action mapping, #7101; Cineon write: 10-bit gray/RGB; animated WebP frames load into video layers, #1198; Photoshop mixed-order TIFF type geometry, #4758; DDS textures save: uncompressed or BC1–BC3, optional mip chain, DDS Options in Save As (#1327); PSD smart filters: 53 filters (39 more: Pinch, Polar Coordinates, Ripple, Spherize, Twirl, Wave, ZigZag, Invert, Blur, Surface Blur, Smart Sharpen, Diffuse, Wind, Offset, Mezzotint, Clouds, Difference Clouds, Fibers, Lens Flare and others) plus Hue/Saturation and Perspective Warp mapped both ways, #6296, #6298, #6300, #6302, #6304, #6314, #6316, #6267, #6268, FILE-215-2; large-file fixtures: a 20 MP layered PSD, a 150-layer layout, a 2 GB PSD and a 4.4 GB PSB generated at test time and round-tripped, FILE-216-2 done, #5107; earlier: smart objects keep Photoshop's Cylinder warp through re-renders and saves, #4112; 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; 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; Amiga IFF write: 24-plane ILBM, Save As `.iff`; PSD stores spot channels as Photoshop does, ink 0 = solid, and numbers them in 1053, #7415 split; TIFF writes and reads alpha and spot channels as extra samples with Photoshop's Line truncated
**PSD Filter Gallery (#8940, 2026-10-23):** Halftone Pattern maps its size, contrast and dot/circle/line pattern as editable settings on import and export, with the reference application's descriptor keys (`HlSz`, `Cntr`, `ScrT`: `ScrD`/`ScrC`/`ScrL`). PSD/PSB round trips pass at 8/16/32 bits. This does not claim pixel equivalence for the existing renderer. Unknown or malformed settings remain verbatim on import.
@@ -26,7 +26,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 with their warp: the bend presets, a custom mesh and, since #4112, Cylinder; CS2 PlLd/lnkD read with their warp, kept as is or re-saved as SoLd once edited), smart filters (53 mapped, among them Invert, the Distort filters but Shear, Clouds, Difference Clouds, Fibers and Lens Flare, plus Hue/Saturation, Perspective Warp, Filter Gallery with Chrome and a Camera Raw subset, rest verbatim), slices, comps, Advanced Blending, each layer's XMP packet (`layer.xmpMetadata`); alpha and spot channels as Photoshop stores them (spot ink 0 = solid, channel identifiers in 1053), and PSDs with spot channels from PhotoCraft 0.1.0–0.16.0, which stored the ink the other way round, keep their ink. Oracle floors: Photoshop-authored 190/258, io 148/170, psd-tools 249/309; round trip ≥ 169/170, 308/309, 258/258. 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); generated 20 MP, 150-layer, 2 GB PSD and 4.4 GB PSB fixtures opened, saved and re-opened by io tests/it/large_files.rs (FILE-216-2, 2026-10-13; the 4.4 GB PSB opens on Windows); > 4 GB from the app's File › Open 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, YCbCr read as RGB (JPEG-compressed with subsampled chroma, or uncompressed without subsampling; #10316), BigTIFF, every IFD, banded parallel decode; flat pages up to 300,000 px a side open a group of rows at a time into the layer, with no full-size copy, and are refused with an error when the machine lacks the memory (Linux: free RAM and swap, cgroup limits; #8169); layered TIFF both byte orders, including Photoshop mixed-order type blocks on read (#4758/#4771) and TySh text descriptors written in PSD order (#9098) and Photoshop's 14-byte `LMsk` block (#9095); LZW/ZIP for scripted saves by `tiffCompression`; undecodable type keeps saved pixels (FILE-215-7); alpha and spot channels as extra samples (at most 16) with Photoshop's names, ink colours and solidity, spot ink stored 0 = solid (#7415); no Save Transparency choice yet (channels are written as Photoshop does with it off) |
| TIFF | R/W | yes | yes | 8/16/32f, Gray/RGB/CMYK, YCbCr read as RGB (JPEG-compressed with subsampled chroma, or uncompressed without subsampling; #10316), BigTIFF, every IFD, banded parallel decode; flat pages up to 300,000 px a side open a group of rows at a time into the layer, with no full-size copy, and are refused with an error when the machine lacks the memory (Linux: free RAM and swap, cgroup limits; #8169); layered TIFF both byte orders, including Photoshop mixed-order type blocks on read (#4758/#4771) and TySh text descriptors written in PSD order (#9098) and Photoshop's 14-byte `LMsk` block (#9095); TIFF Options on Save As and Save a Copy (Image Compression None/LZW/ZIP, Save Image Pyramid, Save Transparency, Discard Layers and Save a Copy; scripts pass `tiffCompression`, `tiffTransparency`, `tiffPyramid`, `tiffLayers`; #8827), no JPEG compression, Pixel Order or Byte Order (the encoder writes interleaved samples in the machine's byte order); undecodable type keeps saved pixels (FILE-215-7); alpha and spot channels as extra samples (at most 16) with Photoshop's names, ink colours and solidity, spot ink stored 0 = solid (#7415); Save Transparency on keeps the transparency as the first extra sample ahead of the channels (a layered file marks it with `MTrn`, as Photoshop does), off mattes on white; unset, it is kept only without alpha or spot channels |
| 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); File › Save, Save As and Save a Copy ask JPEG Options: Quality 0–12, starting at the opened file's quality or else the Export preference, and Baseline ("Standard") / Baseline Optimized / Progressive; scripts pass `quality`/`jpegFormat`, the CLI `--jpeg-format` (FILE-215-19). Baseline Optimized fits the Huffman tables only at 4:4:4 (Gray, CMYK) or progressive: RGB is written 4:2:0, which zune-jpeg 0.5.15 decodes wrongly with fitted tables, as in Save for Web. No Matte, progressive Scans (3–5) or size preview |
| 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 |
@@ -151,6 +151,7 @@ The original reference entry retains its source date and historical totals; curr
| Date | Change | Summary |
|---|---|---|
| 2026-11-02 | minor | TIFF Options on Save As and Save a Copy (#8827): Image Compression (None, LZW, ZIP), Save Image Pyramid (half-size levels marked reduced-resolution, down to 64 px, alpha-weighted; +45 ms on a 30 MP RGB/8 save), Save Transparency (on: transparency kept ahead of alpha and spot channels, `MTrn` in a layered file; off: matted on white) and Discard Layers and Save a Copy. Scripts, `doc.save`, MCP `save` and the CLI (`--tiff-transparency`, `--tiff-pyramid`) take the same answers. JPEG compression, Pixel Order and Byte Order not offered |
| 2026-11-01 | minor | `.atn`: event reference [atn.md](atn.md): the 117 supported events, and measured keys, defaults, ranges and enum values for 101 events not mapped yet |
| 2026-10-31 | minor | `.atn` Group B: four Render events load, play and save; 120 supported and 97 unmapped. Supported-table columns corrected against the event registry; the original 117/101 reference entry remains historical. |
| 2026-10-31 | minor | `.atn`: Pinch (`Pnch`), Polar Coordinates (`Plr `), Spherize (`Sphr`), Twirl (`Twrl`), Wave (`Wave`) and ZigZag (`ZgZg`) map to `filter.distort.*` with every key in recorded order; out-of-range values clamped and missing keys given Photoshop's defaults on import; a Wave scaled below 100 % stays a Photoshop step (the command has no scale); Shear still kept verbatim (#10605) |
+3 -2
View File
@@ -1,6 +1,6 @@
# Where PhotoCraft falls short of Photoshop
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (G11: four Render ATN events mapped, 120 supported/97 unmapped; G9: 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; selected colour sets edit drawing, tone and supported filters; geometry remains open; G11: `.atn` document offsets preserve opening order after tab reordering, #7103; embedded AI/PDF/EPS save-back retains native format with a source-bound SVG display preview; Smooth and Feather command masks cropped to selection bounds plus blur reach; G1: Halftone Pattern Filter Gallery settings survive PSD/PSB saves (#8940); cropped selection morphology and command mask conversion performance evidence added; G6: Art History Brush landed as partial, TOOL-213-20, #1610, so no toolbar tool is missing; G4: five hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; G9: Crop tool canvas menu, #6561; G2: Content-Aware Scale seam carving 1.65–3.6× faster with unchanged output, P28 row 3.3 → 1.6 s on a 4-core VM, #5236; G9: UI scale presets done, 105–120% steps, #3222; G14: lossy DNG, raw sidecars, Camera Raw Defaults live, Calibration and Auto, CR3 assessed as not clean-room feasible; G8: PSD type on a path opens on its path and saves back into the file's `Txt2`, #7962; G11: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; adjustment clipping stays visible in compact Properties, #5231; G9: Color panel modes, ramp and copy commands, the same in every theme, UI-217-17, #6000; G17: Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; G10: `.asl` style libraries landed, #1051; G8: area type (TYPE-218-10); G1: smart objects keep Photoshop's Cylinder warp, #4112; G8: paragraph direction buttons in the Paragraph panel and options bar, TYPE-218-2 partial; G1: 32-bit Hue/Saturation and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; G11: compound layer properties export as separate Photoshop Set events, rename last, #8304; G11: Batch and droplets take the result at the action's Save step, so actions ending in Save As and Close work; G11: `.atn` steps that switch to another open document import, play and save back, #7103; G14: the Nikon D4 white level follows the sample depth, so 12-bit D4 NEFs no longer open 2.6 stops dark, #5978; G14: a Nikon NEF's Adobe RGB preview is read as Adobe RGB (maker-note ColorSpace 0x001E), #5987; Apply Layer Comp action mapping, #7101; G10: JPEG Options dialog landed, FILE-215-19 partial (no Matte, progressive Scans or size preview); G10: Cineon write; G10: DPX read and write, #1049, Cineon and Amiga IFF read; Classical Object Finder improvement; learned segmentation remains open; G4: named, stateful section locks and visible keyboard focus in Brush Settings; G4: independent Brush Pose tilt-axis overrides, #3825 partial; G4: Transfer Mixer-only controls, #3825 partial; G9: Preferences › File Handling › Save in Background takes effect, #6207, 24 of 169 preferences do nothing; G7: Content-Aware Move previews every selection the command takes, coarse then exact, TOOL-213-4 done, #6680; G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; G9: Animated Zoom pref read: holding the Zoom tool zooms continuously, #6210, prefs that do nothing 25 of 166; G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget in local runs, baseline not re-run, #6205; G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 1Line truncated
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-02 · **Change:** minor (G10: TIFF Options dialog on Save As and Save a Copy, compression, Save Image Pyramid, Save Transparency, #8827; G11: four Render ATN events mapped, 120 supported/97 unmapped; G9: 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; selected colour sets edit drawing, tone and supported filters; geometry remains open; G11: `.atn` document offsets preserve opening order after tab reordering, #7103; embedded AI/PDF/EPS save-back retains native format with a source-bound SVG display preview; Smooth and Feather command masks cropped to selection bounds plus blur reach; G1: Halftone Pattern Filter Gallery settings survive PSD/PSB saves (#8940); cropped selection morphology and command mask conversion performance evidence added; G6: Art History Brush landed as partial, TOOL-213-20, #1610, so no toolbar tool is missing; G4: five hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; G9: Crop tool canvas menu, #6561; G2: Content-Aware Scale seam carving 1.65–3.6× faster with unchanged output, P28 row 3.3 → 1.6 s on a 4-core VM, #5236; G9: UI scale presets done, 105–120% steps, #3222; G14: lossy DNG, raw sidecars, Camera Raw Defaults live, Calibration and Auto, CR3 assessed as not clean-room feasible; G8: PSD type on a path opens on its path and saves back into the file's `Txt2`, #7962; G11: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; adjustment clipping stays visible in compact Properties, #5231; G9: Color panel modes, ramp and copy commands, the same in every theme, UI-217-17, #6000; G17: Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; G10: `.asl` style libraries landed, #1051; G8: area type (TYPE-218-10); G1: smart objects keep Photoshop's Cylinder warp, #4112; G8: paragraph direction buttons in the Paragraph panel and options bar, TYPE-218-2 partial; G1: 32-bit Hue/Saturation and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; G11: compound layer properties export as separate Photoshop Set events, rename last, #8304; G11: Batch and droplets take the result at the action's Save step, so actions ending in Save As and Close work; G11: `.atn` steps that switch to another open document import, play and save back, #7103; G14: the Nikon D4 white level follows the sample depth, so 12-bit D4 NEFs no longer open 2.6 stops dark, #5978; G14: a Nikon NEF's Adobe RGB preview is read as Adobe RGB (maker-note ColorSpace 0x001E), #5987; Apply Layer Comp action mapping, #7101; G10: JPEG Options dialog landed, FILE-215-19 partial (no Matte, progressive Scans or size preview); G10: Cineon write; G10: DPX read and write, #1049, Cineon and Amiga IFF read; Classical Object Finder improvement; learned segmentation remains open; G4: named, stateful section locks and visible keyboard focus in Brush Settings; G4: independent Brush Pose tilt-axis overrides, #3825 partial; G4: Transfer Mixer-only controls, #3825 partial; G9: Preferences › File Handling › Save in Background takes effect, #6207, 24 of 169 preferences do nothing; G7: Content-Aware Move previews every selection the command takes, coarse then exact, TOOL-213-4 done, #6680; G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; G9: Animated Zoom pref read: holding the Zoom tool zooms continuously, #6210, prefs that do nothing 25 of 166; G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget in local runs, baseline not re-run, #6205; G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 24Line truncated
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-01 · **Change:** minor (G11: twelve Stylize/Pixelate ATN events mapped, 128 supported/89 unmapped; G9: 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; selected colour sets edit drawing, tone and supported filters; geometry remains open; G11: `.atn` document offsets preserve opening order after tab reordering, #7103; embedded AI/PDF/EPS save-back retains native format with a source-bound SVG display preview; Smooth and Feather command masks cropped to selection bounds plus blur reach; G1: Halftone Pattern Filter Gallery settings survive PSD/PSB saves (#8940); cropped selection morphology and command mask conversion performance evidence added; G6: Art History Brush landed as partial, TOOL-213-20, #1610, so no toolbar tool is missing; G4: five hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; G9: Crop tool canvas menu, #6561; G2: Content-Aware Scale seam carving 1.65–3.6× faster with unchanged output, P28 row 3.3 → 1.6 s on a 4-core VM, #5236; G9: UI scale presets done, 105–120% steps, #3222; G14: lossy DNG, raw sidecars, Camera Raw Defaults live, Calibration and Auto, CR3 assessed as not clean-room feasible; G8: PSD type on a path opens on its path and saves back into the file's `Txt2`, #7962; G11: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; adjustment clipping stays visible in compact Properties, #5231; G9: Color panel modes, ramp and copy commands, the same in every theme, UI-217-17, #6000; G17: Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; G10: `.asl` style libraries landed, #1051; G8: area type (TYPE-218-10); G1: smart objects keep Photoshop's Cylinder warp, #4112; G8: paragraph direction buttons in the Paragraph panel and options bar, TYPE-218-2 partial; G1: 32-bit Hue/Saturation and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; G11: compound layer properties export as separate Photoshop Set events, rename last, #8304; G11: Batch and droplets take the result at the action's Save step, so actions ending in Save As and Close work; G11: `.atn` steps that switch to another open document import, play and save back, #7103; G14: the Nikon D4 white level follows the sample depth, so 12-bit D4 NEFs no longer open 2.6 stops dark, #5978; G14: a Nikon NEF's Adobe RGB preview is read as Adobe RGB (maker-note ColorSpace 0x001E), #5987; Apply Layer Comp action mapping, #7101; G10: JPEG Options dialog landed, FILE-215-19 partial (no Matte, progressive Scans or size preview); G10: Cineon write; G10: DPX read and write, #1049, Cineon and Amiga IFF read; Classical Object Finder improvement; learned segmentation remains open; G4: named, stateful section locks and visible keyboard focus in Brush Settings; G4: independent Brush Pose tilt-axis overrides, #3825 partial; G4: Transfer Mixer-only controls, #3825 partial; G9: Preferences › File Handling › Save in Background takes effect, #6207, 24 of 169 preferences do nothing; G7: Content-Aware Move previews every selection the command takes, coarse then exact, TOOL-213-4 done, #6680; G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; G9: Animated Zoom pref read: holding the Zoom tool zooms continuously, #6210, prefs that do nothing 25 of 166; G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget in local runs, baseline not re-run, #6205; G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 24Line truncated
Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impact
@@ -365,7 +365,7 @@ what an agent can't finish alone.
### G10. Missing and partial file formats
- **Progress (2026-10-26):** Embedded SVG/PDF-compatible AI/PDF/EPS smart objects can be edited in VectorCraft, including nested PSD payloads. AI/PDF/EPS working copies retain their format with a separate source-bound SVG display preview; native bytes and previews persist through .pcraft and PSD/PSB saves. This does not add standalone EPS/DCS import or establish lossless Adobe round-trip compatibility. See [workflow and limits](embedded-vector-editing.md); estimates and parity percentages are unchanged.
- **Missing:** JPEG Options' Matte, progressive Scans and size preview (FILE-215-19 partial), Photoshop PDF read and its vector/text/multi-page
- **Missing:** JPEG Options' Matte, progressive Scans and size preview (FILE-215-19 partial), TIFF Options' JPEG compression, Pixel Order and Byte Order (the rest landed 2026-11-02, #8827), Photoshop PDF read and its vector/text/multi-page
write (FILE-215-10, #2541; a single flattened page now saves via Save As / Save a Copy / CLI,
2026-10-11, #3401), AVIF read (#463) and default-build AVIF write, JPEG XL, JPEG 2000 (#1047),
DICOM, EPS/DCS, Pixar, WBMP, MPO/JPS, PICT, Scitex CT, Photoshop
@@ -456,6 +456,7 @@ what an agent can't finish alone.
| 2026-10-21 | minor | G11: Batch and droplets take the result at the action's recorded Save / Save As step (Photoshop's "Override Action 'Save As' Commands"); estimate unchanged |
| 2026-10-21 | minor | G9: right-click on a pending crop opens the Crop tool menu (presets, Clear, overlays, Cancel, Crop; #6561); Reset still open |
| 2026-10-22 | minor | G8: Auto / Left-to-right / Right-to-left paragraph direction buttons in the Paragraph panel, Properties and the Type options bar (#6793); TYPE-218-2 partial (the visual RTL caret is still missing, and PSD doesn't store the direction yet) |
| 2026-11-02 | minor | G10: TIFF Options dialog on Save As and Save a Copy: Image Compression, Save Image Pyramid, Save Transparency, Discard Layers (#8827); JPEG compression, Pixel Order and Byte Order not offered; no readiness percentage or estimate changed |
| 2026-10-19 | minor | G10: JPEG Options dialog landed (FILE-215-19 partial: no Matte, progressive Scans or size preview); no readiness percentage or estimate changed |
| 2026-10-19 | minor | G11: `.atn` steps that select another open document by offset import as `document.activate {"offset"}`, play and save back (#7103); estimate unchanged |
| 2026-10-19 | minor | G11: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430 |
+2 -2
View File
@@ -129,7 +129,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu
| FILE-215-4 | Adjustments (Hue/Sat + Colorize, Curves, Levels, Shadows/Highlights) apply as Smart Filters | done | [#215](https://github.com/storytold/photocraft/issues/215) | Image › Adjustments on a smart object records image.adjustments.<kind> as a smart filter (adjust_cmds.rs adjust_as_smart_filter; the selection becomes the filter mask), re-rendered from the source by adjust_as_filter and re-editable with layer.smartFilter.setParams; PSD maps Levels/Curves/Shadows-Highlights both ways (smart_map.rs). Opening the editor from the smart-filter row is FILE-215-5's row work |
| 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) | done | [#215](https://github.com/storytold/photocraft/issues/215) | #426: SmartObject.perspective holds the projective map (transform keeps its affine approximation); Distort / Perspective on a smart object set it (transform_cmds.rs, smart_cmds::set_placement), it re-renders from the source through the homography, Warp composes with it, and the PSD placement reads and writes nonAffineTransform / Trnf (io/blocks.rs placed_projective, smart_map.rs); tests distort_survives_edit_contents, warp_on_a_distorted_smart_object_follows_the_corners, placement survives the save |
| 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/spot channels and a Quick Mask are written as TIFF extra samples (at most 16) plus Photoshop resources for name, colour and solidity; Photoshop's MTrn marker is read (#7415). The TIFF Options Save Transparency choice isn't offered: channels are written as Photoshop does with it off |
| 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/spot channels and a Quick Mask are written as TIFF extra samples (at most 16) plus Photoshop resources for name, colour and solidity; Photoshop's MTrn marker is read (#7415). TIFF Options (ui tiff_options_ui.rs) asks on every TIFF Save As and Save a Copy: compression, Save Image Pyramid, Save Transparency (on writes MTrn next to channels, as Photoshop does) and the layers choice (#8827) |
| 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; flat pages up to 300000 px a side decode a group of rows at a time into the layer (codecs TiffBands, #8169): the 117504 x 22464 px banner from #8456 opens in 3.3 s at 11.45 GB peak; refused with an error past free memory (io memory.rs); layered TIFFs still decode whole; 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 | partial | [#215](https://github.com/storytold/photocraft/issues/215) | io pdf.rs: Save As / Save a Copy / CLI write one flattened RGB/Gray/CMYK page with ICC (#3401); print PDFs in print_cmds. Multi-page save, presentation, comps, vector/text output and PDF import (#2541) remain |
@@ -308,7 +308,7 @@ Never-crash attribute on 30 of 30 crate roots.
| BUG-203-6 | Failure-injection tests: mid-write, rename and read-only dir errors keep original bytes | done | [#203](https://github.com/storytold/photocraft/issues/203) | format/src/atomic/tests.rs: Faulty AtomicFs injects mid-write StorageFull, rename failure and a read-only dir; locked-target retries, symlink and file-mode preservation covered too |
| BUG-204-1 | Interface prefs (UI scale, font size, channels in colour, sliders, tooltips) wired or hidden | done | [#204](https://github.com/storytold/photocraft/issues/204) | prefs_ui.rs tick reads ui_scale (sync_display_scale), ui_font_size (theme::set_ui_font_size) and show_tooltips (sync_tooltips); show_channels_in_color is wired in channel_thumbs and the canvas channel view (#2385); dynamic_color_sliders is in prefs::HIDDEN_UNTIL_IMPLEMENTED |
| BUG-204-2 | workspace.large_tabs, animated_zoom, auto_show_home_screen wired or hidden | done | [#204](https://github.com/storytold/photocraft/issues/204) | workspace.large_tabs controls document tab height in canvas.rs; auto_show_home_screen drives the Home screen; general.animated_zoom gates discrete canvas zoom transitions and continuous held Zoom tool presses (zoom_hold.rs, #6210), and is exposed in General preferences |
| BUG-204-3 | RAW prefs and ask_before_saving_layered_tiff read, or hidden | done | [#204](https://github.com/storytold/photocraft/issues/204) | ask_before_saving_layered_tiff drives the TIFF Options prompt (ui-egui tiff_options_ui.rs); raw_defaults.open_in_camera_raw drives the Camera Raw dialog (camera_raw_ui.rs); the other raw_defaults fields drive the raw open and Camera Raw (#5128) |
| BUG-204-3 | RAW prefs and ask_before_saving_layered_tiff read, or hidden | done | [#204](https://github.com/storytold/photocraft/issues/204) | ask_before_saving_layered_tiff drives the layered-file note and its Don't show again in TIFF Options (ui-egui tiff_options_ui.rs); raw_defaults.open_in_camera_raw drives the Camera Raw dialog (camera_raw_ui.rs); the other raw_defaults fields drive the raw open and Camera Raw (#5128) |
| BUG-204-4 | Recent files persisted through prefs across restarts | done | [#204](https://github.com/storytold/photocraft/issues/204) | crates/ui-egui/src/lib.rs::push_recent stores the list in preferences; prefs_ui::load restores it and recent_files_survive_a_restart_and_honour_the_count verifies reload |
| BUG-204-5 | Recent-files list honours recent_file_count (default 20) | done | [#204](https://github.com/storytold/photocraft/issues/204) | lib.rs push_recent caps the list with recent_cap (recent_file_count); menus.rs covers default and custom limits |
| BUG-204-6 | Test: every Prefs field is read somewhere or on a hidden allowlist | done | [#204](https://github.com/storytold/photocraft/issues/204) | crates/engine/tests/it/prefs_usage.rs every_preference_is_read_or_hidden: each field is read outside prefs.rs or listed in prefs::HIDDEN_UNTIL_IMPLEMENTED, never both |
+1 -1
View File
@@ -67,7 +67,7 @@ id = "BUG-204-3"
target = "RAW prefs and ask_before_saving_layered_tiff read, or hidden"
status = "done"
issue = 204
note = "ask_before_saving_layered_tiff drives the TIFF Options prompt (ui-egui tiff_options_ui.rs); raw_defaults.open_in_camera_raw drives the Camera Raw dialog (camera_raw_ui.rs); the other raw_defaults fields drive the raw open and Camera Raw (#5128)"
note = "ask_before_saving_layered_tiff drives the layered-file note and its Don't show again in TIFF Options (ui-egui tiff_options_ui.rs); raw_defaults.open_in_camera_raw drives the Camera Raw dialog (camera_raw_ui.rs); the other raw_defaults fields drive the raw open and Camera Raw (#5128)"
[[item]]
id = "BUG-204-4"
+1 -1
View File
@@ -52,7 +52,7 @@ id = "FILE-215-7"
target = "Layered TIFF read and write (tag 37724), honouring the ask-before-saving pref"
status = "done"
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/spot channels and a Quick Mask are written as TIFF extra samples (at most 16) plus Photoshop resources for name, colour and solidity; Photoshop's MTrn marker is read (#7415). The TIFF Options Save Transparency choice isn't offered: channels are written as Photoshop does with it off"
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/spot channels and a Quick Mask are written as TIFF extra samples (at most 16) plus Photoshop resources for name, colour and solidity; Photoshop's MTrn marker is read (#7415). TIFF Options (ui tiff_options_ui.rs) asks on every TIFF Save As and Save a Copy: compression, Save Image Pyramid, Save Transparency (on writes MTrn next to channels, as Photoshop does) and the layers choice (#8827)"
[[item]]
id = "FILE-215-8"