Files
photocraft/crates/io/tests/it/psd_thumbnail.rs
T
e4e2607c85 Preview spot inks over the RGB/CMYK composite as an overprint (#10276)
* PSD: a flat file's named extra channels are not its transparency

A PSD without layer records had its first extra channel read as the merged
transparency, so the first spot or alpha channel of a flattened document
vanished and its ink punched a transparent hole in the image (psd-tools
cmyk-alpha-spot.psd, cmyk-spot.psd). When the alpha channel names (1045, or
1006 when 1045 is missing) name every extra channel and the first is not
"Transparency", there is none. The import also reads channel names from
1006 when 1045 is missing, and a spot whose DisplayInfo colour space is
unknown takes its ink from the Alternate Spot Colors (1067).

* channel_map: read 1067 records with as_chunks

* Preview spot inks over the RGB/CMYK composite as an overprint

Visible spot channels of RGB and CMYK documents print over the canvas
composite with the Multichannel ink formula, in Channels panel order,
instead of a tint; alpha channels and Quick Mask still tint over them.
Spot channels open visible, and the PSD thumbnail (1036) prints them.
flatten, export and the merged image stay free of spot inks. Ink
colours go through the document's CMYK profile, and into an RGB
document's own profile.

Refs #10249

* channel_view: test solidity over a gray picture

* Thumbnail: matte only inked pixels; test the merged planes directly

Review feedback on #10276: pixels without spot ink keep their
transparency in the thumbnail buffer, and the thumbnail test checks the
saved merged process planes instead of a re-imported flatten.

* Thumbnail spot inks: sample big boxes on a 4x4 grid

Review feedback on #10276: reducing each spot channel no longer scans the
whole document; a thumbnail pixel averages at most 4x4 samples, so a huge
document costs about h x 4 row reads per spot.

* Spot overlay: composite a proxy for the first draw of big documents

The overprint needs the composite under the inks. Rendering the full-resolution
composite to sample every factor-th pixel cost ~1 s for a 24 MP CMYK document.
A proxy document picks the same pixels (nearest-neighbour downsample) for about
1/factor² of the work. Documents with layer effects, vector masks or feathered
masks keep the full-resolution path.

* Proxy: downsample rows in parallel; the overlay proxy leaves out unused channels

The spot overlay's proxy shrank the spot channels, selection and Quick Mask that an
RGB or CMYK composite never reads: about two thirds of its cost. downsample now
reads its rows in parallel, 64 at a time.

* Spot overlay proxy: keep the full-resolution composite under uncached pattern fills

A pattern fill renders its tiles at their own size on a proxy, so the proxy would
sample other pattern pixels. Unless the fill's matching cache is shrunk with the
proxy, use the full-resolution composite.

* Spot overlay proxy: hidden layers don't decide the composite path

Hidden layers and the contents of hidden groups are not composited, so a hidden
feathered mask or pattern fill no longer forces the full-resolution composite
(the same rule as proxy_faithful).

* Update crates/compose/src/multichannel.rs

Co-authored-by: aiongg <67543387+aiongg@users.noreply.github.com>

* Spot overlay: only inked pixels replace the canvas; inks through the display transform

Where every visible spot is 0 the overlay stays transparent, so the normal
canvas (display LUT, proofing, 32-bit preview, full resolution) shows; an
empty spot renders no composite. Printed pixels go through the canvas
display transform (sRGB encoding of linear composites, monitor profile,
Proof Colors), keyed into the texture. Ink colours come from one InkSpace
per render: the document's profiles are parsed once, not per spot per
damage rect.

* test(compose): cover hidden spot preview and document approximation

* fix(ui-egui): preserve solo spot channel display when process colours are hidden

Clicking a spot channel row in the Channels panel targets the channel alone
and hides all process colour channels (`vis == 0`). Overprint inks were
previously extracted from `overlays` before checking `vis == 0`, leaving
`overlays` empty and causing the solo channel view to fall back to an active
layer mask (or return `None` if the layer had no mask).

Keep the spot channel in `overlays` so `vis == 0` can select it as the solo
grayscale picture, separating overprint inks only when process colours are
visible (`vis > 0`).

Adds a regression test targeting an existing spot channel in RGB and CMYK on
an unmasked layer and editing it.

* channel_view: document the spot overprint preview as an approximation

* test(ui-egui): solo spot channel wins over an unrelated layer mask

* channel_view: sRGB spot inks, lazy display transform, inked-area composite

Review fixes for the spot overprint preview:

- RGB spot colours are sRGB, like the CMYK, Lab and gray ones: InkSpace now
  converts them into an RGB document's own profile too. In a linear (EXR/HDR),
  Adobe RGB or ProPhoto document an RGB ink showed the wrong colour (brightened
  in a linear one once the canvas sRGB-encoded it).
- The display transform is looked up only when the view is redrawn and inks
  are shown, not every frame before the cache check; display_transform_for
  borrows the proof state (proof_ref) instead of cloning a default CMYK profile.
- Visible spot channels without ink, with nothing else shown, draw no texture:
  render returns None and ensure remembers it, instead of uploading an
  all-transparent document-sized texture. A damage re-render that finds nothing
  clears its rect, so erased ink never lingers.
- Printing a few inked pixels composites only their bounding box when that is
  cheaper than the whole (proxy) composite, and a cached composite is borrowed
  instead of copied.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: aiongg <67543387+aiongg@users.noreply.github.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 23:34:12 +01:00

180 lines
8.9 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 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:?}");
}
/// The thumbnail shows the document's spot inks over its composite, as the reference editor's
/// does (psd-tools cmyk-alpha-spot.psd: its spot-only text is in the preview, not in the merged
/// image).
#[test]
fn spot_inks_print_in_the_thumbnail() {
for mode in [ColorMode::Rgb, ColorMode::Cmyk] {
let mut d = doc(mode, SampleType::U8, 64, 32, [1.0, 1.0, 1.0, 1.0], 1.0);
let fmt = photocraft_color::PixelFormat::new(ColorMode::Grayscale, SampleType::U8, false);
let mut ink = photocraft_raster::Surface::new(fmt);
ink.fill_rect(photocraft_geom::Rect::new(0, 0, 32, 32), &[1.0]);
let teal = photocraft_color::Color::rgb(0.0, 157.0 / 255.0, 165.0 / 255.0);
d.channels.push(photocraft_doc::AlphaChannel { spot: Some((teal, 0.0)), ..photocraft_doc::AlphaChannel::new("light teal", ink) });
let bytes = export(&d, "x.psd", &ExportOptions::default()).unwrap().bytes;
let (w, _, px) = thumbnail(&bytes).unwrap();
let (inked, bare) = (px[(16 * w + 8) as usize], px[(16 * w + 56) as usize]);
assert!(near(inked, [0.0, 157.0 / 255.0, 165.0 / 255.0], 0.06), "{mode:?} {inked:?}");
assert!(near(bare, [1.0, 1.0, 1.0], 0.04), "{mode:?} {bare:?}");
// The merged process planes stay free of the ink: white (no CMYK ink is stored as 255 too).
let merged = PsdFile::from_bytes(&bytes).unwrap().decode_merged().unwrap();
let plane = 64 * 32;
for c in 0..mode.color_channels() {
assert_eq!(merged[c * plane + 16 * 64 + 8], 255, "{mode:?} merged channel {c}");
}
}
}