Skip to content

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

File Handling: wire Image Previews to embed a PSD thumbnail (#204) (#2971)

David Mann8a72978549ca
diff --git a/apps/photocraft-web/src/web.rs b/apps/photocraft-web/src/web.rs
index b6e3c82d6..4f674560e 100644
--- a/apps/photocraft-web/src/web.rs
+++ b/apps/photocraft-web/src/web.rs
@@ -351,6 +351,7 @@ fn services(inbox: Inbox) -> Services {
opts.tiff_layers = settings.tiff_layers;
opts.xmp = if settings.xmp_all { photocraft_io::XmpEmbed::All } else { photocraft_io::XmpEmbed::None };
opts.tga_bits = settings.tga_bits;
+ opts.image_previews = settings.image_previews;
photocraft_io::export(doc, path, &opts).map(|r| (r.bytes, r.warnings)).map_err(|e| e.to_string())
})),
file_dialog: Some(Box::new(|request, _parent, reply| match request {
diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs
index e3e17dc7c..739fb2363 100644
--- a/apps/photocraft/src/services.rs
+++ b/apps/photocraft/src/services.rs
@@ -199,6 +199,7 @@ fn export_options(settings: &photocraft_ui_egui::ExportSettings) -> photocraft_i
opts.tiff_layers = settings.tiff_layers;
opts.xmp = if settings.xmp_all { photocraft_io::XmpEmbed::All } else { photocraft_io::XmpEmbed::None };
opts.tga_bits = settings.tga_bits;
+ opts.image_previews = settings.image_previews;
opts
}
diff --git a/crates/engine/src/artboard_cmds.rs b/crates/engine/src/artboard_cmds.rs
index 8ec0b7716..ed80e89b6 100644
--- a/crates/engine/src/artboard_cmds.rs
+++ b/crates/engine/src/artboard_cmds.rs
@@ -434,7 +434,7 @@ fn artboards_to_files(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "file.export.artboardsToFiles";
let dir = str_param(p, "dir", cmd).or_else(|_| str_param(p, "output", cmd))?.to_string();
let format = p.get("format").and_then(Value::as_str).unwrap_or("png").trim_start_matches('.').to_ascii_lowercase();
- let save = SaveOpts::from_params(p, cmd)?;
+ let save = SaveOpts::from_params(s, p, cmd)?;
let d = s.active().ok_or(EngineError::NoDocument)?;
let prefix = p.get("prefix").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name));
let doc = d.doc.clone();
diff --git a/crates/engine/src/comps_cmds.rs b/crates/engine/src/comps_cmds.rs
index f29723fb7..58f92f84e 100644
--- a/crates/engine/src/comps_cmds.rs
+++ b/crates/engine/src/comps_cmds.rs
@@ -367,7 +367,7 @@ fn comps_to_files(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "file.export.layerCompsToFiles";
let dir = str_param(p, "dir", cmd).or_else(|_| str_param(p, "output", cmd))?.to_string();
let format = p.get("format").and_then(Value::as_str).unwrap_or("png").trim_start_matches('.').to_ascii_lowercase();
- let save = SaveOpts::from_params(p, cmd)?;
+ let save = SaveOpts::from_params(s, p, cmd)?;
let d = s.active().ok_or(EngineError::NoDocument)?;
let prefix = p.get("prefix").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name));
let doc = d.doc.clone();
diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs
index ad3c6adef..32298b895 100644
--- a/crates/engine/src/file_cmds.rs
+++ b/crates/engine/src/file_cmds.rs
@@ -218,8 +218,9 @@ pub(crate) fn import(name: &str, bytes: &[u8]) -> Result<Document> {
Ok(r.document)
}
-/// What a headless save writes beyond the format: JPEG quality, TIFF layers and Targa bits.
-#[derive(Debug, Clone, Copy, Default)]
+/// What a headless save writes beyond the format: JPEG quality, TIFF layers, Targa bits and PSD
+/// previews.
+#[derive(Debug, Clone, Copy)]
pub(crate) struct SaveOpts {
/// Photoshop's 0–12 JPEG scale.
pub quality: Option<f64>,
@@ -228,16 +229,27 @@ pub(crate) struct SaveOpts {
/// Targa: 24 or 32 bits per pixel (`"tgaBits"`); unset, 32 with an alpha channel or
/// transparency, else 24.
pub tga_bits: Option<photocraft_io::TgaBits>,
+ /// PSD/PSB: embed the thumbnail resource (Preferences › File Handling › Image Previews).
+ pub image_previews: bool,
+}
+
+impl Default for SaveOpts {
+ fn default() -> Self {
+ SaveOpts { quality: None, tiff_layers: false, tga_bits: None, image_previews: true }
+ }
}
impl SaveOpts {
- /// `quality`, `tiffLayers` and `tgaBits` from command `cmd`'s params; a `tgaBits` other than
- /// 24 or 32 is an error.
- pub(crate) fn from_params(p: &Value, cmd: &str) -> Result<Self> {
+ /// `quality`, `tiffLayers` and `tgaBits` from command `cmd`'s params (a `tgaBits` other than
+ /// 24 or 32 is an error); the image previews from the session's File Handling preferences
+ /// (Ask When Saving has no dialog here, so it saves them, as Photoshop's Save As checkbox
+ /// starts on).
+ pub(crate) fn from_params(s: &Session, p: &Value, cmd: &str) -> Result<Self> {
Ok(SaveOpts {
quality: f64_param(p, "quality"),
tiff_layers: p.get("tiffLayers").and_then(Value::as_bool).unwrap_or(false),
tga_bits: tga_bits_param(p, cmd)?,
+ image_previews: s.prefs().file_handling.image_previews != crate::prefs::Ask::Never,
})
}
@@ -271,7 +283,8 @@ pub fn tga_bits_param(p: &Value, cmd: &str) -> Result<Option<photocraft_io::TgaB
pub(crate) fn encode(doc: &Document, path: &str, save: impl Into<SaveOpts>) -> Result<(Vec<u8>, Vec<String>)> {
crate::allocation::checkpoint("saving document")?;
let save = save.into();
- let mut opts = photocraft_io::ExportOptions { tiff_layers: save.tiff_layers, tga_bits: save.tga_bits, ..Default::default() };
+ let mut opts =
+ photocraft_io::ExportOptions { tiff_layers: save.tiff_layers, tga_bits: save.tga_bits, image_previews: save.image_previews, ..Default::default() };
if let Some(q) = save.quality {
let q = (q.clamp(0.0, 12.0) / 12.0 * 99.0 + 1.0).round() as u8;
opts.encode.jpeg_quality = q;
@@ -378,7 +391,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, SaveOpts::from_params(p, "file.saveACopy")?)?;
+ let warnings = save_doc(&doc, &path, SaveOpts::from_params(s, p, "file.saveACopy")?)?;
Ok(json!({"path": path, "warnings": warnings}))
}
@@ -938,7 +951,7 @@ fn batch(s: &mut Session, p: &Value) -> Result<Value> {
}
};
let actions = crate::actions_cmds::ActionState { list, playing: s.actions.playing, playback_stack: s.actions.playback_stack.clone(), ..Default::default() };
- let r = process_files(&inputs, &output, &format, SaveOpts::from_params(p, cmd)?, "", &|scratch| {
+ let r = process_files(&inputs, &output, &format, SaveOpts::from_params(s, p, cmd)?, "", &|scratch| {
scratch.actions = actions.clone();
for (id, params) in &steps {
let r = scratch.execute(id, params.clone())?;
@@ -952,7 +965,7 @@ fn batch(s: &mut Session, p: &Value) -> Result<Value> {
Ok(r)
}
-fn image_processor(_s: &mut Session, p: &Value) -> Result<Value> {
+fn image_processor(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "file.scripts.imageProcessor";
let inputs = batch_inputs(p, cmd)?;
let output = str_param(p, "output", cmd)?.to_string();
@@ -962,7 +975,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, SaveOpts::from_params(p, cmd)?.or_quality(8.0), "", &|scratch| {
+ let r = process_files(&inputs, &output, &format, SaveOpts::from_params(s, p, cmd)?.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!({}))?;
}
@@ -1103,7 +1116,7 @@ fn layers_to_files(s: &mut Session, p: &Value) -> Result<Value> {
let dir = str_param(p, "dir", cmd).or_else(|_| str_param(p, "output", cmd))?.to_string();
let format = p.get("format").and_then(Value::as_str).unwrap_or("png").trim_start_matches('.').to_ascii_lowercase();
let visible_only = p.get("visibleOnly").and_then(Value::as_bool).unwrap_or(true);
- let save = SaveOpts::from_params(p, cmd)?;
+ let save = SaveOpts::from_params(s, p, cmd)?;
let d = s.active().ok_or(EngineError::NoDocument)?;
let prefix = p.get("prefix").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name));
let doc = d.doc.clone();
diff --git a/crates/engine/src/file_cmds/tests.rs b/crates/engine/src/file_cmds/tests.rs
index b7a92ff92..f301d4c9a 100644
--- a/crates/engine/src/file_cmds/tests.rs
+++ b/crates/engine/src/file_cmds/tests.rs
@@ -171,6 +171,27 @@ fn bad_targa_bits_are_refused_before_writing() {
}
}
+/// Preferences › File Handling › Image Previews decides whether a PSD gets Photoshop's
+/// thumbnail resource (1036): Always and Ask When Saving write it, Never doesn't.
+#[test]
+fn image_previews_preference_controls_the_psd_thumbnail() {
+ use crate::prefs::Ask;
+ let dir = tmp("previews");
+ let mut s = session(300, 200, 16);
+ let has_thumbnail = |path: &str| {
+ let file = photocraft_psd::PsdFile::from_bytes(&std::fs::read(path).unwrap()).unwrap();
+ file.resources.iter().any(|r| r.id == photocraft_psd::resources::ids::THUMBNAIL)
+ };
+ for (ask, expect) in [(Ask::Always, true), (Ask::Never, false), (Ask::Ask, true)] {
+ s.edit_prefs(|p| p.file_handling.image_previews = ask);
+ let out = join(&dir, &format!("{ask:?}.psd"));
+ s.execute("file.saveACopy", json!({"path": out})).unwrap();
+ assert_eq!(has_thumbnail(&out), expect, "{ask:?}");
+ let png = join(&dir, &format!("{ask:?}.png"));
+ s.execute("file.saveACopy", json!({"path": png})).unwrap();
+ }
+}
+
#[test]
fn open_as_forces_the_decoder() {
let dir = tmp("openas");
diff --git a/crates/engine/src/lens_cmds.rs b/crates/engine/src/lens_cmds.rs
index d2b36e948..c0513cf37 100644
--- a/crates/engine/src/lens_cmds.rs
+++ b/crates/engine/src/lens_cmds.rs
@@ -390,7 +390,7 @@ fn camera_raw_cmd(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"layer": id.0, "identity": cr.is_identity(), "ms": t0.ms()}))
}
-fn lens_batch(_s: &mut Session, p: &Value) -> Result<Value> {
+fn lens_batch(s: &mut Session, p: &Value) -> Result<Value> {
let inputs = crate::file_cmds::batch_inputs(p, LENS_BATCH)?;
let output = crate::file_cmds::str_param(p, "output", LENS_BATCH)?.to_string();
let format = p.get("format").and_then(Value::as_str).unwrap_or("same").to_string();
@@ -402,7 +402,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::SaveOpts::from_params(p, LENS_BATCH)?, "", &|scratch| {
+ let r = crate::file_cmds::process_files(&inputs, &output, &format, crate::file_cmds::SaveOpts::from_params(s, p, LENS_BATCH)?, "", &|scratch| {
if scratch.active().is_some_and(|d| d.doc.layers.len() > 1) {
scratch.execute("layer.flattenImage", json!({}))?;
}
diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs
index eb8151508..3cb420fcb 100644
--- a/crates/engine/src/prefs.rs
+++ b/crates/engine/src/prefs.rs
@@ -998,7 +998,6 @@ pub const HIDDEN_UNTIL_IMPLEMENTED: &[&str] = &[
"workspace.autoShowHiddenPanels",
"workspace.enableFloatingDocumentWindowDocking",
"workspace.enableNarrowOptionsBar",
- "fileHandling.imagePreviews",
"fileHandling.saveInBackground",
"fileHandling.ignoreExifProfileTag",
"fileHandling.maximizePsdCompatibility",
diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs
index 53900fdbd..a2b30383d 100644
--- a/crates/io/src/lib.rs
+++ b/crates/io/src/lib.rs
@@ -49,6 +49,7 @@ mod pdn;
pub mod pixels;
mod psd_export;
mod psd_import;
+pub mod psd_thumbnail;
pub mod raw;
pub mod slices_map;
pub mod smart_map;
@@ -165,11 +166,14 @@ pub struct ExportOptions {
/// Targa: bits per pixel of an RGB file. `None` writes 32 when the document has an alpha
/// channel or transparency, else 24; Save As asks, starting at [`tga_default_bits`].
pub tga_bits: Option<TgaBits>,
+ /// PSD/PSB: embed the thumbnail image resource (1036), Preferences › File Handling › Image
+ /// Previews. On by default, as Photoshop's Always Save.
+ pub image_previews: bool,
}
impl Default for ExportOptions {
fn default() -> Self {
- ExportOptions { encode: EncodeOptions::default(), force_psb: false, tiff_layers: false, xmp: XmpEmbed::All, tga_bits: None }
+ ExportOptions { encode: EncodeOptions::default(), force_psb: false, tiff_layers: false, xmp: XmpEmbed::All, tga_bits: None, image_previews: true }
}
}
@@ -320,6 +324,16 @@ pub fn export(doc: &Document, name_or_ext: &str, opts: &ExportOptions) -> Result
warnings.push("free-form text metadata is not supported by PSD/PSB; it will be dropped".into());
}
warnings.extend(tiff_layers::strip_foreign_order_blocks(&mut file));
+ if opts.image_previews {
+ match psd_thumbnail::resource(doc) {
+ // Beside the other resources Photoshop writes ahead of the version info.
+ Ok(r) => {
+ let at = file.resources.iter().position(|r| r.id == photocraft_psd::resources::ids::VERSION_INFO).unwrap_or(file.resources.len());
+ file.resources.insert(at, r);
+ }
+ Err(e) => warnings.push(format!("image preview not saved: {e}")),
+ }
+ }
// Never write a header the reader would refuse (e.g. a zero-sized canvas).
file.header.validate()?;
let bytes = file.to_bytes()?;
diff --git a/crates/io/src/psd_thumbnail.rs b/crates/io/src/psd_thumbnail.rs
new file mode 100644
index 000000000..beaccc5bd
--- /dev/null
+++ b/crates/io/src/psd_thumbnail.rs
@@ -0,0 +1,106 @@
+//! The PSD/PSB thumbnail image resource (1036), written when Preferences › File Handling › Image
+//! Previews saves them (Photoshop's default, Always Save).
+//!
+//! Layout (Adobe PSD spec, "Thumbnail resource format"): a 28-byte big-endian header (format 1 =
+//! kJpegRGB, width, height, widthbytes = (width × 24 + 31) / 32 × 4, total size = widthbytes ×
+//! height, compressed size, bits per pixel 24, planes 1) followed by the JFIF stream. Photoshop
+//! keeps the long side at 160 px or less.
+
+use photocraft_cms::{Builtin, ColorSpace, Intent, Profile, Transform};
+use photocraft_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType as CSample};
+use photocraft_color::ColorMode;
+use photocraft_doc::Document;
+use photocraft_psd::resources::{ImageResource, ids};
+
+use crate::IoError;
+
+/// Longest side of the thumbnail, as Photoshop writes it.
+pub const MAX_SIDE: u32 = 160;
+
+/// Size of the header in front of the JFIF data.
+pub const HEADER_LEN: usize = 28;
+
+/// The 1036 resource for `doc`: its composite reduced to at most [`MAX_SIDE`], converted to
+/// sRGB through the document's profile, matted over white and JPEG-compressed.
+pub(crate) fn resource(doc: &Document) -> Result<ImageResource, IoError> {
+ let mut buf = photocraft_compose::thumbnail_buffer(doc, MAX_SIDE);
+ let (w, h) = (buf.rect.width(), buf.rect.height());
+ if w == 0 || h == 0 || w > MAX_SIDE || h > MAX_SIDE || buf.px.len() != (w as usize) * (h as usize) {
+ return Err(IoError::Unsupported("the image preview could not be rendered".into()));
+ }
+ let src = composite_profile(doc);
+ let dst = Builtin::Srgb.profile();
+ if !src.same_colors(dst) {
+ let t = Transform::new(&src, dst, Intent::RelativeColorimetric, true).map_err(|e| IoError::Unsupported(e.to_string()))?;
+ t.apply(buf.px.as_flattened_mut(), 4);
+ }
+ let mut rgb = Vec::with_capacity(buf.px.len() * 3);
+ for p in &buf.px {
+ let a = finite(p[3]);
+ for &c in &p[..3] {
+ // Over white, as Photoshop shows a transparent document's preview.
+ let v = finite(c) * a + (1.0 - a);
+ rgb.push((v * 255.0).round() as u8);
+ }
+ }
+ let img = Image::from_raw(w, h, ChannelLayout::Rgb, CSample::U8, rgb)?;
+ let opts = EncodeOptions { jpeg_quality: 80, embed_icc: false, embed_metadata: false, ..EncodeOptions::default() };
+ let jfif = photocraft_codecs::encode(&img, Format::Jpeg, &opts)?;
+ Ok(ImageResource::new(ids::THUMBNAIL, thumbnail_bytes(w, h, &jfif)?))
+}
+
+/// A sample clamped to 0–1 (NaN as 0): 32-bit composites can hold values past white.
+fn finite(v: f32) -> f32 {
+ if v.is_nan() { 0.0 } else { v.clamp(0.0, 1.0) }
+}
+
+/// Header plus JFIF data of a `w`×`h` thumbnail resource.
+fn thumbnail_bytes(w: u32, h: u32, jfif: &[u8]) -> Result<Vec<u8>, IoError> {
+ let too_big = || IoError::Unsupported("image preview too large".into());
+ let width_bytes = w.checked_mul(24).map(|v| v.div_ceil(32) * 4).ok_or_else(too_big)?;
+ let total = width_bytes.checked_mul(h).ok_or_else(too_big)?;
+ let compressed = u32::try_from(jfif.len()).map_err(|_| too_big())?;
+ let mut out = Vec::with_capacity(HEADER_LEN + jfif.len());
+ for v in [1, w, h, width_bytes, total, compressed] {
+ out.extend_from_slice(&v.to_be_bytes());
+ }
+ out.extend_from_slice(&24u16.to_be_bytes());
+ out.extend_from_slice(&1u16.to_be_bytes());
+ out.extend_from_slice(jfif);
+ Ok(out)
+}
+
+/// The profile of the compositor's RGB output for `doc`: an RGB document's own (embedded when it
+/// parses, else sRGB), a gray document's gray profile seen as RGB, and sRGB for CMYK and Lab
+/// (which the compositor renders in sRGB).
+fn composite_profile(doc: &Document) -> Profile {
+ let space = match doc.mode {
+ ColorMode::Grayscale | ColorMode::Bitmap | ColorMode::Duotone => ColorSpace::Gray,
+ ColorMode::Cmyk | ColorMode::Lab => return Builtin::Srgb.profile().clone(),
+ _ => ColorSpace::Rgb,
+ };
+ let own = doc.icc_profile.as_ref().and_then(|b| Profile::parse(b).ok()).filter(|p| p.color_space == space);
+ match space {
+ ColorSpace::Gray => {
+ own.and_then(|p| p.gray_as_rgb()).or_else(|| Builtin::SGray.profile().gray_as_rgb()).unwrap_or_else(|| Builtin::Srgb.profile().clone())
+ }
+ _ => own.unwrap_or_else(|| Builtin::Srgb.profile().clone()),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn header_follows_the_spec() {
+ let b = thumbnail_bytes(160, 90, &[0xFF, 0xD8, 0xFF, 0xD9]).unwrap();
+ let u = |i: usize| u32::from_be_bytes(b[i..i + 4].try_into().unwrap());
+ assert_eq!((u(0), u(4), u(8), u(12), u(16), u(20)), (1, 160, 90, 480, 480 * 90, 4));
+ assert_eq!(&b[24..28], &[0, 24, 0, 1]);
+ assert_eq!(&b[28..], &[0xFF, 0xD8, 0xFF, 0xD9]);
+ // Width bytes are padded to 4: 3 px × 3 bytes = 9 → 12.
+ let odd = thumbnail_bytes(3, 1, &[]).unwrap();
+ assert_eq!(u32::from_be_bytes(odd[12..16].try_into().unwrap()), 12);
+ }
+}
diff --git a/crates/io/tests/psd_thumbnail.rs b/crates/io/tests/psd_thumbnail.rs
new file mode 100644
index 000000000..7445bbf75
--- /dev/null
+++ b/crates/io/tests/psd_thumbnail.rs
@@ -0,0 +1,153 @@
+//! Preferences › File Handling › Image Previews: PSD/PSB saves embed Photoshop's thumbnail
+//! resource (1036: 28-byte header + JFIF, ≤ 160 px) unless the previews are turned off.
+
+use photocraft_color::{ColorMode, SampleType};
+use photocraft_doc::{Document, Layer};
+use photocraft_geom::Size;
+use photocraft_io::{ExportOptions, export, import};
+use photocraft_psd::PsdFile;
+use photocraft_psd::resources::ids;
+
+/// A `w`×`h` document of `mode`/`depth` holding one layer of `rgba` (given as straight sRGB-ish
+/// RGBA and converted to the document's model), covering the left `cover` fraction.
+fn doc(mode: ColorMode, depth: SampleType, w: u32, h: u32, rgba: [f32; 4], cover: f32) -> Document {
+ let mut d = Document::new("thumb", Size::new(w, h), mode, depth);
+ let fmt = d.pixel_format();
+ let mut px = vec![0.0; fmt.channels()];
+ photocraft_raster::from_rgba_into(&fmt, rgba, &mut px);
+ let mut layer = Layer::raster("pixels", fmt);
+ let right = ((w as f32 * cover).round() as i32).max(1);
+ layer.surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, right, h as i32), &px);
+ d.layers.push(layer);
+ d
+}
+
+/// The 1036 resource of a saved file, its header checked; returns (width, height, RGB pixels).
+fn thumbnail(bytes: &[u8]) -> Option<(u32, u32, Vec<[f32; 3]>)> {
+ let file = PsdFile::from_bytes(bytes).expect("parse");
+ assert!(!file.resources.iter().any(|r| r.id == ids::THUMBNAIL_PS4), "only the RGB (1036) thumbnail is written");
+ let mut found = file.resources.iter().filter(|r| r.id == ids::THUMBNAIL);
+ let r = found.next()?;
+ assert!(found.next().is_none(), "one thumbnail resource");
+ let d = &r.data;
+ let u = |i: usize| u32::from_be_bytes(d[i..i + 4].try_into().unwrap());
+ let (format, w, h, width_bytes, total, compressed) = (u(0), u(4), u(8), u(12), u(16), u(20));
+ assert_eq!(format, 1, "kJpegRGB");
+ assert!(w >= 1 && h >= 1 && w.max(h) <= 160, "{w}x{h}");
+ assert_eq!(width_bytes, (w * 24).div_ceil(32) * 4);
+ assert_eq!(total, width_bytes * h);
+ assert_eq!(compressed as usize, d.len() - 28);
+ assert_eq!(&d[24..28], &[0, 24, 0, 1], "24 bits per pixel, 1 plane");
+ let jfif = &d[28..];
+ assert!(jfif.starts_with(&[0xFF, 0xD8, 0xFF, 0xE0]) && &jfif[6..11] == b"JFIF\0", "a JFIF stream");
+ let img = photocraft_codecs::decode(jfif).expect("decodes");
+ assert_eq!(img.dimensions(), (w, h));
+ let n = img.layout().channels();
+ assert_eq!(n, 3, "RGB JPEG");
+ let px = img.to_normalized().as_chunks::<3>().0.to_vec();
+ Some((w, h, px))
+}
+
+fn near(a: [f32; 3], b: [f32; 3], tol: f32) -> bool {
+ a.iter().zip(&b).all(|(x, y)| (x - y).abs() <= tol)
+}
+
+#[test]
+fn always_embeds_a_160px_jfif_thumbnail() {
+ let d = doc(ColorMode::Rgb, SampleType::U8, 640, 320, [1.0, 0.0, 0.0, 1.0], 1.0);
+ let out = export(&d, "x.psd", &ExportOptions::default()).unwrap();
+ let (w, h, px) = thumbnail(&out.bytes).expect("Always Save writes the thumbnail");
+ assert_eq!((w, h), (160, 80));
+ let mid = px[(40 * 160 + 80) as usize];
+ assert!(near(mid, [1.0, 0.0, 0.0], 0.08), "{mid:?}");
+ assert!(out.warnings.iter().all(|w| !w.contains("preview")), "{:?}", out.warnings);
+}
+
+#[test]
+fn small_documents_keep_their_size() {
+ let d = doc(ColorMode::Rgb, SampleType::U8, 37, 5, [0.0, 0.0, 1.0, 1.0], 1.0);
+ let (w, h, _) = thumbnail(&export(&d, "x.psd", &ExportOptions::default()).unwrap().bytes).unwrap();
+ assert_eq!((w, h), (37, 5));
+}
+
+#[test]
+fn never_writes_no_thumbnail() {
+ let d = doc(ColorMode::Rgb, SampleType::U8, 64, 64, [0.0, 1.0, 0.0, 1.0], 1.0);
+ for name in ["x.psd", "x.psb"] {
+ let out = export(&d, name, &ExportOptions { image_previews: false, ..Default::default() }).unwrap();
+ assert!(thumbnail(&out.bytes).is_none(), "{name}");
+ }
+}
+
+#[test]
+fn psb_gets_the_thumbnail_too() {
+ let d = doc(ColorMode::Rgb, SampleType::U8, 300, 600, [0.0, 1.0, 0.0, 1.0], 1.0);
+ let out = export(&d, "x.psb", &ExportOptions::default()).unwrap();
+ assert_eq!(out.bytes[5], 2);
+ let (w, h, _) = thumbnail(&out.bytes).unwrap();
+ assert_eq!((w, h), (80, 160));
+}
+
+#[test]
+fn transparency_is_shown_over_white() {
+ let d = doc(ColorMode::Rgb, SampleType::U8, 160, 160, [0.0, 0.0, 0.0, 1.0], 0.5);
+ let (w, _, px) = thumbnail(&export(&d, "x.psd", &ExportOptions::default()).unwrap().bytes).unwrap();
+ let row = 80 * w as usize;
+ assert!(near(px[row + 20], [0.0; 3], 0.08), "{:?}", px[row + 20]);
+ assert!(near(px[row + 140], [1.0; 3], 0.08), "{:?}", px[row + 140]);
+}
+
+#[test]
+fn every_depth_and_mode_gets_an_rgb_thumbnail() {
+ for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab] {
+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ if depth == SampleType::F32 && matches!(mode, ColorMode::Cmyk | ColorMode::Lab) {
+ continue; // Photoshop has no 32-bit CMYK or Lab.
+ }
+ let d = doc(mode, depth, 200, 100, [1.0, 1.0, 1.0, 1.0], 1.0);
+ let out = export(&d, "x.psd", &ExportOptions::default()).unwrap();
+ let (w, h, px) = thumbnail(&out.bytes).unwrap_or_else(|| panic!("{mode:?} {depth:?}: no thumbnail"));
+ assert_eq!((w, h), (160, 80), "{mode:?} {depth:?}");
+ let mid = px[(40 * 160 + 80) as usize];
+ // White paper is white in every model (CMYK through its profile, with BPC).
+ assert!(near(mid, [1.0; 3], 0.1), "{mode:?} {depth:?}: {mid:?}");
+ }
+ }
+}
+
+#[test]
+fn cmyk_and_16_bit_colours_survive_the_conversion() {
+ for (mode, depth) in
+ [(ColorMode::Rgb, SampleType::U16), (ColorMode::Rgb, SampleType::F32), (ColorMode::Cmyk, SampleType::U8), (ColorMode::Lab, SampleType::U16)]
+ {
+ let d = doc(mode, depth, 100, 100, [1.0, 0.0, 0.0, 1.0], 1.0);
+ let (_, _, px) = thumbnail(&export(&d, "x.psd", &ExportOptions::default()).unwrap().bytes).unwrap();
+ let [r, g, b] = px[50 * 100 + 50];
+ assert!(r > 0.7 && g < 0.35 && b < 0.35, "{mode:?} {depth:?}: red reads as {:?}", [r, g, b]);
+ }
+}
+
+#[test]
+fn saved_files_round_trip_and_resave_a_fresh_thumbnail() {
+ let d = doc(ColorMode::Rgb, SampleType::U8, 120, 60, [1.0, 0.0, 0.0, 1.0], 1.0);
+ let first = export(&d, "x.psd", &ExportOptions::default()).unwrap();
+ let back = import("x.psd", &first.bytes).unwrap().document;
+ assert_eq!((back.size.width, back.size.height), (120, 60));
+ // The thumbnail is regenerated, never kept as an opaque resource that would go stale.
+ assert!(back.metadata.psd_resources.iter().all(|(id, _, _)| *id != ids::THUMBNAIL));
+ let again = export(&back, "x.psd", &ExportOptions::default()).unwrap();
+ thumbnail(&again.bytes).expect("one fresh thumbnail");
+ let off = export(&back, "x.psd", &ExportOptions { image_previews: false, ..Default::default() }).unwrap();
+ assert!(thumbnail(&off.bytes).is_none());
+}
+
+#[test]
+fn the_document_profile_is_honoured() {
+ // Mid gray in a linear-sRGB document is sRGB ≈ 0.735, not 0.5: the thumbnail goes through
+ // the embedded profile rather than assuming sRGB.
+ let mut d = doc(ColorMode::Rgb, SampleType::U16, 50, 50, [0.5, 0.5, 0.5, 1.0], 1.0);
+ d.icc_profile = Some(std::sync::Arc::new(photocraft_cms::Builtin::LinearSrgb.profile().to_bytes().to_vec()));
+ let (_, _, px) = thumbnail(&export(&d, "x.psd", &ExportOptions::default()).unwrap().bytes).unwrap();
+ let mid = px[25 * 50 + 25];
+ assert!(near(mid, [0.735; 3], 0.03), "{mid:?}");
+}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 49a0332bc..a1693d945 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -231,11 +231,14 @@ pub struct ExportSettings {
/// Targa: bits per pixel from Targa Options or Export As (`None`: 32 with an alpha channel or
/// transparency, else 24).
pub tga_bits: Option<photocraft_io::TgaBits>,
+ /// PSD/PSB: embed a thumbnail (Preferences › File Handling › Image Previews; see
+ /// [`PhotocraftApp::save_settings`]).
+ pub image_previews: bool,
}
impl Default for ExportSettings {
fn default() -> Self {
- ExportSettings { jpeg_quality: None, webp_lossless: true, webp_quality: None, tiff_layers: true, xmp_all: true, tga_bits: None }
+ ExportSettings { jpeg_quality: None, webp_lossless: true, webp_quality: None, tiff_layers: true, xmp_all: true, tga_bits: None, image_previews: true }
}
}
@@ -1246,6 +1249,14 @@ impl PhotocraftApp {
self.save_as_step(path.to_string(), params.get("tiffLayers").and_then(Value::as_bool), tga_bits)
}
+ /// What a save writes by default under the preferences: File Handling › Image Previews
+ /// decides whether a PSD/PSB gets its thumbnail. Ask When Saving has no Save As checkbox
+ /// here yet, so it saves the preview, as Photoshop's checkbox starts on.
+ pub(crate) fn save_settings(&self) -> ExportSettings {
+ let previews = self.session.prefs().file_handling.image_previews != photocraft_engine::prefs::Ask::Never;
+ ExportSettings { image_previews: previews, ..ExportSettings::default() }
+ }
+
/// Whether saving the active document to `path` writes a copy. `tiff_layers` is the TIFF
/// Options answer: `Some(false)` discards the layers and saves a copy.
fn saves_copy(&self, path: &str, tiff_layers: Option<bool>) -> Result<bool, String> {
@@ -1263,7 +1274,7 @@ impl PhotocraftApp {
/// pixel (`None`: 32 with an alpha channel or transparency, else 24).
fn write_save(&mut self, path: String, tiff_layers: Option<bool>, tga_bits: Option<photocraft_io::TgaBits>) -> Result<Value, String> {
let copy = self.saves_copy(&path, tiff_layers)?;
- let settings = ExportSettings { tiff_layers: tiff_layers.unwrap_or(ExportSettings::default().tiff_layers), tga_bits, ..Default::default() };
+ let settings = ExportSettings { tiff_layers: tiff_layers.unwrap_or(ExportSettings::default().tiff_layers), tga_bits, ..self.save_settings() };
match self.write_document(path.clone(), &settings, copy)? {
Some((path, warnings)) => Ok(serde_json::json!({"path": path, "warnings": warnings})),
None => Ok(serde_json::json!({"path": path, "warnings": [], "pending": true, "job": self.jobs.last_started.map(|j| j.0)})),
@@ -1368,7 +1379,7 @@ impl PhotocraftApp {
if self.background_jobs
&& let Some(save) = self.services.automation_save.clone()
{
- return match jobs_ui::start_save(self, target.clone(), ExportSettings { tga_bits, ..Default::default() }, false, save, true)? {
+ return match jobs_ui::start_save(self, target.clone(), ExportSettings { tga_bits, ..self.save_settings() }, false, save, true)? {
Some((path, warnings)) => Ok(reply(&path, &warnings)),
None => {
let job = self.jobs.last_started;
@@ -1378,8 +1389,9 @@ impl PhotocraftApp {
}
let state = self.session.active().ok_or("no document")?;
let (doc, revision) = (state.doc.id, state.revision);
+ let settings = ExportSettings { tga_bits, ..self.save_settings() };
let export = self.services.export.as_ref().ok_or("no exporter configured")?;
- let (bytes, warnings) = export(&state.doc, &target, &ExportSettings { tga_bits, ..Default::default() })?;
+ let (bytes, warnings) = export(&state.doc, &target, &settings)?;
let write = self.services.automation_write.as_mut().ok_or("automation write authority is not configured")?;
write(&target, &bytes)?;
self.saved_automation(doc, revision, &target, &warnings, false);
diff --git a/crates/ui-egui/src/save_identity_tests.rs b/crates/ui-egui/src/save_identity_tests.rs
index 9cfc86d50..1aed0fa5b 100644
--- a/crates/ui-egui/src/save_identity_tests.rs
+++ b/crates/ui-egui/src/save_identity_tests.rs
@@ -182,3 +182,25 @@ fn automation_flat_save_is_a_copy() {
assert_eq!((st.doc.name.as_str(), st.path.as_deref()), ("layers.psd", Some("layers.psd")));
assert_eq!(st.saved_revision, st.revision);
}
+
+/// Preferences › File Handling › Image Previews reaches the exporter of Save As, Save and
+/// automation saves: Always and Ask When Saving embed the PSD thumbnail, Never doesn't.
+#[test]
+fn image_previews_preference_reaches_the_exporter() {
+ let seen = Rc::new(RefCell::new(Vec::new()));
+ let mut app = app();
+ let log = seen.clone();
+ app.services.export = Some(Box::new(move |_, _, settings: &ExportSettings| {
+ log.borrow_mut().push(settings.image_previews);
+ Ok((b"out".to_vec(), Vec::new()))
+ }));
+ let ctx = egui::Context::default();
+ for (value, expect) in [("always", true), ("never", false), ("ask", true)] {
+ app.run("prefs.set", json!({"path": "fileHandling.imagePreviews", "value": value})).unwrap();
+ seen.borrow_mut().clear();
+ menus::invoke(&mut app, &ctx, "file.saveAs", json!({"path": format!("{value}.psd")})).unwrap();
+ menus::invoke(&mut app, &ctx, "file.save", json!({})).unwrap();
+ app.save_automation(Some(format!("{value} agent.psd"))).unwrap();
+ assert_eq!(*seen.borrow(), [expect; 3], "{value}");
+ }
+}
diff --git a/crates/ui-egui/src/targa_options_ui.rs b/crates/ui-egui/src/targa_options_ui.rs
index a40ee0f42..afc7f60ba 100644
--- a/crates/ui-egui/src/targa_options_ui.rs
+++ b/crates/ui-egui/src/targa_options_ui.rs
@@ -77,7 +77,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
p.bits = bits;
if ok || ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) {
let Some(p) = app.targa_options.take() else { return };
- let settings = ExportSettings { tga_bits: Some(p.bits), ..Default::default() };
+ let settings = ExportSettings { tga_bits: Some(p.bits), ..app.save_settings() };
let step = serde_json::json!({"path": p.path, "tgaBits": p.bits.bits()});
let written = app.with_document(p.doc, |app| app.write_document(p.path, &settings, p.copy));
if written.is_ok() && p.record {
diff --git a/crates/ui-egui/src/tiff_options_ui.rs b/crates/ui-egui/src/tiff_options_ui.rs
index 260bac152..febd5964c 100644
--- a/crates/ui-egui/src/tiff_options_ui.rs
+++ b/crates/ui-egui/src/tiff_options_ui.rs
@@ -70,7 +70,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
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, ..Default::default() };
+ 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() {
diff --git a/crates/ui-egui/src/view_cmds.rs b/crates/ui-egui/src/view_cmds.rs
index 48420a313..190634cca 100644
--- a/crates/ui-egui/src/view_cmds.rs
+++ b/crates/ui-egui/src/view_cmds.rs
@@ -1173,8 +1173,9 @@ fn save_a_copy(app: &mut PhotocraftApp) -> Result<Value, String> {
if parked {
return Ok(json!({"path": path, "warnings": []}));
}
+ let settings = app.save_settings();
let export = app.services.export.as_ref().ok_or("no exporter configured")?;
- let (bytes, warnings) = export(&doc, &path, &crate::ExportSettings::default())?;
+ let (bytes, warnings) = export(&doc, &path, &settings)?;
let write = app.services.write.as_mut().ok_or("no writer configured")?;
write(&path, &bytes)?;
app.ui.status = format!("Saved a copy as {path}");
diff --git a/docs/scorecard.md b/docs/scorecard.md
index 9374ed74a..098f7539b 100644
--- a/docs/scorecard.md
+++ b/docs/scorecard.md
@@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js
| [Performance](#performance) | 3 | 22 | 22 | 56 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 17 not run, 5 not measurable yet (baseline 2026-10-05) |
| [File compatibility](#file-compatibility) | 6 | 12 | 9 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 236/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 133/256, round trip ≥ 258/256 |
| [Tools](#tools) | 25 | 16 | 2 | |
-| [Workspace and UI](#workspace-and-ui) | 9 | 8 | 6 | settings that do nothing: 32 of 154 (target 0) |
+| [Workspace and UI](#workspace-and-ui) | 9 | 8 | 6 | settings that do nothing: 31 of 154 (target 0) |
| [Type](#type) | 2 | 3 | 4 | |
| [Automation](#automation) | 3 | 2 | 6 | 631 of 631 menu items live (100.0%) |
| [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 28 of 28 crates; panic_hunt present |
@@ -176,9 +176,9 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t
## Workspace and UI
-**Settings that do nothing: 32 of 154** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't.
+**Settings that do nothing: 31 of 154** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't.
-Unread: `general.color_picker`, `general.animated_zoom`, `general.zoom_resizes_windows`, `workspace.auto_collapse_icon_panels`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `workspace.enable_narrow_options_bar`, `file_handling.image_previews`, `file_handling.save_in_background`, `file_handling.ignore_exif_profile_tag`, `file_handling.maximize_psd_compatibility`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.missing_glyph_protection`, `type_.text_engine`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `enhanced_controls.touch_gestures`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`.
+Unread: `general.color_picker`, `general.animated_zoom`, `general.zoom_resizes_windows`, `workspace.auto_collapse_icon_panels`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `workspace.enable_narrow_options_bar`, `file_handling.save_in_background`, `file_handling.ignore_exif_profile_tag`, `file_handling.maximize_psd_compatibility`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.missing_glyph_protection`, `type_.text_engine`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `enhanced_controls.touch_gestures`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`.
| Id | Target | Status | Issue | Note |
|---|---|---|---|---|