Skip to content

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

Headless saves write a flat TIFF unless they ask for layers (#825)

Tanish Manku41e9c742dc51
diff --git a/apps/photocraft-cli/src/lib.rs b/apps/photocraft-cli/src/lib.rs
index cfbb0b19e..6aada3b09 100644
--- a/apps/photocraft-cli/src/lib.rs
+++ b/apps/photocraft-cli/src/lib.rs
@@ -14,14 +14,15 @@ pub const USAGE: &str = "\
photocraft-cli: headless Photocraft
USAGE:
- photocraft-cli convert <in> <out> [--format <ext>] [--quality <1-100>]
+ photocraft-cli convert <in> <out> [--format <ext>] [--quality <1-100>] [--tiff-layers]
Convert between formats (.pcraft, .psd, .png, .jpg, .tif, .webp, .exr, …).
+ TIFF output is flat unless --tiff-layers keeps the layers (Photoshop layer data).
photocraft-cli info <file> [--compact]
Print the document as JSON (size, mode, depth, layer tree).
- photocraft-cli run (<file> | --new <json>) --cmd <id> [--params <json>] [--cmd …] [--out <file>] [--format <ext>] [--quality <1-100>]
+ photocraft-cli run (<file> | --new <json>) --cmd <id> [--params <json>] [--cmd …] [--out <file>] [--format <ext>] [--quality <1-100>] [--tiff-layers]
Open a file, run engine commands in order, save the result. Each --params
applies to the preceding --cmd. Prints each command's JSON result.
- photocraft-cli batch --actions <actions.json> --in <dir> --out <dir> [--format <ext>] [--quality <1-100>] [--in-place]
+ photocraft-cli batch --actions <actions.json> --in <dir> --out <dir> [--format <ext>] [--quality <1-100>] [--in-place] [--tiff-layers]
Apply an action list to every image in a directory. Steps are [id, params] pairs,
{\"command\": id, \"params\": {…}} objects or bare ids, as a recorded action or droplet stores them
(a list, or wrapped in {\"actions\": …}, {\"steps\": …} or a droplet). An --out folder that is the
@@ -59,10 +60,10 @@ struct Subcommand {
}
const SUBCOMMANDS: &[Subcommand] = &[
- Subcommand { name: "convert", values: &["--format", "--quality"], bare: &[], run: convert },
+ Subcommand { name: "convert", values: &["--format", "--quality"], bare: &["--tiff-layers"], run: convert },
Subcommand { name: "info", values: &[], bare: &["--compact"], run: |a, out, _| info(a, out) },
- Subcommand { name: "run", values: &["--new", "--cmd", "--params", "--out", "--format", "--quality"], bare: &[], run: run_cmds },
- Subcommand { name: "batch", values: &["--actions", "--in", "--out", "--format", "--quality"], bare: &["--in-place"], run: batch },
+ Subcommand { name: "run", values: &["--new", "--cmd", "--params", "--out", "--format", "--quality"], bare: &["--tiff-layers"], run: run_cmds },
+ Subcommand { name: "batch", values: &["--actions", "--in", "--out", "--format", "--quality"], bare: &["--in-place", "--tiff-layers"], run: batch },
Subcommand { name: "droplet", values: &["--out"], bare: &[], run: droplet },
Subcommand { name: "commands", values: &["--filter"], bare: &["--json"], run: |a, out, _| commands(a, out) },
Subcommand {
@@ -166,7 +167,8 @@ pub fn run(args: &[String], out: &mut dyn Write, err: &mut dyn Write) -> i32 {
}
fn export_opts(a: &Args) -> Result<ExportOptions, String> {
- let mut o = ExportOptions::default();
+ // TIFF output is flat unless asked: scripted conversions keep predictable sizes.
+ let mut o = ExportOptions { tiff_layers: a.has("--tiff-layers"), ..Default::default() };
if let Some(q) = a.get("--quality") {
o.encode.jpeg_quality =
q.parse().ok().filter(|q| (1..=100).contains(q)).ok_or_else(|| format!("bad --quality `{q}`: expected a whole number from 1 to 100"))?;
diff --git a/apps/photocraft-cli/tests/cli.rs b/apps/photocraft-cli/tests/cli.rs
index 90d596634..c3f934741 100644
--- a/apps/photocraft-cli/tests/cli.rs
+++ b/apps/photocraft-cli/tests/cli.rs
@@ -517,3 +517,32 @@ fn droplet_runs_an_action_on_files() {
let o = bin().arg("droplet").arg(d.join("a.png")).arg(d.join("b.png")).output().unwrap();
assert!(!o.status.success(), "not a droplet");
}
+
+#[test]
+fn tiff_output_is_flat_unless_tiff_layers_is_given() {
+ let d = tmp("tiff-layers");
+ let layer_count = |path: &std::path::Path| -> usize {
+ let (info, _) = ok(bin().arg("info").arg(path));
+ let v: Value = serde_json::from_str(&info).unwrap();
+ v["layers"].as_array().unwrap().len()
+ };
+ for (name, flag, layers) in [("flat.tif", None, 1), ("layered.tif", Some("--tiff-layers"), 2)] {
+ let out = d.join(name);
+ let mut cmd = bin();
+ cmd.args(["run", "--new", r#"{"width":16,"height":16}"#]).args(["--cmd", "layer.new.layer", "--params", r#"{"name":"Ink"}"#]);
+ if let Some(flag) = flag {
+ cmd.arg(flag);
+ }
+ ok(cmd.arg("--out").arg(&out));
+ assert_eq!(layer_count(&out), layers, "{name}");
+ }
+ // convert honours the same flag.
+ let src = d.join("layered.tif");
+ let flat = d.join("converted.tif");
+ ok(bin().arg("convert").arg(&src).arg(&flat));
+ assert_eq!(layer_count(&flat), 1);
+ let kept = d.join("kept.tif");
+ ok(bin().arg("convert").arg(&src).arg(&kept).arg("--tiff-layers"));
+ assert_eq!(layer_count(&kept), 2);
+ std::fs::remove_dir_all(d).unwrap();
+}
diff --git a/book/src/formats/raster-formats.md b/book/src/formats/raster-formats.md
index a5df1510c..cbbdc00e7 100644
--- a/book/src/formats/raster-formats.md
+++ b/book/src/formats/raster-formats.md
@@ -4,7 +4,7 @@
## Layered TIFF
-A TIFF saved by Photoshop with its layers carries them in two private tags: 37724 (`ImageSourceData`, the same layer section a PSD has, preceded by the string `Adobe Photoshop Document Data Block`) and 34377 (the PSD image resources). `photocraft-codecs` passes both through as opaque bytes on `Metadata`; `photocraft-io` rebuilds a PSD model from them plus the TIFF's pixels and hands it to the PSD importer, so groups, masks, layer styles, type, shapes, smart objects and adjustment layers open from a TIFF exactly as from a PSD, and are written back the same way. In Intel-order (`II`) files Photoshop stores the whole block structure byte-swapped (reversed keys such as `MIB8` and `ryaL`, little-endian integers and doubles) while pixel samples stay big-endian; `photocraft-psd`'s `tiff` module converts between the two orders field by field, and drops, with a warning, any block whose layout it does not know rather than pass byte-swapped data to other readers. Limits: a TIFF holds one transparency sample, so extra alpha channels are not written; Lab documents are saved flat. Save As asks "Including layers will increase file size" (with "Discard Layers and Save a Copy") while *Ask Before Saving Layered TIFF Files* is on in Preferences › File Handling.
+A TIFF saved by Photoshop with its layers carries them in two private tags: 37724 (`ImageSourceData`, the same layer section a PSD has, preceded by the string `Adobe Photoshop Document Data Block`) and 34377 (the PSD image resources). `photocraft-codecs` passes both through as opaque bytes on `Metadata`; `photocraft-io` rebuilds a PSD model from them plus the TIFF's pixels and hands it to the PSD importer, so groups, masks, layer styles, type, shapes, smart objects and adjustment layers open from a TIFF exactly as from a PSD, and are written back the same way. In Intel-order (`II`) files Photoshop stores the whole block structure byte-swapped (reversed keys such as `MIB8` and `ryaL`, little-endian integers and doubles) while pixel samples stay big-endian; `photocraft-psd`'s `tiff` module converts between the two orders field by field, and drops, with a warning, any block whose layout it does not know rather than pass byte-swapped data to other readers. Limits: a TIFF holds one transparency sample, so extra alpha channels are not written; Lab documents are saved flat. Save As asks "Including layers will increase file size" (with "Discard Layers and Save a Copy") while *Ask Before Saving Layered TIFF Files* is on in Preferences › File Handling. Scripted and agent saves write a flat TIFF unless they ask for layers: `--tiff-layers` for `photocraft-cli convert`, `run` and `batch`, and `"tiffLayers": true` in the save, batch and export commands and MCP `doc_save`.
Capability details such as sample depth, channel layout, alpha, ICC, EXIF, XMP, DPI, and animation behavior are defined by `crates/codecs/src/format.rs`. Do not infer fidelity from the filename extension alone.
diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs
index b69097b4f..08a555d74 100644
--- a/crates/automation/src/rpc.rs
+++ b/crates/automation/src/rpc.rs
@@ -97,7 +97,8 @@ impl Headless {
}
"doc.new" => self.command_run("file.new", p),
"doc.save" => {
- let mut opts = photocraft_io::ExportOptions::default();
+ let mut opts =
+ photocraft_io::ExportOptions { tiff_layers: p.get("tiffLayers").and_then(Value::as_bool).unwrap_or(false), ..Default::default() };
if let Some(q) = p.get("quality").and_then(Value::as_u64) {
opts.encode.jpeg_quality = q.clamp(1, 100) as u8;
}
diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs
index 4cd8f3743..8db284bc9 100644
--- a/crates/automation/src/server.rs
+++ b/crates/automation/src/server.rs
@@ -83,6 +83,9 @@ pub struct SaveParams {
/// JPEG quality 1..100 for lossy exports.
#[serde(default)]
pub quality: Option<u8>,
+ /// TIFF: keep the layers (Photoshop layer data). Off by default: a flat TIFF.
+ #[serde(default, rename = "tiffLayers")]
+ pub tiff_layers: bool,
#[serde(default)]
pub index: Option<usize>,
}
@@ -657,7 +660,7 @@ impl PhotocraftMcp {
}
let Some(r) = self
.headless_op(move |h| {
- let mut opts = photocraft_io::ExportOptions::default();
+ let mut opts = photocraft_io::ExportOptions { tiff_layers: p.tiff_layers, ..Default::default() };
if let Some(q) = p.quality {
opts.encode.jpeg_quality = q.clamp(1, 100);
}
diff --git a/crates/engine/src/artboard_cmds.rs b/crates/engine/src/artboard_cmds.rs
index 1ebc43950..eb1fe2c3d 100644
--- a/crates/engine/src/artboard_cmds.rs
+++ b/crates/engine/src/artboard_cmds.rs
@@ -14,7 +14,7 @@ use photocraft_raster::Surface;
use serde_json::{Value, json};
use crate::commands::{CommandSpec, color_param, int};
-use crate::file_cmds::{encode, f64_param, join, native_doc, sanitize, save_doc, stem, str_param, write_file};
+use crate::file_cmds::{SaveOpts, encode, f64_param, join, native_doc, sanitize, save_doc, stem, str_param, write_file};
use crate::{EngineError, Result, Session};
/// Artboard size presets (name, width, height) in pixels, Photoshop's common devices and pages.
@@ -347,7 +347,7 @@ fn artboards_to_files(s: &mut Session, p: &Value) -> Result<Value> {
let Some(one) = artboard_document(&doc, id) else { continue };
let name = if prefix.is_empty() { sanitize(&one.name) } else { format!("{}_{}", sanitize(&prefix), sanitize(&one.name)) };
let path = join(&dir, &format!("{name}.{format}"));
- save_doc(&one, &path, f64_param(p, "quality"))?;
+ save_doc(&one, &path, SaveOpts::from_params(p))?;
files.push(path);
}
if files.is_empty() {
diff --git a/crates/engine/src/comps_cmds.rs b/crates/engine/src/comps_cmds.rs
index 386288c25..55c4bcd29 100644
--- a/crates/engine/src/comps_cmds.rs
+++ b/crates/engine/src/comps_cmds.rs
@@ -11,7 +11,7 @@ use photocraft_doc::{CompLayerState, Document, LayerComp, LayerId};
use serde_json::{Value, json};
use crate::commands::CommandSpec;
-use crate::file_cmds::{f64_param, join, native_doc, sanitize, save_doc, stem, str_param};
+use crate::file_cmds::{SaveOpts, join, native_doc, sanitize, save_doc, stem, str_param};
use crate::{EngineError, Result, Session};
fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
@@ -361,7 +361,7 @@ fn comps_to_files(s: &mut Session, p: &Value) -> Result<Value> {
apply_comp(&mut one, c, false);
one.last_applied_comp = Some(c.id);
let path = join(&dir, &format!("{}_{:04}_{}.{format}", sanitize(&prefix), i, sanitize(&c.name)));
- save_doc(&one, &path, f64_param(p, "quality"))?;
+ save_doc(&one, &path, SaveOpts::from_params(p))?;
files.push(path);
}
if files.is_empty() {
diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs
index e7391ca78..45f7e0f70 100644
--- a/crates/engine/src/file_cmds.rs
+++ b/crates/engine/src/file_cmds.rs
@@ -164,17 +164,45 @@ pub(crate) fn import(name: &str, bytes: &[u8]) -> Result<Document> {
photocraft_io::import(name, bytes).map(|r| r.document).map_err(|e| EngineError::Other(format!("{name}: {e}")))
}
-/// Encodes `doc` for `path`'s extension. `quality` is Photoshop's 0–12 JPEG scale.
-pub(crate) fn encode(doc: &Document, path: &str, quality: Option<f64>) -> Result<(Vec<u8>, Vec<String>)> {
- let mut opts = photocraft_io::ExportOptions::default();
- if let Some(q) = quality {
+/// What a headless save writes beyond the format: JPEG quality and TIFF layers.
+#[derive(Debug, Clone, Copy, Default)]
+pub(crate) struct SaveOpts {
+ /// Photoshop's 0–12 JPEG scale.
+ pub quality: Option<f64>,
+ /// TIFF: keep the layers. Off unless a command's params ask (`"tiffLayers": true`).
+ pub tiff_layers: bool,
+}
+
+impl SaveOpts {
+ /// `quality` and `tiffLayers` from a command's params.
+ pub(crate) fn from_params(p: &Value) -> Self {
+ SaveOpts { quality: f64_param(p, "quality"), tiff_layers: p.get("tiffLayers").and_then(Value::as_bool).unwrap_or(false) }
+ }
+
+ pub(crate) fn or_quality(mut self, q: f64) -> Self {
+ self.quality = self.quality.or(Some(q));
+ self
+ }
+}
+
+impl From<Option<f64>> for SaveOpts {
+ fn from(quality: Option<f64>) -> Self {
+ SaveOpts { quality, ..Default::default() }
+ }
+}
+
+/// Encodes `doc` for `path`'s extension.
+pub(crate) fn encode(doc: &Document, path: &str, save: impl Into<SaveOpts>) -> Result<(Vec<u8>, Vec<String>)> {
+ let save = save.into();
+ let mut opts = photocraft_io::ExportOptions { tiff_layers: save.tiff_layers, ..Default::default() };
+ if let Some(q) = save.quality {
opts.encode.jpeg_quality = (q.clamp(0.0, 12.0) / 12.0 * 99.0 + 1.0).round() as u8;
}
photocraft_io::export(doc, path, &opts).map(|r| (r.bytes, r.warnings)).map_err(|e| EngineError::Other(format!("{path}: {e}")))
}
-pub(crate) fn save_doc(doc: &Document, path: &str, quality: Option<f64>) -> Result<Vec<String>> {
- let (bytes, warnings) = encode(doc, path, quality)?;
+pub(crate) fn save_doc(doc: &Document, path: &str, save: impl Into<SaveOpts>) -> Result<Vec<String>> {
+ let (bytes, warnings) = encode(doc, path, save)?;
write_file(path, &bytes)?;
Ok(warnings)
}
@@ -269,7 +297,7 @@ fn save_a_copy(s: &mut Session, p: &Value) -> Result<Value> {
let px = flattened(&doc, fmt);
doc.layers = vec![Layer::new("Background", LayerContent::Raster(px))];
}
- let warnings = save_doc(&doc, &path, f64_param(p, "quality"))?;
+ let warnings = save_doc(&doc, &path, SaveOpts::from_params(p))?;
Ok(json!({"path": path, "warnings": warnings}))
}
@@ -608,14 +636,7 @@ pub(crate) fn batch_inputs(p: &Value, cmd: &str) -> Result<Vec<String>> {
/// Opens each input in a scratch session, runs `f` on it and saves it to `output` as `format`
/// (`"same"` keeps the input's extension). Errors per file are collected, not fatal.
-pub(crate) fn process_files(
- inputs: &[String],
- output: &str,
- format: &str,
- quality: Option<f64>,
- suffix: &str,
- f: &dyn Fn(&mut Session) -> Result<()>,
-) -> Value {
+pub(crate) fn process_files(inputs: &[String], output: &str, format: &str, save: SaveOpts, suffix: &str, f: &dyn Fn(&mut Session) -> Result<()>) -> Value {
let mut files = Vec::new();
let mut errors = Vec::new();
let mut written = OutputClaims::default();
@@ -631,7 +652,7 @@ pub(crate) fn process_files(
scratch.add_document(doc, Some(path.clone()));
f(&mut scratch)?;
let d = scratch.active().ok_or(EngineError::NoDocument)?;
- save_doc(&d.doc, &out, quality)?;
+ save_doc(&d.doc, &out, save)?;
Ok(())
})();
match r {
@@ -676,7 +697,7 @@ fn batch(_s: &mut Session, p: &Value) -> Result<Value> {
let inputs = batch_inputs(p, cmd)?;
let output = str_param(p, "output", cmd)?.to_string();
let format = p.get("format").and_then(Value::as_str).unwrap_or("same").to_string();
- let r = process_files(&inputs, &output, &format, f64_param(p, "quality"), "", &|scratch| {
+ let r = process_files(&inputs, &output, &format, SaveOpts::from_params(p), "", &|scratch| {
for (id, params) in &steps {
scratch.execute(id, params.clone())?;
}
@@ -695,7 +716,7 @@ fn image_processor(_s: &mut Session, p: &Value) -> Result<Value> {
(w, h) => Some(json!({"width": w.unwrap_or(1e9), "height": h.unwrap_or(1e9), "dontEnlarge": true})),
};
let to_srgb = p.get("convertToSrgb").and_then(Value::as_bool).unwrap_or(false);
- let r = process_files(&inputs, &output, &format, f64_param(p, "quality").or(Some(8.0)), "", &|scratch| {
+ let r = process_files(&inputs, &output, &format, SaveOpts::from_params(p).or_quality(8.0), "", &|scratch| {
if to_srgb && scratch.active().is_some_and(|d| d.doc.mode != ColorMode::Rgb) {
scratch.execute("image.mode.rgb", json!({}))?;
}
@@ -852,7 +873,7 @@ fn layers_to_files(s: &mut Session, p: &Value) -> Result<Value> {
only.clipped = false;
one.layers = vec![only];
let path = join(&dir, &format!("{}_{:04}_{}.{format}", sanitize(&prefix), i, sanitize(&l.name)));
- save_doc(&one, &path, f64_param(p, "quality"))?;
+ save_doc(&one, &path, SaveOpts::from_params(p))?;
files.push(path);
}
Ok(json!({"files": files}))
@@ -1050,7 +1071,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),"layers":bool=true}"##,
+ r##"{"path":str (format from the extension),"quality":0..12? (JPEG),"layers":bool=true,"tiffLayers":bool=false (TIFF: keep the layers; flat by default)}"##,
native_doc,
save_a_copy
),
@@ -1107,7 +1128,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Batch…",
&["File", "Automate"],
None,
- r##"{"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action),"input":folder|[paths],"output":folder,"format":"same|png|jpg|psd|tiff|…"="same","quality":0..12?} → {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),"input":folder|[paths],"output":folder,"format":"same|png|jpg|psd|tiff|…"="same","quality":0..12?,"tiffLayers":bool=false} → {files, errors} (an input whose output name was already written in the run goes to errors)"##,
native,
batch
),
@@ -1116,7 +1137,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Image Processor…",
&["File", "Scripts"],
None,
- r##"{"input":folder|[paths],"output":folder,"format":"jpg|png|psd|tiff|…"="jpg","quality":0..12=8,"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],"output":folder,"format":"jpg|png|psd|tiff|…"="jpg","quality":0..12=8,"tiffLayers":bool=false,"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
),
@@ -1144,7 +1165,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,"quality":0..12?} → {files}"##,
+ r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"visibleOnly":bool=true,"quality":0..12?,"tiffLayers":bool=false} → {files}"##,
native_doc,
layers_to_files
),
diff --git a/crates/engine/src/lens_cmds.rs b/crates/engine/src/lens_cmds.rs
index 20d0f7b8c..1fc6f0cf8 100644
--- a/crates/engine/src/lens_cmds.rs
+++ b/crates/engine/src/lens_cmds.rs
@@ -365,7 +365,7 @@ fn lens_batch(_s: &mut Session, p: &Value) -> Result<Value> {
// Batch default: the EXIF-driven profile, as Photoshop's dialog suggests.
m.entry("profile").or_insert(json!("auto"));
}
- let r = crate::file_cmds::process_files(&inputs, &output, &format, crate::file_cmds::f64_param(p, "quality"), "", &|scratch| {
+ let r = crate::file_cmds::process_files(&inputs, &output, &format, crate::file_cmds::SaveOpts::from_params(p), "", &|scratch| {
if scratch.active().is_some_and(|d| d.doc.layers.len() > 1) {
scratch.execute("layer.flattenImage", json!({}))?;
}
diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs
index 721e5b3dd..4ea5c2f4d 100644
--- a/crates/io/src/lib.rs
+++ b/crates/io/src/lib.rs
@@ -118,8 +118,10 @@ pub struct ExportOptions {
pub encode: EncodeOptions,
/// Write PSB even for `.psd` names when the document is small.
pub force_psb: bool,
- /// TIFF: keep the layers (Photoshop layer data in tag 37724). `false` is Photoshop's
- /// "Discard Layers and Save a Copy": a flat TIFF.
+ /// TIFF: keep the layers (Photoshop layer data in tag 37724). Off by default, so scripted
+ /// and agent saves (CLI, batch, MCP) write a flat TIFF unless they ask for layers; the app's
+ /// 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,
/// Which part of the document's XMP packet a flat export embeds (PSD/PSB/`.pcraft`
/// always keep everything). Everything by default, as Save As does; Export As offers None.
@@ -128,7 +130,7 @@ pub struct ExportOptions {
impl Default for ExportOptions {
fn default() -> Self {
- ExportOptions { encode: EncodeOptions::default(), force_psb: false, tiff_layers: true, xmp: XmpEmbed::All }
+ ExportOptions { encode: EncodeOptions::default(), force_psb: false, tiff_layers: false, xmp: XmpEmbed::All }
}
}
diff --git a/crates/io/tests/tiff_layers.rs b/crates/io/tests/tiff_layers.rs
index 2b7bcf46f..068413f17 100644
--- a/crates/io/tests/tiff_layers.rs
+++ b/crates/io/tests/tiff_layers.rs
@@ -99,7 +99,7 @@ fn every_compression_keeps_the_layers() {
use photocraft_codecs::TiffCompression;
let d = gen_doc(ColorMode::Rgb, SampleType::U16, Features::PIXELS);
for c in [TiffCompression::None, TiffCompression::Lzw, TiffCompression::Deflate, TiffCompression::PackBits] {
- let mut opts = ExportOptions::default();
+ let mut opts = ExportOptions { tiff_layers: true, ..Default::default() };
opts.encode.tiff_compression = c;
let r = export(&d, "x.tiff", &opts).unwrap();
let back = import("x.tiff", &r.bytes).unwrap().document;
@@ -164,7 +164,7 @@ fn transparency_is_straight_in_the_composite() {
fn big_documents_use_the_psb_signature() {
// Forcing PSB stands in for a > 30000 px document.
let d = gen_doc(ColorMode::Rgb, SampleType::U8, Features::PIXELS);
- let r = export(&d, "x.tif", &ExportOptions { force_psb: true, ..Default::default() }).unwrap();
+ let r = export(&d, "x.tif", &ExportOptions { force_psb: true, tiff_layers: true, ..Default::default() }).unwrap();
let (_, layers) = tags(&r.bytes);
assert!(layers.unwrap().starts_with(photocraft_psd::tiff::SIGNATURE_PSB));
let back = import("x.tif", &r.bytes).unwrap().document;
@@ -264,3 +264,13 @@ fn damaged_layer_data_opens_flattened() {
}
}
}
+
+#[test]
+fn default_export_options_write_a_flat_tiff() {
+ // Scripted and agent saves (CLI, batch, MCP) build on the defaults: layers only on request.
+ let d = gen_doc(ColorMode::Rgb, SampleType::U8, Features::PIXELS);
+ assert!(tiff_layers::would_write_layers(&d));
+ let r = export(&d, "x.tif", &ExportOptions::default()).unwrap();
+ assert_eq!(tags(&r.bytes), (None, None));
+ assert_eq!(import("x.tif", &r.bytes).unwrap().document.layers.len(), 1);
+}