From 4705fc59805c3a848a0d4a24781514cb875db5bb Mon Sep 17 00:00:00 2001 From: Nigel Ihza Firdausy <106657905+Ni-zav@users.noreply.github.com> Date: Mon, 12 Oct 2026 18:01:20 +0700 Subject: [PATCH 01/24] feat(io): open Krita .kra composites as editable raster documents (#3692) (#3700) * feat(io): open Krita .kra composites as editable raster documents (#3692) * cargo fmt Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Brandon Thomas Co-authored-by: Claude Opus 5.5 --- apps/photocraft/src/services.rs | 7 ++- crates/io/src/kra.rs | 108 ++++++++++++++++++++++++++++++++ crates/io/src/lib.rs | 10 +++ 3 files changed, 122 insertions(+), 3 deletions(-) create mode 100644 crates/io/src/kra.rs diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index 8342baa257..0b1a366a69 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -20,9 +20,9 @@ mod recovery_tests; /// Photoshop brushes (.abr), gradients (.grd), swatches (.aco, .ase) and keyboard shortcut sets /// (.kys), which go to the preset libraries and Edit › Keyboard Shortcuts. const OPEN_EXTS: &[&str] = &[ - "pcraft", "pdn", "ora", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", "pbm", "pgm", - "ppm", "pam", "pfm", "fits", "fit", "fts", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", - "svg", "svgz", "aco", "ase", "kys", "af", "afdesign", "afphoto", "afpub", + "pcraft", "pdn", "ora", "kra", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", "pbm", + "pgm", "ppm", "pam", "pfm", "fits", "fit", "fts", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", + "grd", "svg", "svgz", "aco", "ase", "kys", "af", "afdesign", "afphoto", "afpub", ]; const SVG_EXTS: &[&str] = &["svg", "svgz"]; @@ -43,6 +43,7 @@ fn open_filters() -> Vec<(&'static str, Vec)> { ("All Formats", open_filter_extensions(OPEN_EXTS)), ("PhotoCraft", open_filter_extensions(&["pcraft"])), ("OpenRaster", open_filter_extensions(&["ora"])), + ("Krita", open_filter_extensions(&["kra"])), ("SVG", open_filter_extensions(SVG_EXTS)), ] } diff --git a/crates/io/src/kra.rs b/crates/io/src/kra.rs new file mode 100644 index 0000000000..a3af8b119c --- /dev/null +++ b/crates/io/src/kra.rs @@ -0,0 +1,108 @@ +//! Krita .kra import: the merged PNG is an editable raster layer, not a replacement +//! for Krita's native layer tree. Never write this document back to the .kra source. +//! The ZIP reader checks entry bounds, sizes and CRC before the PNG decoder runs. + +use photocraft_codecs::{self as codecs, DecodeOptions, Format}; +use photocraft_format::zip::ZipReader; +use photocraft_raster::Interrupt; + +use crate::{ImportResult, IoError}; + +const MIMETYPE: &[u8] = b"application/x-krita"; +const MAX_ENTRY: usize = 512 << 20; +const MAX_PIXELS_BYTES: u64 = 1 << 30; + +fn invalid(message: impl Into) -> IoError { + IoError::Kra(message.into()) +} + +/// Krita writes its mimetype as the first, uncompressed ZIP entry. +pub(crate) fn is_kra(bytes: &[u8]) -> bool { + crate::ora::zip_mimetype(bytes).is_some_and(|mime| mime.trim_ascii() == MIMETYPE) +} + +/// Import Krita's official merged preview as a flattened, editable PhotoCraft document. +/// Do not silently pretend this imported a layered or lossless Krita document. +pub(crate) fn import(name: &str, bytes: &[u8], ctl: &Interrupt<'_>) -> Result { + ctl.check().map_err(|_| IoError::Cancelled)?; + let archive = ZipReader::new(bytes).map_err(|e| invalid(e.to_string()))?; + let mime = archive.read_by_name("mimetype", 256).map_err(|e| invalid(e.to_string()))?; + if mime.trim_ascii() != MIMETYPE { + return Err(invalid("the archive's mimetype is not application/x-krita")); + } + ctl.progress(0.10); + let merged = archive.read_by_name("mergedimage.png", MAX_ENTRY).map_err(|e| invalid(format!("mergedimage.png: {e}")))?; + if codecs::detect(&merged) != Some(Format::Png) { + return Err(invalid("mergedimage.png is not a PNG image")); + } + ctl.check().map_err(|_| IoError::Cancelled)?; + let mut opts = DecodeOptions::default(); + opts.limits.max_width = crate::ora::MAX_SIDE; + opts.limits.max_height = crate::ora::MAX_SIDE; + opts.limits.max_alloc = MAX_PIXELS_BYTES; + let image = codecs::decode_with(&merged, &opts).map_err(|e| invalid(format!("mergedimage.png: {e}")))?; + ctl.check().map_err(|_| IoError::Cancelled)?; + let mut result = crate::flat::image_to_document(name, &image)?; + result.source_read_only = true; + result.warnings.push("Krita layers, masks and editable document structure were not imported; only mergedimage.png is available".into()); + Ok(result) +} + +#[cfg(test)] +mod tests { + use super::*; + use photocraft_codecs::{ChannelLayout, EncodeOptions, Image, SampleType}; + use photocraft_format::zip::ZipWriter; + + fn png() -> Vec { + let image = Image::from_raw(2, 1, ChannelLayout::Rgba, SampleType::U8, vec![255, 0, 0, 255, 0, 0, 255, 128]).unwrap(); + codecs::encode(&image, Format::Png, &EncodeOptions::default()).unwrap() + } + + fn archive(mime: &[u8], with_merged: bool) -> Vec { + let mut zip = ZipWriter::new(); + zip.add("mimetype", mime).unwrap(); + zip.add("maindoc.xml", b"").unwrap(); + if with_merged { + zip.add("mergedimage.png", &png()).unwrap(); + } + zip.finish().unwrap() + } + + #[test] + fn imports_krita_composite_without_claiming_to_preserve_layers() { + let bytes = archive(MIMETYPE, true); + assert!(is_kra(&bytes)); + // The mimetype is authoritative even without a .kra extension. + for name in ["scene.kra", "download"] { + let r = crate::import(name, &bytes).unwrap(); + assert_eq!((r.document.size.width, r.document.size.height), (2, 1)); + assert_eq!(r.document.name, name); + assert_eq!(r.document.layers.len(), 1); + assert_eq!(r.document.layers[0].name, "Layer 0", "alpha-bearing composite"); + let pixels = r.document.layers[0].surface().unwrap(); + assert!(pixels.rgba(0, 0)[0] > 0.99); + assert!(pixels.rgba(1, 0)[2] > 0.99); + assert!((pixels.rgba(1, 0)[3] - 128.0 / 255.0).abs() < 0.01); + assert!(r.source_read_only, ".kra must not be overwritten by a flat save"); + assert!(!r.preview_only, "the flattened image is editable"); + assert!(r.warnings.iter().any(|w| w.contains("layers") && w.contains("not imported"))); + } + } + + #[test] + fn malformed_or_non_krita_archives_do_not_open_as_krita() { + let wrong = archive(b"image/openraster", true); + assert!(!is_kra(&wrong)); + assert!(import("wrong.kra", &wrong, &Interrupt::NONE).is_err()); + assert!(import("missing.kra", &archive(MIMETYPE, false), &Interrupt::NONE).is_err()); + assert!(import("broken.kra", b"not a zip", &Interrupt::NONE).is_err()); + } + + #[test] + fn a_png_with_a_misleading_kra_extension_remains_a_png() { + let r = crate::import("renamed.kra", &png()).unwrap(); + assert_eq!(r.document.size.width, 2); + assert!(!r.source_read_only, "a real PNG must not be treated as a Krita source"); + } +} diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 9ea361994b..0a9acbc19a 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -18,6 +18,7 @@ //! * Paint.NET PDN3 documents open as editable bitmap layers (import only). //! * OpenRaster (`.ora`) documents open and save with their layers, groups, blend modes, //! opacity and visibility; see `ora`. +//! * Krita (`.kra`) documents open as their merged composite; source layers are not imported. //! * Affinity documents (`.af`, `.afdesign`, `.afphoto`, `.afpub`) open natively //! with no source save path, what isn't imported listed in the warnings; a file //! whose native data can't be read opens as its embedded preview; see `affinity`. @@ -41,6 +42,7 @@ pub mod effects_map; pub mod exr_parts; mod flat; mod gradient_bake; +mod kra; pub mod linked; mod multichannel_map; mod ora; @@ -80,6 +82,9 @@ pub enum IoError { /// OpenRaster read failure. #[error("OpenRaster: {0}")] Ora(String), + /// Krita document decode failure. + #[error("Krita: {0}")] + Kra(String), /// PSD parse/write failure. #[error("PSD: {0}")] Psd(#[from] PsdError), @@ -268,6 +273,11 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, m if ora::is_ora(bytes) || has_extension(name, "ora") { return ora::import(name, bytes, ctl); } + // Krita files are ZIP containers carrying a merged PNG. A recognized raster signature + // still wins over a misleading .kra suffix (as with SVG imports). + if kra::is_kra(bytes) || (has_extension(name, "kra") && photocraft_codecs::detect(bytes).is_none()) { + return kra::import(name, bytes, ctl); + } if has_extension(name, "pdn") || bytes.starts_with(b"PDN3") { return pdn::import(name, bytes, ctl); } From 6547ca0b8459ef37e1dfb373cc00a81740ed74a4 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Mon, 12 Oct 2026 07:02:10 -0400 Subject: [PATCH 02/24] fix(psd): Multichannel alpha channels stay alpha; a save keeps resources and global blocks (#4031) - DisplayInfo kinds 0/1 (selected / masked areas) now import as alpha channels instead of black spot inks; a Multichannel composite still prints them as black ink, so the look is unchanged. - Saving a Multichannel PSD writes global light, grid and guides, saved / work / clipping paths, EXIF and every other imported resource (print settings, IPTC, layer-id seed, alpha ids while they match the channels), except the ones that only describe layers, plus the document-level tagged blocks (4-byte padded). Path writing and global-block padding are shared with the layered writer. Co-authored-by: Claude Opus 5.5 --- crates/compose/src/multichannel.rs | 15 ++- crates/io/src/channel_map.rs | 10 +- crates/io/src/multichannel_map.rs | 60 ++++++++++-- crates/io/src/psd_export.rs | 127 ++++++++++++++------------ crates/io/tests/multichannel.rs | 142 +++++++++++++++++++++++++++++ 5 files changed, 284 insertions(+), 70 deletions(-) create mode 100644 crates/io/tests/multichannel.rs diff --git a/crates/compose/src/multichannel.rs b/crates/compose/src/multichannel.rs index 63bec04bf6..88c0b2f359 100644 --- a/crates/compose/src/multichannel.rs +++ b/crates/compose/src/multichannel.rs @@ -3,7 +3,8 @@ //! Ink density `v` (the channel value, 1 = solid) of an ink with display colour `c` and solidity //! `s` turns the colour underneath `p` into `(1 − s·v)·p·(1 − v + v·c) + s·v·c`: transparent inks //! (solidity 0) multiply like overprinted process inks, opaque ones cover what is below, which is -//! how Photoshop previews spot channels. +//! how Photoshop previews spot channels. An alpha-type channel of a Multichannel document +//! (selected / masked areas) still prints, as a transparent black ink, like Photoshop shows it. use photocraft_doc::Document; use photocraft_geom::Rect; @@ -15,7 +16,7 @@ pub fn inks(doc: &Document, rect: Rect) -> Buffer { let mut buf = Buffer::filled(rect, [1.0, 1.0, 1.0, 1.0]); let mut vals = Vec::new(); for ch in &doc.channels { - let Some((ink, solidity)) = ch.spot else { continue }; + let (ink, solidity) = ch.spot.unwrap_or((photocraft_color::Color::BLACK, 0.0)); if ch.surface.content_bounds().intersect(&rect).is_empty() { continue; } @@ -65,7 +66,15 @@ mod tests { assert_eq!(r.px[1], [0.0, 1.0, 1.0, 1.0]); assert_eq!(r.px[2], [0.0, 0.0, 1.0, 1.0]); assert_eq!(r.px[3], [1.0, 0.0, 1.0, 1.0]); - // Alpha channels and other modes are not inks. + // An alpha-type channel prints as a black ink. + let mut k = Surface::new(fmt); + k.write_region(Rect::new(0, 0, 4, 1), &[0.5, 0.0, 0.0, 0.0]); + doc.channels.push(AlphaChannel::new("Alpha", k)); + let r = crate::flatten(&doc); + // 0.5 is stored as 128/255 in an 8-bit channel: within one 8-bit step. + assert!((r.px[0][0] - 0.5).abs() <= 1.0 / 255.0 && (r.px[0][1] - 0.5).abs() <= 1.0 / 255.0, "{:?}", r.px[0]); + assert_eq!(r.px[1], [0.0, 1.0, 1.0, 1.0]); + // Other modes have no inks. doc.mode = ColorMode::Rgb; assert_eq!(crate::flatten(&doc).px[1][3], 0.0); } diff --git a/crates/io/src/channel_map.rs b/crates/io/src/channel_map.rs index d3630bf35a..bafde26f30 100644 --- a/crates/io/src/channel_map.rs +++ b/crates/io/src/channel_map.rs @@ -1,10 +1,10 @@ //! Alpha / spot channel options <-> PSD `DisplayInfo` image resources (1077, and the older 1007). //! //! Layout (Adobe PSD spec, "DisplayInfo"): resource 1077 starts with a 4-byte version (1), then -//! one 14-byte record per extra channel: colour space (u16), four u16 colour components, opacity -//! (u16, 0..100), kind (u8: 0 = colour indicates selected areas, 1 = masked ("protected") areas, -//! 2 = spot channel) and one padding byte. Resource 1007 has the same records without the -//! version and without the spot kind. +//! one 13-byte record per extra channel: colour space (u16), four u16 colour components, opacity +//! (u16, 0..100) and kind (u8: 0 = colour indicates selected areas, 1 = masked ("protected") +//! areas, 2 = spot channel). Resource 1007 has the same records without the version and the spot +//! kind, each followed by a padding byte (14 bytes). use photocraft_color::{Color, ColorMode}; use photocraft_doc::{AlphaChannel, ColorIndicates}; @@ -59,6 +59,8 @@ pub(crate) fn apply_display_info(data: &[u8], versioned: bool, skip: usize, chan match rec[12] { 2 => c.spot = Some((color, opacity)), k => { + // An alpha channel, not an ink (a Multichannel import starts every channel as one). + c.spot = None; c.color = color; c.opacity = opacity; c.indicates = if k == 0 { ColorIndicates::SelectedAreas } else { ColorIndicates::MaskedAreas }; diff --git a/crates/io/src/multichannel_map.rs b/crates/io/src/multichannel_map.rs index d20a70efcd..db31e743ef 100644 --- a/crates/io/src/multichannel_map.rs +++ b/crates/io/src/multichannel_map.rs @@ -9,13 +9,21 @@ use photocraft_color::{Color, ColorMode, PixelFormat, SampleType}; use photocraft_doc::{AlphaChannel, Document}; use photocraft_geom::Rect; -use photocraft_psd::file::LayerInfoPlacement; +use photocraft_psd::file::{GlobalLayerMask, LayerInfoPlacement}; use photocraft_psd::resources::{ImageResource, ResolutionInfo, ids, version_info_resource}; -use photocraft_psd::{ColorMode as PsdMode, Compression, Header, ImageData, PsdFile}; +use photocraft_psd::{ColorMode as PsdMode, Compression, Header, ImageData, PsdFile, TaggedBlock}; use photocraft_raster::Surface; use crate::pixels::{encode_be, psd_depth}; +/// Grid and guides. +const GRID_AND_GUIDES: u16 = 1032; +/// Alpha identifiers: one u32 per extra channel. +const ALPHA_IDENTIFIERS: u16 = 1053; +/// Resources that only describe layers: target layer (1024), layer groups (1026), layer +/// selection ids (1069) and layer groups enabled (1072). A Multichannel document has no layers. +const LAYER_ONLY_RESOURCES: [u16; 4] = [ids::LAYER_STATE, ids::LAYER_GROUP_INFO, 1069, 1072]; + /// Value of sample `i` of a big-endian plane. fn decode(plane: &[u8], i: usize, s: SampleType) -> f32 { match s { @@ -44,7 +52,8 @@ pub(crate) fn import(file: &PsdFile, all: &[u8], doc: &mut Document, names: &[St s.write_region(canvas, &vals); s.prune(); let name = names.get(k).cloned().filter(|s| !s.is_empty()).unwrap_or_else(|| format!("Channel {}", k + 1)); - // Without DisplayInfo the channels print in black, as Photoshop shows them. + // Without DisplayInfo the channels print in black, as Photoshop shows them. DisplayInfo + // turns alpha-type channels (selected / masked areas) back into alpha channels. doc.channels.push(AlphaChannel { spot: Some((Color::BLACK, 0.0)), ..AlphaChannel::new(name, s) }); } if let Some(r) = file.resource(crate::channel_map::DISPLAY_INFO) { @@ -97,17 +106,54 @@ pub(crate) fn document_to_psd(doc: &Document, force_psb: bool) -> (PsdFile, Vec< let image_data = ImageData::encode(Compression::Rle, &planes, &header) .or_else(|_| ImageData::encode(Compression::Raw, &planes, &header)) .unwrap_or(ImageData { compression: Compression::Raw, data: planes }); - let mut resources = vec![ImageResource::new(ids::RESOLUTION_INFO, ResolutionInfo::from_dpi(f64::from(doc.resolution_dpi)).to_bytes())]; + let mut resources = vec![ + ImageResource::new(ids::RESOLUTION_INFO, ResolutionInfo::from_dpi(f64::from(doc.resolution_dpi)).to_bytes()), + ImageResource::new(ids::GLOBAL_ANGLE, (doc.global_light.angle.round() as i32).to_be_bytes().to_vec()), + ImageResource::new(ids::GLOBAL_ALTITUDE, (doc.global_light.altitude.round() as i32).to_be_bytes().to_vec()), + ]; + // Grid and guides: Photoshop writes it in every file, guides or not. + resources.push(ImageResource::new(GRID_AND_GUIDES, crate::psd_export::guides_resource(doc))); if !channels.is_empty() { let names: Vec<&str> = channels.iter().map(|c| c.name.as_str()).collect(); 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.extend(crate::psd_export::path_resources(doc, &mut warnings)); + // The XMP and EXIF resolution follow the ResolutionInfo resource, so no copy contradicts it. + let ppi = Some((doc.resolution_dpi, doc.resolution_dpi)).filter(|d| d.0 > 0.0); if let Some(x) = &doc.metadata.xmp { - resources.push(ImageResource::new(ids::XMP, x.as_bytes().to_vec())); + resources.push(ImageResource::new(ids::XMP, photocraft_codecs::export_xmp(x, ppi).as_bytes().to_vec())); + } + if let Some(e) = &doc.metadata.exif { + resources.push(ImageResource::new(ids::EXIF, photocraft_codecs::export_exif(e, ppi).into_owned())); + } + // Every other imported resource (print settings, IPTC, the layer-id seed, ...), except the + // ones that only describe layers and any already written above. + let written: Vec = resources.iter().map(|r| r.id).collect(); + for (id, name, data) in &doc.metadata.psd_resources { + if LAYER_ONLY_RESOURCES.contains(id) || written.contains(id) || !crate::psd_export::keep_imported_resource(doc, *id, data) { + continue; + } + // Alpha identifiers: one u32 per channel, only while they still match the channels. + if *id == ALPHA_IDENTIFIERS && data.len() != channels.len().saturating_mul(4) { + continue; + } + let mut r = ImageResource::new(*id, data.to_vec()); + r.name = crate::psd_export::legacy_name(name); + resources.push(r); + } + if let Some(data) = crate::annotations_map::fresh_scale_resource(doc) { + resources.push(ImageResource::new(crate::annotations_map::MEASUREMENT_SCALE, data)); } resources.push(version_info_resource(true)); + // Document-level tagged blocks (patterns, notes, ...) are valid without a layer section; a + // kept layer block would describe layers the document doesn't have. + let global_blocks: Vec = crate::annotations_map::export_blocks(doc, crate::pattern_map::export_global_blocks(doc)) + .into_iter() + .filter(|(_, key, _)| !matches!(key, b"Layr" | b"Lr16" | b"Lr32")) + .map(|(sig, key, data)| crate::psd_export::global_block(sig, key, &data)) + .collect(); let color_mode_data = photocraft_psd::hdr::color_mode_data_for_depth(header.depth); let file = PsdFile { header, @@ -115,8 +161,8 @@ pub(crate) fn document_to_psd(doc: &Document, force_psb: bool) -> (PsdFile, Vec< resources, layer_info: None, layer_info_placement: LayerInfoPlacement::Section, - global_layer_mask: None, - global_blocks: Vec::new(), + global_layer_mask: (!global_blocks.is_empty()).then(GlobalLayerMask::default), + global_blocks, layer_mask_trailing: Vec::new(), image_data, }; diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index 1c43a36457..3d8d637eb4 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -1053,7 +1053,7 @@ fn effects_unchanged(l: &Layer) -> Option { Some(m == l.effects.enabled && items == l.effects.items) } -fn legacy_name(s: &str) -> Vec { +pub(crate) fn legacy_name(s: &str) -> Vec { s.chars().map(|c| if c.is_ascii() && !c.is_ascii_control() { c as u8 } else { b'?' }).take(255).collect() } @@ -1079,7 +1079,7 @@ pub(crate) fn pascal_names_resource(names: &[&str]) -> Vec { v } -fn guides_resource(doc: &Document) -> Vec { +pub(crate) fn guides_resource(doc: &Document) -> Vec { let mut v = Vec::new(); v.extend_from_slice(&1u32.to_be_bytes()); v.extend_from_slice(&576u32.to_be_bytes()); @@ -1095,6 +1095,72 @@ fn guides_resource(doc: &Document) -> Vec { v } +/// Path resources: saved paths (2000+), the work path (1025) and the clipping path name (2999), +/// the last only when the imported one doesn't already name the document's clipping path. +pub(crate) fn path_resources(doc: &Document, warnings: &mut Vec) -> Vec { + use crate::vector_map::{CLIPPING_PATH, WORK_PATH, path_from_resource, path_to_records}; + let mut out = Vec::new(); + let (w, h) = (doc.size.width, doc.size.height); + let max = (*crate::vector_map::SAVED_PATHS.end() - *crate::vector_map::SAVED_PATHS.start() + 1) as usize; + if doc.paths.len() > max { + warnings.push(format!("only {max} saved paths fit in PSD; the rest were dropped")); + } + for (i, p) in doc.paths.iter().take(max).enumerate() { + let data = match &p.psd_raw { + Some(r) if path_from_resource(r, w, h).as_ref() == Some(&p.path) => r.to_vec(), + _ => path_to_records(&p.path, w, h).to_bytes(), + }; + let mut r = ImageResource::new(crate::vector_map::SAVED_PATHS.start() + i as u16, data); + r.name = legacy_name(&p.name); + out.push(r); + } + if let Some(wp) = &doc.work_path { + out.push(ImageResource::new(WORK_PATH, path_to_records(wp, w, h).to_bytes())); + } + let raw_clip = doc.metadata.psd_resources.iter().find(|(id, _, _)| *id == CLIPPING_PATH); + let raw_name = raw_clip.map(|(_, _, d)| { + let n = usize::from(d.first().copied().unwrap_or(0)); + d.get(1..1 + n).map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default() + }); + if let Some(c) = &doc.clipping_path + && raw_name.as_deref() != Some(c.name.as_str()) + { + // Pascal name, then flatness as 16.16 fixed (best effort; see vector_map docs). + let mut data = vec![0u8]; + let name = legacy_name(&c.name); + data[0] = name.len() as u8; + data.extend_from_slice(&name); + data.extend_from_slice(&((c.flatness.max(0.0) * 65536.0) as u32).to_be_bytes()); + out.push(ImageResource::new(CLIPPING_PATH, data)); + } + out +} + +/// Whether an imported (unmodelled) resource still describes the document and is written back. +pub(crate) fn keep_imported_resource(doc: &Document, id: u16, data: &[u8]) -> bool { + // Measurement scale / count resources: only while they still describe the document. + if !crate::annotations_map::keep_resource(doc, id) { + return false; + } + // A preserved clipping-path resource is only valid while it names the current one. + if id == crate::vector_map::CLIPPING_PATH { + let n = usize::from(data.first().copied().unwrap_or(0)); + let raw_name = data.get(1..1 + n).map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default(); + return doc.clipping_path.as_ref().is_some_and(|c| c.name == raw_name); + } + true +} + +/// A document-level (global) tagged block. Photoshop pads these to a multiple of 4, and readers +/// such as psd-tools step to the next block that way: an even pad after `CAI ` (77 bytes) +/// misaligned every block after it (#200). +pub(crate) fn global_block(signature: [u8; 4], key: [u8; 4], data: &[u8]) -> TaggedBlock { + let mut tb = TaggedBlock::new(key, data.to_vec()); + tb.signature = signature; + tb.padding = Some(vec![0; (4 - data.len() % 4) % 4]); + tb +} + fn cmyk_of(fmt: &PixelFormat) -> bool { fmt.mode == ColorMode::Cmyk } @@ -1467,43 +1533,7 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, c data.push(0); resources.push(ImageResource::new(crate::channel_map::QUICK_MASK_INFO, data)); } - // Paths: saved paths (2000+), the work path (1025), the clipping path name (2999). - { - use crate::vector_map::{CLIPPING_PATH, WORK_PATH, path_from_resource, path_to_records}; - let (w, h) = (doc.size.width, doc.size.height); - let max = (*crate::vector_map::SAVED_PATHS.end() - *crate::vector_map::SAVED_PATHS.start() + 1) as usize; - if doc.paths.len() > max { - ex.warnings.push(format!("only {max} saved paths fit in PSD; the rest were dropped")); - } - for (i, p) in doc.paths.iter().take(max).enumerate() { - let data = match &p.psd_raw { - Some(r) if path_from_resource(r, w, h).as_ref() == Some(&p.path) => r.to_vec(), - _ => path_to_records(&p.path, w, h).to_bytes(), - }; - let mut r = ImageResource::new(crate::vector_map::SAVED_PATHS.start() + i as u16, data); - r.name = legacy_name(&p.name); - resources.push(r); - } - if let Some(wp) = &doc.work_path { - resources.push(ImageResource::new(WORK_PATH, path_to_records(wp, w, h).to_bytes())); - } - let raw_clip = doc.metadata.psd_resources.iter().find(|(id, _, _)| *id == CLIPPING_PATH); - let raw_name = raw_clip.map(|(_, _, d)| { - let n = usize::from(d.first().copied().unwrap_or(0)); - d.get(1..1 + n).map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default() - }); - if let Some(c) = &doc.clipping_path - && raw_name.as_deref() != Some(c.name.as_str()) - { - // Pascal name, then flatness as 16.16 fixed (best effort; see vector_map docs). - let mut data = vec![0u8]; - let name = legacy_name(&c.name); - data[0] = name.len() as u8; - data.extend_from_slice(&name); - data.extend_from_slice(&((c.flatness.max(0.0) * 65536.0) as u32).to_be_bytes()); - resources.push(ImageResource::new(CLIPPING_PATH, data)); - } - } + resources.extend(path_resources(doc, &mut ex.warnings)); if let Some(groups) = link_group_resource(&doc.layers) { resources.push(ImageResource::new(ids::LAYER_GROUP_INFO, groups)); } @@ -1548,13 +1578,7 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, c if !ex.records.is_empty() && matches!(&key, b"Lr16" | b"Lr32" | b"Layr") { continue; } - let mut tb = TaggedBlock::new(key, data.to_vec()); - tb.signature = sig; - // Photoshop pads document-level (global) blocks to a multiple of 4, and readers such as - // psd-tools step to the next block that way: an even pad after `CAI ` (77 bytes) - // misaligned every block after it (#200). - tb.padding = Some(vec![0; (4 - data.len() % 4) % 4]); - global_blocks.push(tb); + global_blocks.push(global_block(sig, key, &data)); } if let Some(txt2) = txt2 { let mut tb = TaggedBlock::new(*b"Txt2", txt2.clone()); @@ -1576,18 +1600,9 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, c if *id == crate::slices_map::SLICES && slices_resource.is_some() { continue; } - // Measurement scale / count resources: only while they still describe the document. - if !crate::annotations_map::keep_resource(doc, *id) { + if !keep_imported_resource(doc, *id, data) { continue; } - // A preserved clipping-path resource is only valid while it names the current one. - if *id == crate::vector_map::CLIPPING_PATH { - let n = usize::from(data.first().copied().unwrap_or(0)); - let raw_name = data.get(1..1 + n).map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default(); - if doc.clipping_path.as_ref().is_none_or(|c| c.name != raw_name) { - continue; - } - } let mut r = ImageResource::new(*id, data.to_vec()); r.name = legacy_name(name); resources.push(r); diff --git a/crates/io/tests/multichannel.rs b/crates/io/tests/multichannel.rs new file mode 100644 index 0000000000..d6016070d1 --- /dev/null +++ b/crates/io/tests/multichannel.rs @@ -0,0 +1,142 @@ +//! Multichannel PSDs: alpha-type channels and the document's resources and global blocks survive +//! an import → export → import round trip. + +use photocraft_doc::{ColorIndicates, Knot, NamedPath, Path, PathOp, Subpath}; +use photocraft_io::*; +use photocraft_psd::resources::ImageResource; +use photocraft_psd::{ColorMode, Compression, PsdFile, TaggedBlock, Version, testgen}; + +/// DisplayInfo (1077) record: RGB colour, opacity (0..100) and kind (0/1 alpha, 2 spot). +fn display_record(out: &mut Vec, rgb: [u16; 3], opacity: u16, kind: u8) { + out.extend_from_slice(&0u16.to_be_bytes()); + for v in [rgb[0], rgb[1], rgb[2], 0] { + out.extend_from_slice(&v.to_be_bytes()); + } + out.extend_from_slice(&opacity.to_be_bytes()); + out.push(kind); +} + +/// A two-channel Multichannel file: a cyan spot ink and an alpha channel (masked areas, red 50 %). +fn file(depth: u16) -> PsdFile { + let mut f = testgen::merged_only(Version::Psd, ColorMode::Multichannel, depth, Compression::Rle, 9, 5); + let mut info = 1u32.to_be_bytes().to_vec(); + display_record(&mut info, [0, 65535, 65535], 0, 2); + display_record(&mut info, [65535, 0, 0], 50, 1); + f.resources.push(ImageResource::new(1077, info)); + f +} + +fn roundtrip(d: &photocraft_doc::Document) -> (PsdFile, photocraft_doc::Document) { + let out = export(d, "x.psd", &ExportOptions::default()).unwrap(); + let back = PsdFile::from_bytes(&out.bytes).unwrap(); + let (doc, _) = psd_to_document(&back); + (back, doc) +} + +#[test] +fn alpha_type_channels_import_as_alpha_and_round_trip() { + for depth in [8, 16] { + let f = file(depth); + let (d, _) = psd_to_document(&f); + assert_eq!(d.channels.len(), 2); + assert_eq!(d.channels[0].spot.map(|(c, _)| c.to_rgb()), Some([0.0, 1.0, 1.0])); + let a = &d.channels[1]; + assert_eq!(a.spot, None, "an alpha-type channel is not a spot ink ({depth}-bit)"); + assert_eq!(a.color.to_rgb(), [1.0, 0.0, 0.0]); + assert!((a.opacity - 0.5).abs() < 1e-6); + assert_eq!(a.indicates, ColorIndicates::MaskedAreas); + + // It still prints as black ink, so the composite is what a black spot channel gives. + let mut as_ink = d.clone(); + as_ink.channels[1].spot = Some((photocraft_color::Color::BLACK, 0.0)); + assert_eq!(photocraft_compose::flatten(&d).px, photocraft_compose::flatten(&as_ink).px); + + // Saved back unchanged: same DisplayInfo, same planes, same channels on reopening. + let (back, d2) = roundtrip(&d); + assert_eq!(back.resource(1077).map(|r| r.data.clone()), f.resource(1077).map(|r| r.data.clone())); + assert_eq!(back.decode_merged().unwrap(), f.decode_merged().unwrap()); + assert_eq!(d2.channels[1].spot, None); + assert_eq!(d2.channels[1].indicates, ColorIndicates::MaskedAreas); + assert!((d2.channels[1].opacity - 0.5).abs() < 1e-6); + assert!(d2.channels[0].spot.is_some()); + } +} + +#[test] +fn resources_and_global_blocks_survive_a_save() { + let mut f = file(8); + let iptc = vec![0x1c, 2, 0, 0, 2, 0, 4]; + let print_flags = vec![0, 0, 0, 0, 0, 0, 0, 1, 0]; + let seed = 7u32.to_be_bytes().to_vec(); + let alpha_ids = [0u32, 1].iter().flat_map(|v| v.to_be_bytes()).collect::>(); + f.resources.push(ImageResource::new(1028, iptc.clone())); + f.resources.push(ImageResource::new(1011, print_flags.clone())); + f.resources.push(ImageResource::new(1044, seed.clone())); + f.resources.push(ImageResource::new(1053, alpha_ids.clone())); + // A target-layer index describes layers, which a Multichannel document doesn't have. + f.resources.push(ImageResource::new(1024, vec![0, 0])); + let fmsk = vec![0, 0, 0, 0, 0, 50]; + f.global_blocks.push(TaggedBlock::new(*b"FMsk", fmsk.clone())); + let (mut d, _) = psd_to_document(&f); + d.guides.horizontal.push(2.0); + d.guides.vertical.push(3.0); + d.global_light.angle = 60.0; + let path = + Path::new(vec![Subpath { closed: true, op: PathOp::Combine, knots: vec![Knot::corner(1.0, 1.0), Knot::corner(8.0, 1.0), Knot::corner(4.0, 4.0)] }]); + d.paths.push(NamedPath { name: "Outline".into(), path, psd_raw: None }); + + let (back, d2) = roundtrip(&d); + let res = |id: u16| back.resource(id).map(|r| r.data.clone()); + assert_eq!(res(1028), Some(iptc)); + assert_eq!(res(1011), Some(print_flags)); + assert_eq!(res(1044), Some(seed)); + assert_eq!(res(1053), Some(alpha_ids)); + assert_eq!(res(1024), None); + let blocks: Vec<_> = back.global_blocks.iter().filter(|b| &b.key == b"FMsk").collect(); + assert_eq!(blocks.len(), 1); + assert_eq!(blocks[0].data, fmsk); + assert_eq!(d2.guides.horizontal, vec![2.0]); + assert_eq!(d2.guides.vertical, vec![3.0]); + assert_eq!(d2.global_light.angle, 60.0); + // The file's own saved path and the new one. + let names: Vec<&str> = d2.paths.iter().map(|p| p.name.as_str()).collect(); + assert_eq!(names, ["Path 1", "Outline"]); + let anchors = |p: &Path| p.subpaths.iter().flat_map(|s| s.knots.iter().map(|k| (k.anchor.x, k.anchor.y))).collect::>(); + let (got, want) = (anchors(&d2.paths[1].path), anchors(&d.paths[1].path)); + assert_eq!(got.len(), want.len()); + assert!(got.iter().zip(&want).all(|(a, b)| (a.0 - b.0).abs() < 1e-3 && (a.1 - b.1).abs() < 1e-3), "{got:?}"); + assert_eq!(back.decode_merged().unwrap(), f.decode_merged().unwrap()); + + // Alpha identifiers that no longer match the channels are not written. + d.channels.pop(); + let (back, _) = roundtrip(&d); + assert!(back.resource(1053).is_none()); +} + +/// A Photoshop Multichannel file: its alpha-type channel stays an alpha channel and a save keeps +/// every resource except the thumbnail (regenerated) and every document-level block. +#[cfg(feature = "corpus")] +#[test] +fn corpus_multichannel_round_trip_keeps_channels_and_resources() { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/psd/psd-tools/colormodes/4x4_16bit_multichannel.psd"); + assert!(path.is_file(), "{} is missing: run `cargo xtask corpus --all`", path.display()); + let bytes = std::fs::read(&path).unwrap(); + let f = PsdFile::from_bytes(&bytes).unwrap(); + let (d, _) = psd_to_document(&f); + let alpha: Vec<_> = d.channels.iter().filter(|c| c.spot.is_none()).collect(); + assert!(!alpha.is_empty(), "the file's alpha-type channel imports as an alpha channel"); + for a in &alpha { + assert_eq!(a.indicates, ColorIndicates::MaskedAreas); + assert_eq!(a.color.to_rgb(), [1.0, 0.0, 0.0]); + assert!((a.opacity - 0.5).abs() < 1e-6); + } + let (back, d2) = roundtrip(&d); + assert_eq!(back.resource(1077).map(|r| r.data.clone()), f.resource(1077).map(|r| r.data.clone())); + assert_eq!(back.decode_merged().unwrap(), f.decode_merged().unwrap()); + assert_eq!(d2.channels.iter().filter(|c| c.spot.is_none()).count(), alpha.len()); + let mut lost: Vec = f.resources.iter().map(|r| r.id).filter(|id| back.resource(*id).is_none()).collect(); + lost.retain(|id| *id != 1036); + assert!(lost.is_empty(), "resources lost on save: {lost:?}"); + let keys = |f: &PsdFile| f.global_blocks.iter().map(|b| b.key).collect::>(); + assert_eq!(keys(&back), keys(&f)); +} From b564f2ca9c81c0d51c87d96ee559de75dfd75cfc Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Mon, 12 Oct 2026 07:04:33 -0400 Subject: [PATCH 03/24] fix(layers): identify the Background by structure, never by its English name (#4036) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Photoshop's Background is the bottom layer of a file without transparency: a pixel layer that is transparency- and position-locked, whatever the file's language calls it ("Hintergrund", "背景", "Arrière-plan"). We matched the name "Background" in compose (deep / shallow knockout), the engine (cut/clear, merge visible, transforms, warps, distort, erasers, styles, masks, crops, straighten, smart-object unpack) and the UI (Properties, layer row, tab title), so a localized file's deep knockout revealed transparency instead of the Background. - `Document::background` / `background_mut` / `is_background` and `Layer::has_background_traits` in the doc model replace every name check; `extra_cmds::background_to_layer` is the one "Background → Layer 0" conversion. - PSD import marks the bottom record position-locked when it is transparency-protected and has no transparency channel, with or without an `lspf` block. Affinity import and HDR Toning now lock the Background's position like every other place that creates one. Co-authored-by: Claude Opus 5.5 --- crates/compose/src/advanced.rs | 6 +-- crates/compose/src/advanced_tests.rs | 23 ++++++++++ crates/doc/src/lib.rs | 50 ++++++++++++++++++++++ crates/engine/src/adjust_cmds.rs | 1 + crates/engine/src/analysis_cmds.rs | 2 +- crates/engine/src/background_cmds.rs | 15 +++---- crates/engine/src/color_to_alpha_cmds.rs | 4 +- crates/engine/src/commands.rs | 2 +- crates/engine/src/distort_cmds.rs | 16 ++----- crates/engine/src/edit_cmds.rs | 13 +++--- crates/engine/src/eraser_cmds.rs | 21 +++------ crates/engine/src/extra_cmds.rs | 19 ++++---- crates/engine/src/float_cmds.rs | 4 +- crates/engine/src/frame_cmds.rs | 2 +- crates/engine/src/image_cmds.rs | 9 ++-- crates/engine/src/layer_copy_cmds.rs | 2 +- crates/engine/src/layer_multi_cmds.rs | 8 +--- crates/engine/src/lens_cmds.rs | 3 +- crates/engine/src/mode_cmds.rs | 3 +- crates/engine/src/perspective_crop_cmds.rs | 12 +++--- crates/engine/src/pick_cmds.rs | 2 +- crates/engine/src/presets/styles.rs | 8 +--- crates/engine/src/slice_cmds.rs | 2 +- crates/engine/src/smart_cmds.rs | 2 +- crates/engine/src/smart_cmds/unpack.rs | 3 +- crates/engine/src/transform_cmds.rs | 27 ++++++------ crates/engine/src/warp_cmds.rs | 8 ++-- crates/io/src/affinity.rs | 1 + crates/io/src/psd_import.rs | 10 +++++ crates/io/tests/psd_background.rs | 39 +++++++++++++++++ crates/ui-egui/src/canvas.rs | 2 +- crates/ui-egui/src/doc_props_ui.rs | 7 +-- crates/ui-egui/src/panels.rs | 2 +- 33 files changed, 213 insertions(+), 115 deletions(-) create mode 100644 crates/io/tests/psd_background.rs diff --git a/crates/compose/src/advanced.rs b/crates/compose/src/advanced.rs index 4a9cb3e89b..6809c9e865 100644 --- a/crates/compose/src/advanced.rs +++ b/crates/compose/src/advanced.rs @@ -84,10 +84,10 @@ pub fn shapeless(layer: &Layer) -> bool { !layer.advanced.transparency_shapes && (layer.advanced.knockout != Knockout::None || effects::has_effects(layer)) } -/// The Background layer of a stack: the bottom layer, a locked, opaque-by-convention pixel layer -/// named "Background" (how PSD import and File › New create it). +/// Whether `l`, the bottom layer of a stack, is the Background: identified by its locks and kind, +/// never by its (localized) name ([`photocraft_doc::Document::background`]). pub fn is_background(l: &Layer) -> bool { - l.name == "Background" && l.locks.transparency && !l.clipped && matches!(l.content, LayerContent::Raster(_)) + l.has_background_traits() } /// What a deep knockout reveals over `rect`: the document's initial backdrop with its Background diff --git a/crates/compose/src/advanced_tests.rs b/crates/compose/src/advanced_tests.rs index c4e437a4b6..0ca3bdadb9 100644 --- a/crates/compose/src/advanced_tests.rs +++ b/crates/compose/src/advanced_tests.rs @@ -437,3 +437,26 @@ fn a_knockout_background_does_not_recurse() { let got = render(&d, Rect::from_xywh(0, 0, 1, 1)).px[0]; assert!(got[3] <= 1.0); } + +/// The Background is found by its structure, not its English name: a file from a German or +/// Japanese Photoshop calls it "Hintergrund" or "背景", and a deep knockout still reveals it. A +/// bottom layer merely called "Background", without the Background's locks, is not one. +#[test] +fn deep_knockout_reveals_a_localized_background() { + for depth in DEPTHS { + for name in ["Hintergrund", "背景", "Arrière-plan"] { + let mut d = doc(depth, true); + d.layers[0].name = name.into(); + let green = solid(&d, "green", full(&d), GREEN); + d.layers.push(green); + d.layers.push(knocker(&d, Knockout::Deep)); + check(&d, 2, 2, WHITE, name); + } + let mut d = doc(depth, true); + d.layers[0].locks = Default::default(); + let green = solid(&d, "green", full(&d), GREEN); + d.layers.push(green); + d.layers.push(knocker(&d, Knockout::Deep)); + check(&d, 2, 2, [0.0; 4], "an unlocked layer named Background"); + } +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 5ff69e581c..354de06d31 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -636,6 +636,13 @@ pub struct Layer { } impl Layer { + /// Whether the layer has the Background's own properties: an unclipped pixel layer with + /// transparency and position locked. Only the bottom layer of a document with them is the + /// Background: use [`Document::background`] / [`Document::is_background`] to identify it. + pub fn has_background_traits(&self) -> bool { + self.locks.transparency && self.locks.position && !self.clipped && matches!(self.content, LayerContent::Raster(_)) + } + pub fn new(name: impl Into, content: LayerContent) -> Self { Layer { id: LayerId::fresh(), @@ -1040,6 +1047,25 @@ impl Document { self.path_of(id).map_or_else(Locks::default, |p| self.locks_at(&p)) } + /// The Background layer, identified structurally as Photoshop does, never by its name (a file + /// from a German or Japanese Photoshop names it "Hintergrund" or "背景"): the bottom layer of + /// the stack, a pixel layer that is not clipped, with transparency and position locked (a PSD + /// stores it without a transparency channel and transparency-protected; File › New and opaque + /// flat files create it the same way). + pub fn background(&self) -> Option<&Layer> { + self.layers.first().filter(|l| Layer::has_background_traits(l)) + } + + /// [`Self::background`], mutably. + pub fn background_mut(&mut self) -> Option<&mut Layer> { + self.layers.first_mut().filter(|l| Layer::has_background_traits(l)) + } + + /// Whether `id` is the document's Background layer ([`Self::background`]). + pub fn is_background(&self, id: LayerId) -> bool { + self.background().is_some_and(|b| b.id == id) + } + pub fn layer(&self, id: LayerId) -> Option<&Layer> { fn rec(layers: &[Layer], id: LayerId) -> Option<&Layer> { layers.iter().find_map(|l| if l.id == id { Some(l) } else { l.children().and_then(|ch| rec(ch, id)) }) @@ -1205,6 +1231,30 @@ mod tests { assert_eq!(s.pixel(100, 0), vec![0.0; 4]); } + /// The Background is the locked bottom pixel layer, whatever it is called. + #[test] + fn background_is_structural_not_named() { + let mut d = doc(); + let id = d.layers[0].id; + assert!(d.is_background(id)); + for name in ["Hintergrund", "背景", "Arrière-plan"] { + d.layers[0].name = name.into(); + assert_eq!(d.background().map(|l| l.id), Some(id), "{name}"); + } + // A layer called "Background" without the locks, or above the bottom, is not it. + let mut top = Layer::raster("Background", d.pixel_format()); + top.locks.transparency = true; + top.locks.position = true; + let top_id = top.id; + d.layers.push(top); + assert!(!d.is_background(top_id)); + d.layers[0].locks.position = false; + assert!(d.background().is_none()); + d.layers[0].locks.position = true; + d.layers[0].clipped = true; + assert!(d.background_mut().is_none()); + } + #[test] fn max_group_depth_counts_nesting_without_recursing() { let mut d = doc(); diff --git a/crates/engine/src/adjust_cmds.rs b/crates/engine/src/adjust_cmds.rs index 42dd44d767..48f6e56246 100644 --- a/crates/engine/src/adjust_cmds.rs +++ b/crates/engine/src/adjust_cmds.rs @@ -428,6 +428,7 @@ fn hdr_toning(s: &mut Session, p: &Value) -> Result { let data: Vec = px.iter().flat_map(|q| photocraft_raster::from_rgba(&fmt, *q)).collect(); let mut bg = Layer::raster("Background", fmt); bg.locks.transparency = true; + bg.locks.position = true; crate::pixels_mut(&mut bg)?.write_region(doc.bounds(), &data); *active = Some(bg.id); doc.layers = vec![bg]; diff --git a/crates/engine/src/analysis_cmds.rs b/crates/engine/src/analysis_cmds.rs index b369479ce0..1ba04dfe4c 100644 --- a/crates/engine/src/analysis_cmds.rs +++ b/crates/engine/src/analysis_cmds.rs @@ -670,7 +670,7 @@ fn straighten(s: &mut Session, p: &Value) -> Result { return Ok(json!({"angle": 0.0})); } let st = s.active().ok_or(EngineError::NoDocument)?; - let active_bg = st.active_layer.and_then(|id| d.layer(id)).is_some_and(|l| l.name == "Background" && l.locks.position); + let active_bg = st.active_layer.and_then(|id| d.layer(id)).is_some_and(|l| d.is_background(l.id)); let crop = p.get("crop").and_then(Value::as_bool).unwrap_or(active_bg || st.active_layer.is_none()); let (w0, h0) = (f64::from(d.size.width), f64::from(d.size.height)); compound(s, "Straighten", |s| { diff --git a/crates/engine/src/background_cmds.rs b/crates/engine/src/background_cmds.rs index 1da5ebc92b..81c47501d3 100644 --- a/crates/engine/src/background_cmds.rs +++ b/crates/engine/src/background_cmds.rs @@ -10,14 +10,13 @@ use photocraft_doc::{Document, Layer, LayerContent, LayerId}; use serde_json::{Value, json}; use crate::commands::CommandSpec; -use crate::extra_cmds::is_background; use crate::{EngineError, Result, Session}; const CMD: &str = "layer.new.backgroundFromLayer"; /// The document's Background layer, if it has one (always the bottom layer). pub(crate) fn background_id(doc: &Document) -> Option { - doc.layers.first().filter(|l| is_background(l)).map(|l| l.id) + doc.background().map(|l| l.id) } /// Refuses an edit that moved the Background `bg` (taken before the edit) off the bottom of the @@ -155,7 +154,7 @@ mod tests { assert_eq!(s.execute(CMD, json!({})).unwrap()["layer"], a.0); assert_eq!(order(&s), [a, l0, b], "{depth}: drops to the bottom"); let l = &doc(&s).layers[0]; - assert!(is_background(l) && l.name == "Background", "{depth}"); + assert!(doc(&s).is_background(l.id) && l.name == "Background", "{depth}"); assert_eq!(s.active().unwrap().active_layer, Some(a)); // Its pixels stay; transparency takes the background colour (blue). let red = pixel(&s, 3, 3); @@ -170,10 +169,10 @@ mod tests { assert!(s.undo()); assert_eq!(order(&s), [l0, a, b], "{depth}"); let l = doc(&s).layer(a).unwrap(); - assert!(!is_background(l) && l.name == "A"); + assert!(!doc(&s).is_background(l.id) && l.name == "A"); assert!(s.redo()); assert_eq!(order(&s), [a, l0, b], "{depth}"); - assert!(is_background(&doc(&s).layers[0])); + assert!(doc(&s).is_background(doc(&s).layers[0].id)); } } @@ -191,7 +190,7 @@ mod tests { assert_eq!(d.layers[1].id, l0); assert_eq!(d.layers[2].id, a); let bg = &d.layers[0]; - assert!(is_background(bg) && !bg.visible, "visibility is kept"); + assert!(d.is_background(bg.id) && !bg.visible, "visibility is kept"); assert_eq!(bg.opacity, 1.0); } @@ -211,7 +210,7 @@ mod tests { for p in [json!({"layer": "A"}), json!({"layer": -1}), json!({"layer": 1.5}), json!({"layer": 99999}), json!({"layer": [a.0]})] { assert!(s.execute(CMD, p.clone()).is_err(), "{p}"); } - assert!(!doc(&s).layers.iter().any(is_background)); + assert!(doc(&s).background().is_none()); // A group or an adjustment layer can't become the Background. s.execute("layer.select", json!({"layer": a.0})).unwrap(); s.execute("layer.groupLayers", json!({})).unwrap(); @@ -220,7 +219,7 @@ mod tests { s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap(); assert!(!s.is_enabled(CMD)); assert!(s.execute(CMD, json!({})).is_err()); - assert!(!doc(&s).layers.iter().any(is_background)); + assert!(doc(&s).background().is_none()); } #[test] diff --git a/crates/engine/src/color_to_alpha_cmds.rs b/crates/engine/src/color_to_alpha_cmds.rs index c3120f4ad8..a6208e8246 100644 --- a/crates/engine/src/color_to_alpha_cmds.rs +++ b/crates/engine/src/color_to_alpha_cmds.rs @@ -92,7 +92,7 @@ fn enabled(s: &Session) -> std::result::Result<(), String> { if locks.pixels || locks.all { return Err(format!("the layer \"{}\" is locked", l.name)); } - if locks.transparency && !crate::extra_cmds::is_background(l) { + if locks.transparency && !d.doc.is_background(l.id) { return Err(format!("the transparency of layer \"{}\" is locked", l.name)); } Ok(()) @@ -217,7 +217,7 @@ mod tests { s.execute("edit.undo", json!({})).unwrap(); assert_eq!(name(&s), "Background"); let d = s.active().unwrap(); - assert!(crate::extra_cmds::is_background(d.doc.layer(d.active_layer.unwrap()).unwrap())); + assert!(d.doc.is_background(d.active_layer.unwrap())); } #[test] diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 2ce0b3762f..3554e5690f 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -1416,7 +1416,7 @@ pub(crate) fn translate_layer(doc: &Document, l: &mut Layer, dx: i32, dy: i32) { pub(crate) fn layer_copy(doc: &Document, id: LayerId) -> Result { let src = doc.layer(id).ok_or(EngineError::NoLayer(id))?; // A copy of the Background layer is an ordinary, unlocked layer (Photoshop). - let from_background = src.name == "Background" && src.locks.transparency && doc.layers.first().is_some_and(|b| b.id == id); + let from_background = doc.is_background(id); let mut dup = src.duplicate(); dup.name = doc.copy_name(&dup.name); if from_background { diff --git a/crates/engine/src/distort_cmds.rs b/crates/engine/src/distort_cmds.rs index 75ebf529bc..c164eaf679 100644 --- a/crates/engine/src/distort_cmds.rs +++ b/crates/engine/src/distort_cmds.rs @@ -213,15 +213,6 @@ fn smart_layer(s: &Session) -> std::result::Result<(), String> { } } -/// Unlocks a Background layer for an operation that exposes transparency (as Photoshop does). -fn float_background(l: &mut Layer) { - if l.locks.position && l.name == "Background" { - l.locks.position = false; - l.locks.transparency = false; - l.name = "Layer 0".into(); - } -} - fn check_locks(l: &Layer, group: Locks, position: bool) -> Result<()> { let locks = l.locks.union(group); if locks.all || locks.pixels || (position && locks.position) { @@ -247,14 +238,15 @@ fn run_on_layer(s: &mut Session, cmd: &str, label: &str, p: &Value, moves: bool, let canvas = doc.bounds(); let selection = doc.selection.clone(); let group = crate::transform_cmds::group_locks(doc, id); + // A Background gains transparency when the distortion moves pixels (as in Photoshop). + if moves { + crate::extra_cmds::background_to_layer(doc, id); + } let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; if let LayerContent::Smart(_) = l.content { let sf = SmartFilter { command: cmd.to_string(), params: params.clone(), blend: photocraft_color::BlendMode::Normal, opacity: 1.0, visible: true }; return crate::smart_cmds::add_smart_filter(doc, id, sf, selection.as_ref()); } - if moves { - float_background(l); - } check_locks(l, group, moves)?; let LayerContent::Raster(surf) = &mut l.content else { return Err(EngineError::Other(format!("{label} needs a pixel layer (rasterize it first)"))); diff --git a/crates/engine/src/edit_cmds.rs b/crates/engine/src/edit_cmds.rs index f99a81a640..d4de2d548e 100644 --- a/crates/engine/src/edit_cmds.rs +++ b/crates/engine/src/edit_cmds.rs @@ -82,7 +82,7 @@ fn whole_layers(d: &crate::DocState, ids: &[LayerId]) -> Option> { let mut copies = scratch_doc(&d.doc); for id in ids { let mut l = d.doc.layer(*id)?.clone(); - if crate::extra_cmds::is_background(&l) { + if d.doc.is_background(*id) { l.name = "Layer 0".into(); l.locks = Default::default(); } @@ -277,7 +277,8 @@ fn clear_selected(doc: &mut Document, id: LayerId, background: [f32; 4]) -> Resu /// Cut / Clear on a layer: makes the selected pixels transparent. The Background can't hold /// transparency, so there the area is filled with the background colour instead (Photoshop). pub(crate) fn clear_area(doc: &mut Document, id: LayerId, area: Rect, sel: Option<&Surface>, background: [f32; 4]) -> Result<()> { - let bg = crate::extra_cmds::is_background(doc.layer(id).ok_or(EngineError::NoLayer(id))?); + doc.layer(id).ok_or(EngineError::NoLayer(id))?; + let bg = doc.is_background(id); let surf = crate::commands::paint_surface(doc, id, &Value::Null)?; if bg { crate::pixels::try_fill_surface(surf, area, background, sel, true)?; @@ -461,7 +462,7 @@ fn merge_visible(s: &mut Session) -> Result { } let lowest = visible[0]; let base = doc.layers[lowest].clone(); - let is_background = base.name == "Background" && base.locks.transparency; + let is_background = lowest == 0 && doc.is_background(base.id); // Composite of visible layers only (hidden ones stay where they are). let mut solo = doc.clone(); solo.layers.retain(|l| l.visible); @@ -1363,7 +1364,7 @@ mod tests { let mut s = fresh(); s.execute(cmd, json!({})).unwrap(); let d = &s.active().unwrap().doc; - assert!(crate::extra_cmds::is_background(&d.layers[0]), "{cmd}: still the Background"); + assert!(d.is_background(d.layers[0].id), "{cmd}: still the Background"); assert_eq!(px(&s, 0, 8, 8), vec![1.0, 0.0, 0.0, 1.0], "{cmd}: cut area is the background colour"); assert_eq!(px(&s, 0, 30, 20), vec![1.0, 1.0, 1.0, 1.0], "{cmd}: outside untouched"); } @@ -1609,9 +1610,9 @@ mod tests { let st = s.active().unwrap(); assert_eq!(st.doc.layers.len(), 4); let pasted = &st.doc.layers[st.doc.layers.len() - 2]; - assert!(!crate::extra_cmds::is_background(pasted)); + assert!(!st.doc.is_background(pasted.id)); assert_eq!(pasted.locks, Default::default()); - assert!(crate::extra_cmds::is_background(&st.doc.layers[0]), "the real Background is untouched"); + assert!(st.doc.is_background(st.doc.layers[0].id), "the real Background is untouched"); } /// #2428: a smart object copied in one document pastes into another as a smart object, in diff --git a/crates/engine/src/eraser_cmds.rs b/crates/engine/src/eraser_cmds.rs index 98169aff72..3fb546de4f 100644 --- a/crates/engine/src/eraser_cmds.rs +++ b/crates/engine/src/eraser_cmds.rs @@ -59,19 +59,6 @@ fn active_pixel_layer(s: &Session, cmd: &str) -> Result { s.active().and_then(|d| d.active_layer).ok_or_else(|| bad(cmd, "no active layer")) } -fn is_background(l: &Layer) -> bool { - l.name == "Background" && l.locks.transparency && l.locks.position && matches!(l.content, LayerContent::Raster(_)) -} - -/// Photoshop converts the Background to a normal layer before erasing to transparency. -fn unlock_background(l: &mut Layer) { - if is_background(l) { - l.name = "Layer 0".into(); - l.locks.transparency = false; - l.locks.position = false; - } -} - fn pixels_locked(doc: &Document, l: &Layer) -> Option { let locks = doc.effective_locks(l.id); (locks.pixels || locks.all).then(|| EngineError::Other(format!("Could not complete your request because the layer \"{}\" is locked", l.name))) @@ -114,7 +101,9 @@ fn magic_eraser(s: &mut Session, p: &Value) -> Result { let bg = s.tools.background; let dmg = s.edit("Magic Eraser", |doc, _| { let selection = doc.selection.clone(); - unlock_background(doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?); + // Photoshop converts the Background to a normal layer before erasing to transparency. + doc.layer(id).ok_or(EngineError::NoLayer(id))?; + crate::extra_cmds::background_to_layer(doc, id); let lock = doc.effective_locks(id).transparency; let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; let surf = l.surface_mut().ok_or_else(|| bad(CMD, "not a pixel layer"))?; @@ -149,15 +138,15 @@ fn background_eraser(s: &mut Session, p: &Value) -> Result { if let Some(e) = pixels_locked(&d.doc, l) { return Err(e); } - if d.doc.effective_locks(id).transparency && !is_background(l) { + if d.doc.effective_locks(id).transparency && !d.doc.is_background(id) { return Err(EngineError::Other(format!("Could not use the Background Eraser because the transparency of layer \"{}\" is locked", l.name))); } } let stroke = Stroke { brush, points: pts }; let dmg = s.edit("Background Eraser", |doc, _| { let selection = doc.selection.clone(); + crate::extra_cmds::background_to_layer(doc, id); let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; - unlock_background(l); let surf = l.surface_mut().ok_or_else(|| bad(CMD, "not a pixel layer"))?; Ok(apply_background_eraser(surf, &stroke, &bs, selection.as_ref())) })?; diff --git a/crates/engine/src/extra_cmds.rs b/crates/engine/src/extra_cmds.rs index 84c0e24de1..cebb9ec890 100644 --- a/crates/engine/src/extra_cmds.rs +++ b/crates/engine/src/extra_cmds.rs @@ -43,13 +43,9 @@ fn has_clip_and_selection(s: &Session) -> std::result::Result<(), String> { d.doc.selection.as_ref().map(|_| ()).ok_or_else(|| "Paste Into needs a selection".into()) } -pub(crate) fn is_background(l: &Layer) -> bool { - l.name == "Background" && l.locks.transparency && l.locks.position && matches!(l.content, LayerContent::Raster(_)) -} - fn has_background(s: &Session) -> std::result::Result<(), String> { let d = s.active().ok_or("no document open")?; - d.doc.layers.first().filter(|l| is_background(l)).map(|_| ()).ok_or_else(|| "the document has no Background layer".into()) + d.doc.background().map(|_| ()).ok_or_else(|| "the document has no Background layer".into()) } /// The layers a layer-style command acts on: as [`crate::layer_multi_cmds::targets`], but with @@ -60,7 +56,7 @@ pub(crate) fn style_targets(s: &Session, p: &Value, fits: impl Fn(&Layer) -> boo return Ok(ids); } let d = s.active().ok_or(EngineError::NoDocument)?; - let ids: Vec = ids.into_iter().filter(|id| d.doc.layer(*id).is_some_and(|l| !is_background(l) && fits(l))).collect(); + let ids: Vec = ids.into_iter().filter(|id| d.doc.layer(*id).is_some_and(|l| !d.doc.is_background(l.id) && fits(l))).collect(); if ids.is_empty() { return Err(EngineError::Other("none of the selected layers can take this layer style change".into())); } @@ -441,7 +437,7 @@ pub fn reveal_all_bounds(doc: &Document) -> Rect { fn layer_from_background(s: &mut Session) -> Result { let id = s.edit("Layer From Background", |doc, active| { - let l = doc.layers.first_mut().filter(|l| is_background(l)).ok_or(EngineError::Other("the document has no Background layer".into()))?; + let l = doc.background_mut().ok_or(EngineError::Other("the document has no Background layer".into()))?; unlock_background(l); *active = Some(l.id); Ok(l.id) @@ -458,7 +454,14 @@ pub(crate) fn unlock_background(l: &mut Layer) { /// Before `id` gets a layer mask: the Background can't have one, so it becomes a normal layer /// first ("Layer 0"), as when adding a mask to it in Photoshop. Other layers are left alone. pub(crate) fn background_to_layer_for_mask(doc: &mut photocraft_doc::Document, id: photocraft_doc::LayerId) { - if let Some(l) = doc.layers.first_mut().filter(|l| l.id == id && is_background(l)) { + background_to_layer(doc, id); +} + +/// If `id` is the Background ([`photocraft_doc::Document::background`], whatever its name), turns +/// it into a normal layer ("Layer 0"), as Photoshop does before an edit the Background can't +/// take (moving, transforming, exposing transparency, a style). Other layers are left alone. +pub(crate) fn background_to_layer(doc: &mut photocraft_doc::Document, id: photocraft_doc::LayerId) { + if let Some(l) = doc.background_mut().filter(|l| l.id == id) { unlock_background(l); } } diff --git a/crates/engine/src/float_cmds.rs b/crates/engine/src/float_cmds.rs index 892f754748..aaab22fde2 100644 --- a/crates/engine/src/float_cmds.rs +++ b/crates/engine/src/float_cmds.rs @@ -58,7 +58,7 @@ impl CutParts { // A mask has no alpha: it keeps its format, and the cut leaves background colour. let mut rest = if mask { surf.clone() } else { full.clone() }; let mut piece = Surface::new(with_alpha); - let fill = !copy && (mask || crate::extra_cmds::is_background(l)); + let fill = !copy && (mask || doc.is_background(layer)); // A mask's untouched pixels (its default, e.g. white) move too, so take the whole canvas. let b = sel.content_bounds().intersect(&if mask { doc.bounds() } else { surf.content_bounds() }); if !b.is_empty() { @@ -165,7 +165,7 @@ fn can_float(s: &Session) -> std::result::Result<(), String> { /// floating? The Background is position-locked, but its selected pixels move (Photoshop). pub fn locked_for_float(doc: &Document, l: &photocraft_doc::Layer) -> bool { let locks = doc.effective_locks(l.id); - locks.all || (locks.position && !crate::extra_cmds::is_background(l)) + locks.all || (locks.position && !doc.is_background(l.id)) } fn float(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/frame_cmds.rs b/crates/engine/src/frame_cmds.rs index df84bdcfd1..c97006e746 100644 --- a/crates/engine/src/frame_cmds.rs +++ b/crates/engine/src/frame_cmds.rs @@ -137,7 +137,7 @@ fn new_frame(s: &mut Session, p: &Value) -> Result { let gid = match content { Some(id) => { let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?; - if !matches!(l.content, LayerContent::Raster(_)) || crate::extra_cmds::is_background(l) { + if !matches!(l.content, LayerContent::Raster(_)) || doc.is_background(id) { return Err(bad("only a pixel layer (not the Background) can go in a frame".into())); } let gid = doc.insert_above(Some(id), Layer::group(name, vec![])); diff --git a/crates/engine/src/image_cmds.rs b/crates/engine/src/image_cmds.rs index f477bd220e..9ccca87ada 100644 --- a/crates/engine/src/image_cmds.rs +++ b/crates/engine/src/image_cmds.rs @@ -300,7 +300,7 @@ fn crop_doc(doc: &mut Document, cmd: &str, r: Rect, delete_pixels: bool, extensi // A Background cannot hold transparent pixels: like an opaque Canvas Size extension, the area // an extending Crop adds is filled with the extension (background) colour. if extends - && let Some(bg) = doc.layers.first_mut().filter(|l| crate::extra_cmds::is_background(l)) + && let Some(bg) = doc.background_mut() && let LayerContent::Raster(surf) = &mut bg.content { let old = old_canvas.translate(dx, dy); @@ -381,16 +381,13 @@ fn canvas_size(s: &mut Session, p: &Value) -> Result { // A shrink or no-op resize must not silently convert the Background. if ext[3] == 0.0 && (nw > ow as u32 || nh > oh as u32) - && let Some(bg) = doc.layers.first_mut() - && crate::extra_cmds::is_background(bg) + && let Some(bg) = doc.background_mut() { crate::extra_cmds::unlock_background(bg); } // The locked Background layer is extended with the extension colour. if ext[3] > 0.0 - && let Some(bg) = doc.layers.first_mut() - && bg.name == "Background" - && bg.locks.transparency + && let Some(bg) = doc.background_mut() && let LayerContent::Raster(surf) = &mut bg.content { let fmt = surf.format(); diff --git a/crates/engine/src/layer_copy_cmds.rs b/crates/engine/src/layer_copy_cmds.rs index 29eff4c8df..9a42778de2 100644 --- a/crates/engine/src/layer_copy_cmds.rs +++ b/crates/engine/src/layer_copy_cmds.rs @@ -163,7 +163,7 @@ fn copy_to_document(s: &mut Session, p: &Value) -> Result { let src_layer = sdoc.layer(*id).ok_or(EngineError::NoLayer(*id))?; let mut l = src_layer.duplicate(); // A dragged Background arrives as an ordinary layer (the destination keeps its own). - if crate::extra_cmds::is_background(src_layer) && sdoc.layers.first().is_some_and(|b| b.id == *id) { + if sdoc.is_background(*id) { l.name = ddoc.next_layer_name("Layer"); l.locks = Default::default(); } diff --git a/crates/engine/src/layer_multi_cmds.rs b/crates/engine/src/layer_multi_cmds.rs index 62006d0832..f0bf4a503e 100644 --- a/crates/engine/src/layer_multi_cmds.rs +++ b/crates/engine/src/layer_multi_cmds.rs @@ -44,7 +44,7 @@ pub(crate) fn mask_targets(s: &Session, p: &serde_json::Value) -> Result = ids.into_iter().filter(|id| d.doc.layer(*id).is_some_and(|l| l.mask.is_none() && !crate::extra_cmds::is_background(l))).collect(); + let ids: Vec = ids.into_iter().filter(|id| d.doc.layer(*id).is_some_and(|l| l.mask.is_none() && !d.doc.is_background(l.id))).collect(); if ids.is_empty() { return Err(EngineError::Other("none of the selected layers can take a layer mask".into())); } @@ -163,13 +163,9 @@ pub fn select(s: &mut Session, p: &Value) -> Result { Ok(json!({"selected": selected(s).iter().map(|l| l.0).collect::>()})) } -pub(crate) fn is_locked_background(l: &Layer) -> bool { - l.name == "Background" && l.locks.transparency && matches!(l.content, LayerContent::Raster(_)) -} - fn select_all_layers(s: &mut Session) -> Result { let d = s.active().ok_or(EngineError::NoDocument)?; - let ids: Vec = d.doc.walk().into_iter().filter(|(_, _, l)| !is_locked_background(l)).map(|(_, _, l)| l.id).collect(); + let ids: Vec = d.doc.walk().into_iter().filter(|(_, _, l)| !d.doc.is_background(l.id)).map(|(_, _, l)| l.id).collect(); if ids.is_empty() { return Err(EngineError::Other("there are no layers to select".into())); } diff --git a/crates/engine/src/lens_cmds.rs b/crates/engine/src/lens_cmds.rs index c0513cf373..31d69300f4 100644 --- a/crates/engine/src/lens_cmds.rs +++ b/crates/engine/src/lens_cmds.rs @@ -287,6 +287,7 @@ fn run_filter(s: &mut Session, cmd: &str, label: &str, stored: Value, float_bg: let canvas = doc.bounds(); let selection = doc.selection.clone(); let locks = doc.effective_locks(id); + let background = doc.is_background(id); let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; if let LayerContent::Smart(_) = l.content { let sf = SmartFilter { command: cmd.to_string(), params: stored.clone(), blend: photocraft_color::BlendMode::Normal, opacity: 1.0, visible: true }; @@ -296,7 +297,7 @@ fn run_filter(s: &mut Session, cmd: &str, label: &str, stored: Value, float_bg: return Err(EngineError::Other(format!("layer \"{}\" is locked", l.name))); } // A Background layer gains transparency when the edge mode exposes it (as in Photoshop). - if float_bg && l.locks.position && l.name == "Background" { + if float_bg && background { l.locks.position = false; l.locks.transparency = false; l.name = "Layer 0".into(); diff --git a/crates/engine/src/mode_cmds.rs b/crates/engine/src/mode_cmds.rs index def9440c84..5965303495 100644 --- a/crates/engine/src/mode_cmds.rs +++ b/crates/engine/src/mode_cmds.rs @@ -91,8 +91,9 @@ pub(crate) fn rotate_arbitrary(s: &mut Session, p: &Value) -> Result { let canvas = doc.bounds(); let fmt = doc.pixel_format(); let dpi = doc.resolution_dpi; + let background_id = doc.background().map(|l| l.id); for l in doc.layers.iter_mut() { - let background = l.name == "Background" && l.locks.position && matches!(l.content, LayerContent::Raster(_)); + let background = Some(l.id) == background_id; if background && let Some(surf) = l.surface_mut() { // The Background stays a Background: rotated pixels over the background colour. let src = surf.content_bounds(); diff --git a/crates/engine/src/perspective_crop_cmds.rs b/crates/engine/src/perspective_crop_cmds.rs index c8881e6f70..8acaf42ce2 100644 --- a/crates/engine/src/perspective_crop_cmds.rs +++ b/crates/engine/src/perspective_crop_cmds.rs @@ -14,7 +14,7 @@ use photocraft_algo::transform::{Homography, Interp, convex_quad, quad_size, quad_to_rect, warp_surface_clipped}; use photocraft_color::PixelFormat; -use photocraft_doc::{Document, Layer, LayerContent, Size}; +use photocraft_doc::{Document, Layer, LayerContent, LayerId, Size}; use photocraft_geom::{Affine, Rect}; use photocraft_raster::Surface; use serde_json::{Value, json}; @@ -154,12 +154,13 @@ fn warp_gray(s: &Surface, h: &Homography, interp: Interp, clip: Rect) -> Result< } /// Maps every layer's pixels and masks through `h` into `clip`. -fn warp_layers(layers: &mut [Layer], h: &Homography, interp: Interp, clip: Rect, bg: &[f32]) -> Result<()> { +/// `background_id` is the id of the document's Background, if it has one. +fn warp_layers(layers: &mut [Layer], h: &Homography, interp: Interp, clip: Rect, bg: &[f32], background_id: Option) -> Result<()> { for l in layers { crate::allocation::checkpoint("a perspective crop")?; - let background = crate::extra_cmds::is_background(l); + let background = background_id == Some(l.id); match &mut l.content { - LayerContent::Group(g) => warp_layers(&mut g.children, h, interp, clip, bg)?, + LayerContent::Group(g) => warp_layers(&mut g.children, h, interp, clip, bg, None)?, LayerContent::Raster(surf) => { let warped = warp_surface_clipped(surf, surf.content_bounds(), h, interp, clip)?; *surf = if background { @@ -188,7 +189,8 @@ fn apply(doc: &mut Document, q: &[[f64; 2]; 4], h: &Homography, size: (u32, u32) let (w, ht) = size; let clip = Rect::from_xywh(0, 0, w, ht); let bg = photocraft_raster::from_rgba(&doc.pixel_format(), bg); - warp_layers(&mut doc.layers, h, interp, clip, &bg)?; + let background_id = doc.background().map(|l| l.id); + warp_layers(&mut doc.layers, h, interp, clip, &bg, background_id)?; for ch in doc.channels.iter_mut().chain(doc.quick_mask.as_mut()) { ch.surface = warp_gray(&ch.surface, h, interp, clip)?; } diff --git a/crates/engine/src/pick_cmds.rs b/crates/engine/src/pick_cmds.rs index ccb3b4ca11..c8583305da 100644 --- a/crates/engine/src/pick_cmds.rs +++ b/crates/engine/src/pick_cmds.rs @@ -126,7 +126,7 @@ pub fn layers_in_rect(doc: &Document, r: Rect, group: bool) -> Vec { let canvas = doc.bounds(); for (path, _, l) in doc.walk().iter().rev() { if matches!(l.content, LayerContent::Group(_) | LayerContent::Adjustment(_)) - || crate::layer_multi_cmds::is_locked_background(l) + || doc.is_background(l.id) || doc.effective_locks(l.id).all || !(1..=path.len()).all(|n| doc.layer_at(&path[..n]).is_some_and(|a| a.visible)) { diff --git a/crates/engine/src/presets/styles.rs b/crates/engine/src/presets/styles.rs index a8c60d6a4c..ee4607cf86 100644 --- a/crates/engine/src/presets/styles.rs +++ b/crates/engine/src/presets/styles.rs @@ -191,13 +191,9 @@ fn apply(s: &mut Session, p: &Value) -> Result { let mode = doc.mode; let effects: Vec<_> = effects.iter().cloned().map(|e| e.in_mode(mode)).collect(); for id in &ids { - let l = doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?; // Styles can't sit on the Background: Photoshop turns it into a normal layer first. - if l.name == "Background" && l.locks.transparency && l.locks.position && matches!(l.content, photocraft_doc::LayerContent::Raster(_)) { - l.name = "Layer 0".into(); - l.locks.transparency = false; - l.locks.position = false; - } + crate::extra_cmds::background_to_layer(doc, *id); + let l = doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?; if add { l.effects.items.extend(effects.iter().cloned()); } else { diff --git a/crates/engine/src/slice_cmds.rs b/crates/engine/src/slice_cmds.rs index 0d3cceb6f0..959f132927 100644 --- a/crates/engine/src/slice_cmds.rs +++ b/crates/engine/src/slice_cmds.rs @@ -50,7 +50,7 @@ fn has_layer_for_slice(s: &Session) -> std::result::Result<(), String> { if matches!(l.content, LayerContent::Adjustment(_)) { return Err("adjustment layers have no bounds to slice".into()); } - if d.doc.layers.first().is_some_and(|b| b.id == id && b.name == "Background" && b.locks.transparency && b.locks.position) { + if d.doc.is_background(id) { return Err("the Background layer can't have a layer-based slice".into()); } if d.doc.slices.list.iter().any(|s| s.layer == Some(id)) { diff --git a/crates/engine/src/smart_cmds.rs b/crates/engine/src/smart_cmds.rs index 5678a8b7d9..e632251982 100644 --- a/crates/engine/src/smart_cmds.rs +++ b/crates/engine/src/smart_cmds.rs @@ -666,7 +666,7 @@ fn any_layer(l: &Layer, f: &dyn Fn(&Layer) -> bool) -> bool { /// blend mode, clipping and label stay on the smart layer. The cache is the exact composite, so /// the document looks the same before and after. pub fn layer_to_smart(doc: &Document, l: &Layer) -> Result { - let background = l.name == "Background" && l.locks.position; + let background = doc.is_background(l.id); let mut inner = l.clone(); inner.visible = true; inner.opacity = 1.0; diff --git a/crates/engine/src/smart_cmds/unpack.rs b/crates/engine/src/smart_cmds/unpack.rs index 8ddfa3d8b5..0fdf3ac3fa 100644 --- a/crates/engine/src/smart_cmds/unpack.rs +++ b/crates/engine/src/smart_cmds/unpack.rs @@ -32,9 +32,10 @@ fn contents(s: &Session, doc: &Document, sm: &SmartObject, intent: Intent, bpc: if src.depth != doc.depth { crate::image_cmds::convert_layers_depth(&mut src.layers, doc.depth); } + let background_id = src.background().map(|l| l.id); let mut layers = std::mem::take(&mut src.layers); for l in &mut layers { - if crate::extra_cmds::is_background(l) { + if Some(l.id) == background_id { l.name = "Layer 0".into(); l.locks = Default::default(); } diff --git a/crates/engine/src/transform_cmds.rs b/crates/engine/src/transform_cmds.rs index 44ea2e189c..2b35b18333 100644 --- a/crates/engine/src/transform_cmds.rs +++ b/crates/engine/src/transform_cmds.rs @@ -201,10 +201,10 @@ pub(crate) fn group_locks(doc: &Document, id: LayerId) -> Locks { } /// The locks a transform of `l` meets: its own and `group`'s (those it inherits). The Background's -/// position lock doesn't count: Photoshop turns it into a normal layer first ([`transform_layer`]). -fn transform_locks(l: &Layer, group: Locks) -> Locks { +/// position lock doesn't count: Photoshop turns it into a normal layer first. +fn transform_locks(l: &Layer, group: Locks, background: bool) -> Locks { let mut own = l.locks; - if own.position && l.name == "Background" { + if background { own.position = false; own.transparency = false; } @@ -217,29 +217,24 @@ fn transform_locks(l: &Layer, group: Locks) -> Locks { pub fn locked_for_transform(doc: &Document, id: LayerId) -> bool { let Some(l) = doc.layer(id) else { return false }; // An explicit stack rather than recursion: documents can nest deeply. - let mut stack = vec![(l, group_locks(doc, id))]; - while let Some((l, group)) = stack.pop() { - let locks = transform_locks(l, group); + let mut stack = vec![(l, group_locks(doc, id), doc.is_background(id))]; + while let Some((l, group, background)) = stack.pop() { + let locks = transform_locks(l, group, background); if locks.position || locks.all { return true; } if let LayerContent::Group(g) = &l.content { - stack.extend(g.children.iter().map(|c| (c, locks))); + stack.extend(g.children.iter().map(|c| (c, locks, false))); } } false } -/// `group` holds the locks `l` inherits from the groups around it ([`group_locks`]). +/// `group` holds the locks `l` inherits from the groups around it ([`group_locks`]). A Background +/// is turned into a normal layer by the caller first ([`crate::extra_cmds::background_to_layer`]). pub(crate) fn transform_layer(doc_sel: Option<&Surface>, group: Locks, l: &mut Layer, h: &Homography, affine: Option, interp: Interp) -> Result<()> { crate::allocation::checkpoint("transforming pixels")?; - let locks = transform_locks(l, group); - // Photoshop turns the Background into a normal layer before transforming it. - if l.locks.position && l.name == "Background" { - l.locks.position = false; - l.locks.transparency = false; - l.name = "Layer 0".into(); - } + let locks = transform_locks(l, group, false); if locks.position || locks.all { return Err(EngineError::Other(format!("layer \"{}\" is locked", l.name))); } @@ -493,6 +488,8 @@ fn transform(s: &mut Session, p: &Value) -> Result { let id = id.ok_or_else(|| EngineError::Other("no active layer".into()))?; let is_group = doc.layer(id).is_some_and(Layer::is_group); let group = group_locks(doc, id); + // Photoshop turns the Background into a normal layer before transforming it. + crate::extra_cmds::background_to_layer(doc, id); let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; transform_layer(if is_group { None } else { sel.as_ref() }, group, l, &h, affine, interp)?; if !h.is_identity() { diff --git a/crates/engine/src/warp_cmds.rs b/crates/engine/src/warp_cmds.rs index 49578cbb52..844da50345 100644 --- a/crates/engine/src/warp_cmds.rs +++ b/crates/engine/src/warp_cmds.rs @@ -110,12 +110,9 @@ pub fn warp_from_params(cmd: &str, p: &Value, rect: [f64; 4]) -> Result { Ok(w) } +/// A Background is turned into a normal layer by the caller first +/// ([`crate::extra_cmds::background_to_layer`]). fn warp_layer(doc_sel: Option<&Surface>, group: Locks, l: &mut Layer, w: &Warp, rect: Rect, interp: Interp) -> Result<()> { - if l.locks.position && l.name == "Background" { - l.locks.position = false; - l.locks.transparency = false; - l.name = "Layer 0".into(); - } let locks = l.locks.union(group); if locks.position || locks.all { return Err(EngineError::Other(format!("layer \"{}\" is locked", l.name))); @@ -270,6 +267,7 @@ fn apply(s: &mut Session, p: &Value, cmd: &str) -> Result { let sel = doc.selection.clone(); let is_group = doc.layer(id).is_some_and(Layer::is_group); let group = crate::transform_cmds::group_locks(doc, id); + crate::extra_cmds::background_to_layer(doc, id); let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; warp_layer(if is_group { None } else { sel.as_ref() }, group, l, &w, rect, interp)?; let snapshot = doc.clone(); diff --git a/crates/io/src/affinity.rs b/crates/io/src/affinity.rs index f829326e21..efba868be0 100644 --- a/crates/io/src/affinity.rs +++ b/crates/io/src/affinity.rs @@ -151,6 +151,7 @@ impl Builder { bg.prune(); let mut l = Layer::new("Background", LayerContent::Raster(bg)); l.locks.transparency = true; + l.locks.position = true; layers.insert(0, l); } self.doc.layers = layers; diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs index 137381fc54..ffe2d34eaf 100644 --- a/crates/io/src/psd_import.rs +++ b/crates/io/src/psd_import.rs @@ -706,6 +706,16 @@ pub fn psd_to_document_with(file: &PsdFile, ctl: &photocraft_raster::Interrupt) // its own profile, as the compositor and the PSD writer read them. let space = photocraft_compose::cmyk_space(&doc); doc.layers = photocraft_color::convert::with_cmyk_space(space.as_ref(), || cx.build(&tree, 0)); + // Photoshop's Background: the bottom record, a transparency-protected pixel layer stored + // without a transparency channel (-1). It is also position-locked, whatever its + // (localized) name and whether or not the file carries an `lspf` block. + if let (Some(rec), Some(bottom)) = (file.layers().first(), doc.layers.first_mut()) + && rec.flags.transparency_protected() + && !rec.channels.iter().any(|c| c.id == -1) + && matches!(bottom.content, LayerContent::Raster(_)) + { + bottom.locks.position = true; + } // Layer › Link Layers: resource 1026 holds one group id per layer record (0 = unlinked). if let Some(Ok(photocraft_psd::resources::ResourceData::LayerGroupInfo(groups))) = file.resources.iter().find(|r| r.id == ids::LAYER_GROUP_INFO).and_then(photocraft_psd::resources::ImageResource::parsed) diff --git a/crates/io/tests/psd_background.rs b/crates/io/tests/psd_background.rs new file mode 100644 index 0000000000..d24d24409e --- /dev/null +++ b/crates/io/tests/psd_background.rs @@ -0,0 +1,39 @@ +//! A PSD's Background is recognised by its structure (the bottom record, transparency-protected, +//! stored without a transparency channel), whatever its name in the Photoshop language that +//! saved the file. + +use photocraft_io::psd_to_document; +use photocraft_psd::{ColorMode, Compression, PsdFile, TaggedBlock, Version, testgen}; + +/// `testgen::layered` with its bottom layer turned into a Photoshop Background named `name`. +fn file(name: &str, transparency_channel: bool) -> PsdFile { + let mut f = testgen::layered(Version::Psd, ColorMode::Rgb, 8, Compression::Rle); + let bottom = f.layers_mut().first_mut().unwrap(); + bottom.name = name.bytes().filter(u8::is_ascii).collect(); + bottom.blocks.retain(|b| &b.key != b"luni" && &b.key != b"lspf"); + bottom.blocks.push(TaggedBlock::unicode_name(name)); + bottom.flags.set_transparency_protected(true); + if !transparency_channel { + bottom.channels.retain(|c| c.id != -1); + } + f +} + +#[test] +fn a_localized_background_is_the_background() { + for name in ["Hintergrund", "背景", "Arrière-plan"] { + let (d, _) = psd_to_document(&file(name, false)); + let bg = d.background().unwrap_or_else(|| panic!("{name}: no Background")); + assert_eq!(bg.name, name); + assert!(bg.locks.transparency && bg.locks.position, "{name}"); + assert_eq!(bg.id, d.layers[0].id); + } +} + +#[test] +fn a_protected_layer_with_transparency_is_not_the_background() { + // Lock Transparent Pixels on an ordinary bottom layer: it keeps its transparency channel. + let (d, _) = psd_to_document(&file("Background", true)); + assert!(d.layers[0].locks.transparency); + assert!(d.background().is_none()); +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 19f1cbf4c0..c9e4c6ce9c 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -2089,7 +2089,7 @@ const STUDIO_TAB_GAP: f32 = 4.0; fn pro_tab_title(app: &PhotocraftApp, i: usize) -> String { let Some(st) = app.session.documents().get(i) else { return String::new() }; let zoom = app.ui.views.get(i).map_or(100.0, |v| v.zoom * 100.0); - let active_layer = st.active_layer.and_then(|id| st.doc.layer(id)).filter(|l| !(l.name == "Background" && l.locks.transparency)); + let active_layer = st.active_layer.and_then(|id| st.doc.layer(id)).filter(|l| !st.doc.is_background(l.id)); let mask = app.session.active_index() == Some(i) && app.ui.mask_target && active_layer.is_some_and(|l| l.mask.is_some()); let model = if mask { tl!("Layer Mask").to_string() } else { mode_label(&st.doc).to_string() }; let layer = active_layer.map(|l| format!("{}, ", l.name)).unwrap_or_default(); diff --git a/crates/ui-egui/src/doc_props_ui.rs b/crates/ui-egui/src/doc_props_ui.rs index 2383590c79..8c10b8c442 100644 --- a/crates/ui-egui/src/doc_props_ui.rs +++ b/crates/ui-egui/src/doc_props_ui.rs @@ -3,15 +3,16 @@ //! Rulers & Grids toggles. Every edit dispatches an engine or view command, so the panel stays thin. use egui::{Align2, Rect, RichText, Sense, Stroke, StrokeKind, pos2, vec2}; -use photocraft_doc::{ColorMode, Document, Layer, LayerContent, LayerId, SampleType}; +use photocraft_doc::{ColorMode, Document, Layer, LayerId, SampleType}; use serde_json::{Value, json}; use crate::theme::Tokens; use crate::{PhotocraftApp, icons, widgets}; -/// Photoshop's Background layer: the locked, opaque raster layer at the bottom of the stack. +/// Photoshop's Background layer: the locked, opaque raster layer at the bottom of the stack, +/// whatever its (localized) name ([`Document::background`]). pub fn is_background(doc: &Document, l: &Layer) -> bool { - l.name == "Background" && l.locks.transparency && matches!(l.content, LayerContent::Raster(_)) && doc.layers.first().is_some_and(|b| b.id == l.id) + doc.is_background(l.id) } /// Does the Properties panel show the Document view? (No layer selected, or the Background layer.) diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 25f3653b05..086d1c0604 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -2689,7 +2689,7 @@ fn layer_row( let name_color = if l.visible { t.text } else { t.text_faint }; let font = if selected && !t.pro { theme::medium(13.0) } else { egui::FontId::proportional(if t.pro { 12.0 } else { 13.0 }) }; // Photoshop before 2026 set the Background layer's name in italics; 2026 sets it upright. - let italic = !t.pro && l.name == "Background" && l.locks.transparency; + let italic = !t.pro && doc.is_background(l.id); // Photoshop rows show only the name; the kind sub-label is a Studio-theme addition. let is_pixel = t.pro || matches!(l.content, LayerContent::Raster(_)); let name_rect = crate::layer_row_ui::truncated(&painter, &l.name, font, name_color, italic, name_right - x).map(|galley| { From 21f1012ce2ef3d90c2f6e867dd84c0edc13d6401 Mon Sep 17 00:00:00 2001 From: Valentin Klein Date: Mon, 12 Oct 2026 13:11:41 +0200 Subject: [PATCH 04/24] Codecs: refuse implausible PNG/WebP headers before allocating (#3691) (#3706) A tiny file declaring a huge image reserved the full output buffer before any data was checked. Add Limits::check_plausible (compression-ratio guard) and a fallible alloc_zeroed, use them in PNG and WebP, and lower the 32-bit default max_alloc to 1 GiB. Co-authored-by: Claude Opus 5.5 --- crates/codecs/src/codecs/png.rs | 8 ++++++-- crates/codecs/src/codecs/webp.rs | 7 +++++-- crates/codecs/src/options.rs | 29 +++++++++++++++++++++++++++-- crates/codecs/tests/limits.rs | 24 ++++++++++++++++++++++++ 4 files changed, 62 insertions(+), 6 deletions(-) diff --git a/crates/codecs/src/codecs/png.rs b/crates/codecs/src/codecs/png.rs index 636238a7bf..2544a1066d 100644 --- a/crates/codecs/src/codecs/png.rs +++ b/crates/codecs/src/codecs/png.rs @@ -7,7 +7,7 @@ use crate::Format; use crate::error::CodecError; use crate::fidelity::Plan; use crate::image::{ChannelLayout, DecodeWarning, Image, Metadata, SampleType}; -use crate::options::{EncodeOptions, Limits, PngCompression}; +use crate::options::{EncodeOptions, Limits, PngCompression, alloc_zeroed}; const F: Format = Format::Png; pub(crate) const XMP_KEYWORD: &str = "XML:com.adobe.xmp"; @@ -29,6 +29,10 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result let (w, h) = info.size(); // Worst case output: 4 channels x 16 bit. limits.check_bytes(w, h, 8)?; + // zlib never beats 1032:1; refuse a file too small for the declared image before the + // output buffer exists. Measured on the stored samples (before palette/bit expansion). + let stored = u64::from(w).saturating_mul(u64::from(h)).saturating_mul(info.bits_per_pixel() as u64).div_ceil(8); + Limits::check_plausible(stored, bytes.len(), 1100)?; } let mut reader = decoder.read_info().map_err(map_png_err)?; // APNG: the IDAT image is the first frame, or an extra default image when no fcTL precedes it. @@ -47,7 +51,7 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result d => return Err(err(format!("unexpected output bit depth {d:?}"))), }; let size = reader.output_buffer_size().ok_or_else(|| err("image too large"))?; - let mut buf = vec![0u8; size]; + let mut buf = alloc_zeroed::(size)?; let out = reader.next_frame(&mut buf).map_err(map_png_err)?; buf.truncate(out.buffer_size()); // Collect ancillary chunks after IDAT. Tolerate malformed tails once pixels diff --git a/crates/codecs/src/codecs/webp.rs b/crates/codecs/src/codecs/webp.rs index c26c10c8cd..36473041dd 100644 --- a/crates/codecs/src/codecs/webp.rs +++ b/crates/codecs/src/codecs/webp.rs @@ -9,7 +9,7 @@ use crate::Format; use crate::error::CodecError; use crate::fidelity::Plan; use crate::image::{ChannelLayout, DecodeWarning, Image, Metadata, SampleType}; -use crate::options::{EncodeOptions, Limits}; +use crate::options::{EncodeOptions, Limits, alloc_zeroed}; const F: Format = Format::WebP; @@ -23,8 +23,11 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result let (w, h) = dec.dimensions(); let layout = if dec.has_alpha() { ChannelLayout::Rgba } else { ChannelLayout::Rgb }; limits.check(w, h, layout, SampleType::U8)?; + // VP8L back-references and VP8 skipped macroblocks compress flat areas extremely well, so the + // ratio is generous; it still stops a header-only file from asking for a gigabyte. + Limits::check_plausible(u64::from(w) * u64::from(h) * layout.channels() as u64, bytes.len(), 1 << 16)?; let size = dec.output_buffer_size().ok_or_else(|| err("image too large"))?; - let mut buf = vec![0u8; size]; + let mut buf = alloc_zeroed::(size)?; dec.read_image(&mut buf).map_err(err)?; let icc = dec.icc_profile().ok().flatten(); let exif = dec.exif_metadata().ok().flatten(); diff --git a/crates/codecs/src/options.rs b/crates/codecs/src/options.rs index 79b288f34c..9337f1e6f1 100644 --- a/crates/codecs/src/options.rs +++ b/crates/codecs/src/options.rs @@ -21,8 +21,10 @@ pub struct Limits { impl Default for Limits { fn default() -> Self { // 2^30 pixels (e.g. 32768²) and, on 64-bit targets, 8 GiB: enough for the large - // documents Photoshop users open (a 20000² RGBA 16-bit image is 3.2 GB). - let max_alloc = if cfg!(target_pointer_width = "64") { 8 << 30 } else { 2 << 30 }; + // documents Photoshop users open (a 20000² RGBA 16-bit image is 3.2 GB). On 32-bit + // targets (wasm32 has a 4 GiB address space shared with the document, history and + // the decoder's own buffers) 1 GiB is the most one buffer can safely ask for. + let max_alloc = if cfg!(target_pointer_width = "64") { 8 << 30 } else { 1 << 30 }; Limits { max_width: 1 << 18, max_height: 1 << 18, max_pixels: 1 << 30, max_alloc } } } @@ -60,6 +62,19 @@ impl Limits { Ok(()) } + /// Decompression-bomb guard for formats that compress: refuse a file too small to hold + /// `declared_bytes` of (stored, pre-expansion) image data, given that the compression + /// never beats `max_ratio`:1. Called before the output buffer is allocated, so a + /// header-only hostile file cannot make the decoder reserve gigabytes. A fixed 1 MiB of + /// slack keeps tiny images and headers with large metadata unaffected. + pub(crate) fn check_plausible(declared_bytes: u64, file_len: usize, max_ratio: u64) -> Result<(), CodecError> { + let capacity = (file_len as u64).saturating_mul(max_ratio).saturating_add(1 << 20); + if declared_bytes > capacity { + return Err(CodecError::LimitExceeded(format!("a {file_len} byte file cannot hold {declared_bytes} bytes of image data"))); + } + Ok(()) + } + pub(crate) fn alloc_usize(&self) -> usize { usize::try_from(self.max_alloc).unwrap_or(usize::MAX) } @@ -149,3 +164,13 @@ impl Default for EncodeOptions { } } } + +/// A zero-filled buffer of `len` elements, allocated fallibly: an allocation failure becomes +/// [`CodecError::LimitExceeded`] instead of aborting the process (which `catch_unwind` cannot +/// stop). +pub(crate) fn alloc_zeroed(len: usize) -> Result, CodecError> { + let mut v = Vec::new(); + v.try_reserve_exact(len).map_err(|_| CodecError::LimitExceeded(format!("cannot allocate {len} elements for the image")))?; + v.resize(len, T::default()); + Ok(v) +} diff --git a/crates/codecs/tests/limits.rs b/crates/codecs/tests/limits.rs index 3613b0871d..6969fea922 100644 --- a/crates/codecs/tests/limits.rs +++ b/crates/codecs/tests/limits.rs @@ -93,6 +93,30 @@ fn png_bomb_header_rejected_before_alloc() { assert!(is_limit(decode(&b))); } +#[test] +fn png_header_at_the_default_limit_needs_a_plausible_file_size() { + // 32768 x 32768 x RGBA16 is exactly the default max_alloc: it passes the dimension limits, + // but a ~100 byte file cannot hold it (zlib tops out near 1032:1), so it is refused before + // the 8 GiB output buffer is allocated. + let mut ihdr = Vec::new(); + ihdr.extend_from_slice(&32768u32.to_be_bytes()); + ihdr.extend_from_slice(&32768u32.to_be_bytes()); + ihdr.extend_from_slice(&[16, 6, 0, 0, 0]); + let mut b = b"\x89PNG\r\n\x1a\n".to_vec(); + b.extend(png_chunk(b"IHDR", &ihdr)); + b.extend(png_chunk(b"IDAT", &[0x78, 0x9C, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01])); + b.extend(png_chunk(b"IEND", &[])); + assert!(is_limit(decode(&b))); +} + +#[test] +fn png_highly_compressible_image_still_decodes() { + let img = Image::from_u8(3000, 3000, ChannelLayout::Rgba, vec![255u8; 3000 * 3000 * 4]).unwrap(); + let b = encode(&img, Format::Png, &EncodeOptions::default()).unwrap(); + assert!(b.len() < 100_000, "{}", b.len()); + assert_eq!(decode(&b).unwrap().width(), 3000); +} + const PNG_TEXT_BUDGET: usize = 64 << 10; fn png_text_decode(bytes: &[u8], max_alloc: usize) -> Result { From 7893a6e04d71aa04cc96b4064ae90981581ea57b Mon Sep 17 00:00:00 2001 From: Valentin Klein Date: Mon, 12 Oct 2026 13:12:00 +0200 Subject: [PATCH 05/24] PSD: avoid cloning layer data when padding and presize the output buffer (#3687) (#3707) Co-authored-by: Claude Opus 5.5 --- crates/psd/src/file.rs | 4 +++ crates/psd/src/layer.rs | 60 ++++++++++++++++++++++++++++++++++++----- crates/psd/src/tiff.rs | 8 +++--- 3 files changed, 63 insertions(+), 9 deletions(-) diff --git a/crates/psd/src/file.rs b/crates/psd/src/file.rs index 3c621bb25a..330940e7a4 100644 --- a/crates/psd/src/file.rs +++ b/crates/psd/src/file.rs @@ -137,7 +137,11 @@ impl PsdFile { pub fn to_bytes(&self) -> Result> { let v = self.header.version; let psb = v.is_psb(); + // Reserve the pixel data up front: appending it to an empty Vec reallocates and copies + // repeatedly. Everything else (headers, resources, records) is small by comparison. + let hint = self.layer_info.as_ref().map_or(0, LayerInfo::channel_data_len).saturating_add(self.image_data.data.len()); let mut out = Vec::new(); + out.try_reserve(hint).map_err(|_| PsdError::LimitExceeded("not enough memory to serialize the file"))?; self.header.write(&mut out); out.put_len(self.color_mode_data.len() as u64, false)?; out.put(&self.color_mode_data); diff --git a/crates/psd/src/layer.rs b/crates/psd/src/layer.rs index cee6758268..5450ed7e67 100644 --- a/crates/psd/src/layer.rs +++ b/crates/psd/src/layer.rs @@ -684,15 +684,25 @@ impl LayerInfo { /// block in 4-byte units (psd-tools) misread the blocks after a body that /// is only padded to even. pub fn pad_to(&mut self, version: Version, align: u64) -> Result<()> { - let align = align.max(1); - let len = self.unpadded_len(version)?; - self.padding = Some(vec![0; ((align - len % align) % align) as usize]); + self.padding = Some(vec![0; self.pad_len(version, align)?]); Ok(()) } - /// Serializes the body (without a length field). - pub(crate) fn write_body(&self, out: &mut Vec, version: Version) -> Result<()> { - let start = out.len(); + /// Number of zero bytes [`Self::pad_to`] would set, without touching `self`. + pub(crate) fn pad_len(&self, version: Version, align: u64) -> Result { + let align = align.max(1); + let len = self.unpadded_len(version)?; + Ok(((align - len % align) % align) as usize) + } + + /// Bytes of channel data and their compression fields: the part of the body worth reserving up + /// front (the records are small next to the pixels). Saturates instead of overflowing. + pub(crate) fn channel_data_len(&self) -> usize { + self.layers.iter().flat_map(|l| &l.channels).filter(|c| c.compression.is_some()).fold(0usize, |n, c| n.saturating_add(2).saturating_add(c.data.len())) + } + + /// Serializes the body without any trailing padding (the padding field is ignored). + pub(crate) fn write_unpadded(&self, out: &mut Vec, version: Version) -> Result<()> { let n = i16::try_from(self.layers.len()).map_err(|_| PsdError::LimitExceeded("more than 32767 layers"))?; out.put_i16(if self.merged_alpha { -n } else { n }); for l in &self.layers { @@ -706,6 +716,13 @@ impl LayerInfo { } } } + Ok(()) + } + + /// Serializes the body (without a length field). + pub(crate) fn write_body(&self, out: &mut Vec, version: Version) -> Result<()> { + let start = out.len(); + self.write_unpadded(out, version)?; match &self.padding { Some(p) => out.put(p), None => { @@ -1022,6 +1039,37 @@ mod tests { assert_eq!(info.layers[0].decode_channel(0, 8, Version::Psd).unwrap(), Vec::::new()); } + /// Padding without cloning the layers writes the same bytes as `pad_to` on a clone, and the + /// channel data length hint is exact. + #[test] + fn unpadded_write_matches_pad_to_on_a_clone() { + use crate::{ColorMode, Compression, testgen}; + for version in [Version::Psd, Version::Psb] { + for depth in [8u16, 16, 32] { + for compression in [Compression::Raw, Compression::Rle] { + let file = testgen::layered(version, ColorMode::Rgb, depth, compression); + let mut info = file.layer_info.clone().unwrap(); + for align in [1u64, 2, 4, 8] { + let mut cloned = info.clone(); + cloned.pad_to(version, align).unwrap(); + let mut want = Vec::new(); + cloned.write_body(&mut want, version).unwrap(); + let pad = info.pad_len(version, align).unwrap(); + let mut got = Vec::new(); + info.write_unpadded(&mut got, version).unwrap(); + assert!(got.len() >= info.channel_data_len()); + got.resize(got.len() + pad, 0); + assert_eq!(got, want, "{version:?} {depth} {compression:?} align {align}"); + } + info.padding = Some(vec![7, 7]); + let mut with_padding = Vec::new(); + info.write_body(&mut with_padding, version).unwrap(); + assert!(with_padding.ends_with(&[7, 7])); + } + } + } + } + #[test] fn nondefault_padding_kept() { let info = LayerInfo { padding: Some(vec![0, 0]), ..Default::default() }; diff --git a/crates/psd/src/tiff.rs b/crates/psd/src/tiff.rs index 0d8f36888a..7c8b1940d5 100644 --- a/crates/psd/src/tiff.rs +++ b/crates/psd/src/tiff.rs @@ -155,10 +155,12 @@ impl ImageSourceData { let version = self.version; let mut blocks = Vec::with_capacity(self.global_blocks.len() + 2); if let Some(info) = &self.layer_info { - let mut info = info.clone(); - info.pad_to(version, 4)?; + // Pad to 4 without cloning the layers (and all their pixel data) just to set `padding`. + let pad = info.pad_len(version, 4)?; let mut data = Vec::new(); - info.write_body(&mut data, version)?; + data.try_reserve(info.channel_data_len().saturating_add(pad)).map_err(|_| PsdError::LimitExceeded("not enough memory for the layer data"))?; + info.write_unpadded(&mut data, version)?; + data.resize(data.len() + pad, 0); blocks.push(padded_block(self.layer_info_key, data)); } if let Some(m) = &self.global_layer_mask { From 476f9838765f619dd3c5d93ddac8e6a5d2e10f5d Mon Sep 17 00:00:00 2001 From: Valentin Klein Date: Mon, 12 Oct 2026 13:12:13 +0200 Subject: [PATCH 06/24] Codecs: bound the TIFF IFD walk by a file-size entry budget (#3683) (#3711) Co-authored-by: Claude Opus 5.5 --- crates/codecs/src/codecs/tiff_ifd.rs | 50 +++++++++++++++++++++++++++- 1 file changed, 49 insertions(+), 1 deletion(-) diff --git a/crates/codecs/src/codecs/tiff_ifd.rs b/crates/codecs/src/codecs/tiff_ifd.rs index 45fe9ee753..199d44ecc7 100644 --- a/crates/codecs/src/codecs/tiff_ifd.rs +++ b/crates/codecs/src/codecs/tiff_ifd.rs @@ -145,6 +145,14 @@ impl<'a> File<'a> { Some(if self.le { u64::from_le_bytes(s) } else { u64::from_be_bytes(s) }) } + /// The declared entry count of the directory at `at`, before its table is parsed. + pub fn entry_count(&self, at: u64) -> Option { + if at < self.header_len() { + return None; + } + if self.big { self.u64_at(at) } else { self.u16_at(at).map(u64::from) } + } + /// The directory at `at`: its whole table, up to and including the next-IFD pointer, must /// be inside the file and after the header. pub fn ifd(&self, at: u64) -> Option { @@ -355,6 +363,10 @@ struct Walk<'a, 'f> { seen: HashSet, pages: Vec, complete: bool, + /// Directory entries that may still be parsed. Real directory tables are disjoint, so their + /// total size is bounded by the file; overlapping tables (a hostile file) would otherwise + /// make every one of thousands of directories cost a full 65,535-entry parse. + entry_budget: u64, } impl Walk<'_, '_> { @@ -366,6 +378,15 @@ impl Walk<'_, '_> { self.complete = false; return; } + let Some(n) = self.f.entry_count(at) else { + self.complete = false; + return; + }; + if n > self.entry_budget { + self.complete = false; + return; + } + self.entry_budget -= n; let Some(ifd) = self.f.ifd(at) else { self.complete = false; return; @@ -391,10 +412,37 @@ pub fn tiff_info(bytes: &[u8]) -> Result { } pub(crate) fn info_of(f: &File<'_>) -> Result { - let mut w = Walk { f, seen: HashSet::new(), pages: Vec::new(), complete: true }; + let mut w = Walk { f, seen: HashSet::new(), pages: Vec::new(), complete: true, entry_budget: (f.b.len() as u64) / 12 + 64 }; w.chain(f.first_ifd, None, 0); if w.pages.is_empty() { return Err(CodecError::malformed(Format::Tiff, "the first image directory is missing or cut off")); } Ok(TiffInfo { big_tiff: f.big, little_endian: f.le, pages: w.pages, complete: w.complete }) } + +#[cfg(test)] +mod tests { + use super::*; + + /// 10,000 directories 4 bytes apart, each declaring 65,535 overlapping entries: the walk must + /// stop after the file-size entry budget instead of parsing ~6.5e8 entries. + #[test] + fn overlapping_directory_tables_exhaust_the_entry_budget() { + let first = 8usize; + let table = 2 + 65_535 * 12 + 4; + let mut b = vec![0u8; first + table + 4 * 10_000]; + b[..8].copy_from_slice(&[b'I', b'I', 42, 0, first as u8, 0, 0, 0]); + for i in 0..10_000usize { + let at = first + 4 * i; + b[at..at + 2].copy_from_slice(&u16::MAX.to_le_bytes()); + let next_cell = at + 2 + 65_535 * 12; + let next = (first + 4 * (i + 1)) as u32; + if let Some(cell) = b.get_mut(next_cell..next_cell + 4) { + cell.copy_from_slice(&next.to_le_bytes()); + } + } + let info = tiff_info(&b).expect("the first directory is readable"); + assert!(!info.complete); + assert!(info.pages.len() < 200, "{} directories parsed", info.pages.len()); + } +} From e156a9ed85821fbd094d9700c03be11e3c4d2a8b Mon Sep 17 00:00:00 2001 From: Streetblock Date: Mon, 12 Oct 2026 13:12:34 +0200 Subject: [PATCH 07/24] perf(compose): select Normal RGB kernel once per buffer (#3715) --- crates/compose/src/lib.rs | 12 +++ crates/compose/src/psblend.rs | 31 ++++++-- crates/compose/src/tests.rs | 141 ++++++++++++++++++++++++++++++++++ 3 files changed, 177 insertions(+), 7 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index a7c0576103..01087f4937 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -1674,6 +1674,18 @@ fn blend_into_fill(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity /// [`blend_into`] mixing coverage in a `gamma` space (type layers). fn blend_into_g(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity: f32, gamma: f32) { + // The blend space is constant in this loop. Some TLS implementations synchronise even a + // boolean read, so select the common Normal kernel once instead of once per pixel. + if mode == BlendMode::Normal && gamma == 1.0 && !psblend::LAB_MIX.with(|l| l.get()) { + for (i, b) in backdrop.px.iter_mut().enumerate() { + let s = src.px[i]; + if s[3] <= 0.0 { + continue; + } + *b = psblend::composite_normal_rgb(*b, s, opacity); + } + return; + } let rect = backdrop.rect; let w = rect.width() as i32; for (i, b) in backdrop.px.iter_mut().enumerate() { diff --git a/crates/compose/src/psblend.rs b/crates/compose/src/psblend.rs index afd8412347..4cff6f3082 100644 --- a/crates/compose/src/psblend.rs +++ b/crates/compose/src/psblend.rs @@ -210,13 +210,7 @@ pub fn composite(mode: BlendMode, backdrop: [f32; 4], source: [f32; 4], opacity: return [r[0], r[1], r[2], ao]; } if mode == BlendMode::Normal { - // Fast path: B(Cb, Cs) = Cs. - if ao <= 0.0 { - return [0.0; 4]; - } - let kb = ab * (1.0 - as_); - let inv = 1.0 / ao; - return [(kb * backdrop[0] + as_ * source[0]) * inv, (kb * backdrop[1] + as_ * source[1]) * inv, (kb * backdrop[2] + as_ * source[2]) * inv, ao]; + return normal_rgb(backdrop, source, as_, ao); } let cb = [backdrop[0], backdrop[1], backdrop[2]]; let cs = [source[0], source[1], source[2]]; @@ -232,6 +226,29 @@ pub fn composite(mode: BlendMode, backdrop: [f32; 4], source: [f32; 4], opacity: out } +/// Normal mixing outside Lab, for callers that select the blend space once per buffer. +#[inline] +pub(crate) fn composite_normal_rgb(backdrop: [f32; 4], source: [f32; 4], opacity: f32) -> [f32; 4] { + let ab = backdrop[3]; + let as_ = source[3] * opacity; + if as_ <= 0.0 { + return backdrop; + } + let ao = as_ + ab * (1.0 - as_); + normal_rgb(backdrop, source, as_, ao) +} + +#[inline] +fn normal_rgb(backdrop: [f32; 4], source: [f32; 4], as_: f32, ao: f32) -> [f32; 4] { + // B(Cb, Cs) = Cs. Keep the scalar composite's operation order and straight alpha. + if ao <= 0.0 { + return [0.0; 4]; + } + let kb = backdrop[3] * (1.0 - as_); + let inv = 1.0 / ao; + [(kb * backdrop[0] + as_ * source[0]) * inv, (kb * backdrop[1] + as_ * source[1]) * inv, (kb * backdrop[2] + as_ * source[2]) * inv, ao] +} + /// Photoshop's "Blend Text Colors Using Gamma" (Color Settings › Advanced, on at 1.45 by /// default): type layers mix their colour with the backdrop in linear light raised to 1 / 1.45 /// ([`text_encode`]), so anti-aliased glyph edges come out lighter over dark backdrops than a diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index c56b7de49d..869c316dd7 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -40,6 +40,147 @@ fn normal_layer_over_background() { assert!(close4(px(&d, 5, 1), [1.0; 4])); } +// The pre-optimisation Normal formula, independent of the production helper. Its operation +// order matters: an algebraically equivalent premultiplied mix can round differently. +fn original_normal_rgb(backdrop: [f32; 4], source: [f32; 4], opacity: f32) -> [f32; 4] { + let ab = backdrop[3]; + let as_ = source[3] * opacity; + if as_ <= 0.0 { + return backdrop; + } + let ao = as_ + ab * (1.0 - as_); + if ao <= 0.0 { + return [0.0; 4]; + } + let kb = ab * (1.0 - as_); + let inv = 1.0 / ao; + [(kb * backdrop[0] + as_ * source[0]) * inv, (kb * backdrop[1] + as_ * source[1]) * inv, (kb * backdrop[2] + as_ * source[2]) * inv, ao] +} + +#[test] +fn normal_rgb_kernel_preserves_scalar_bits() { + let subnormal = f32::from_bits(1); + let backdrops = [[0.0, -0.0, 2.0, 0.0], [0.2, 0.4, 0.6, 0.5], [2.0, -0.25, 4.0, 1.0], [-1.0, 0.01, 1.0, -0.5], [1.0, -0.0, f32::MIN_POSITIVE, subnormal]]; + let sources = [ + [0.9, 0.1, 0.3, 1.0], + [0.25, 2.0, -1.0, 0.5], + [subnormal, 1e-20, 1.0, subnormal], + [0.5, 0.2, 0.7, -0.0], + [0.5, 0.2, 0.7, -0.5], + [f32::NAN, 0.2, 0.7, 0.0], + ]; + for b in backdrops { + for s in sources { + for opacity in [-1.0, -0.0, 0.0, 0.5, 1.0, 2.0] { + let want = original_normal_rgb(b, s, opacity); + let got = psblend::composite_normal_rgb(b, s, opacity); + assert_eq!(got.map(f32::to_bits), want.map(f32::to_bits), "{b:?} / {s:?} / {opacity}"); + } + } + } +} + +fn normal_rgb_test_buffers(fmt: PixelFormat) -> (Buffer, Buffer) { + let rect = Rect::new(-3, -2, 5, 0); + let mut bottom = Surface::new(fmt); + let mut top = Surface::new(fmt); + for y in rect.y0..rect.y1 { + for x in rect.x0..rect.x1 { + let i = ((y - rect.y0) * rect.width() as i32 + x - rect.x0) as usize; + let t = i as f32 / 16.0; + let b = [2.0 * t, 0.4, -0.25 + t, [0.0, 0.25, 0.75, 1.0][i % 4]]; + let s = [0.9 - t, 0.1 + t, 0.3, [0.0, -0.0, 0.5, 1.0][i % 4]]; + bottom.write_pixel(x, y, &photocraft_raster::from_rgba(&fmt, b)); + top.write_pixel(x, y, &photocraft_raster::from_rgba(&fmt, s)); + } + } + (surface_to_buffer(&bottom, rect), surface_to_buffer(&top, rect)) +} + +// Keep the old buffer dispatch as an oracle for the specialised loop and all of its fallbacks. +fn original_blend_into_g(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity: f32, gamma: f32) { + let rect = backdrop.rect; + let w = rect.width() as i32; + for (i, b) in backdrop.px.iter_mut().enumerate() { + let mut s = src.px[i]; + if s[3] <= 0.0 { + continue; + } + let mut mode = mode; + if mode == BlendMode::Dissolve { + let x = rect.x0 + (i as i32 % w); + let y = rect.y0 + (i as i32 / w); + s[3] = if dissolve_noise(x, y) < s[3] * opacity { 1.0 } else { 0.0 }; + mode = BlendMode::Normal; + *b = blend::composite(mode, *b, s, 1.0); + continue; + } + *b = blend::composite_gamma(mode, *b, s, opacity, gamma); + } +} + +fn assert_buffer_bits(got: &Buffer, want: &Buffer) { + assert_eq!(got.rect, want.rect); + assert_eq!(got.px.len(), want.px.len()); + for (i, (got, want)) in got.px.iter().zip(&want.px).enumerate() { + assert_eq!(got.map(f32::to_bits), want.map(f32::to_bits), "pixel {i}: {got:?} vs {want:?}"); + } +} + +#[test] +fn normal_rgb_buffer_dispatch_and_fallbacks_preserve_bits() { + for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F] { + let (bottom, top) = normal_rgb_test_buffers(fmt); + for lab in [false, true] { + psblend::with_lab_mix(lab, || { + psblend::with_hdr(fmt.sample == SampleType::F32, || { + for mode in BlendMode::LAYER_MODES { + for gamma in [1.0, psblend::TEXT_GAMMA] { + for opacity in [0.0, 0.5, 1.0] { + let mut got = bottom.clone(); + let mut want = bottom.clone(); + original_blend_into_g(&mut want, &top, mode, opacity, gamma); + blend_into_g(&mut got, &top, mode, opacity, gamma); + assert_buffer_bits(&got, &want); + } + } + } + }); + }); + } + } +} + +#[test] +fn normal_rgb_buffer_preserves_alpha_skip_and_nested_scopes() { + let rect = Rect::new(-1, -1, 2, 0); + let bottom = Buffer::filled(rect, [-0.0, 0.4, 2.0, 0.75]); + let top = Buffer { rect, px: vec![[f32::NAN, 0.3, 0.1, -0.5], [0.2, 0.3, 0.1, -0.0], [0.2, 0.3, 0.1, f32::NAN]] }; + psblend::with_lab_mix(true, || { + psblend::with_hdr(true, || { + psblend::with_lab_mix(false, || { + psblend::with_hdr(false, || { + let mut got = bottom.clone(); + let mut want = bottom.clone(); + original_blend_into_g(&mut want, &top, BlendMode::Normal, -1.0, 1.0); + blend_into_g(&mut got, &top, BlendMode::Normal, -1.0, 1.0); + assert_buffer_bits(&got, &want); + assert_eq!(got.px[0].map(f32::to_bits), bottom.px[0].map(f32::to_bits)); + assert_eq!(got.px[1].map(f32::to_bits), bottom.px[1].map(f32::to_bits)); + }); + assert!(psblend::HDR.with(|h| h.get())); + }); + assert!(psblend::LAB_MIX.with(|l| l.get())); + assert!(psblend::HDR.with(|h| h.get())); + let mut got = bottom.clone(); + let mut want = bottom.clone(); + original_blend_into_g(&mut want, &top, BlendMode::Normal, 0.5, 1.0); + blend_into_g(&mut got, &top, BlendMode::Normal, 0.5, 1.0); + assert_buffer_bits(&got, &want); + }); + }); +} + #[test] fn opacity_and_fill_multiply() { let mut d = doc_white(4, 4); From 38236f90c24a1fd7f89094a4a1193be0690f08e1 Mon Sep 17 00:00:00 2001 From: Streetblock Date: Mon, 12 Oct 2026 13:12:47 +0200 Subject: [PATCH 08/24] perf(compose): allow empty vector masks in preview proxies (#3716) --- crates/compose/src/proxy.rs | 167 +++++++++++++++++++++++++++++++++++- 1 file changed, 165 insertions(+), 2 deletions(-) diff --git a/crates/compose/src/proxy.rs b/crates/compose/src/proxy.rs index 5560fae374..4fe3b879fb 100644 --- a/crates/compose/src/proxy.rs +++ b/crates/compose/src/proxy.rs @@ -83,15 +83,52 @@ pub fn proxy_document(doc: &Document, k: u32) -> Document { } /// Whether a proxy composite is a faithful reduction of `doc`: layer effects (whose sizes are in -/// document pixels) and vector masks (paths in document coordinates) would not scale with it. +/// document pixels) and nonempty vector masks (paths in document coordinates) would not scale +/// with it. Empty vector masks have constant coverage, including inversion and density. +/// Nonempty paths can still anchor fill layouts even when their mask density is zero. pub fn proxy_faithful(doc: &Document) -> bool { - doc.walk().iter().all(|(_, _, l)| !crate::effects::has_effects(l) && l.vector_mask.as_ref().is_none_or(|v| !v.enabled)) + doc.walk().iter().all(|(_, _, l)| !crate::effects::has_effects(l) && l.vector_mask.as_ref().is_none_or(|v| !v.enabled || v.path.is_empty())) } #[cfg(test)] mod tests { use super::*; use photocraft_color::{Color, ColorMode, PixelFormat, SampleType}; + use photocraft_doc::vector::{Knot, Path, Subpath, VectorMask}; + use photocraft_doc::{Effect, Fill, GradientStyle, LayerMask}; + + fn two_colors(size: Size, depth: SampleType) -> Document { + let mut doc = Document::new("mask", size, ColorMode::Rgb, depth); + let format = doc.pixel_format(); + for (name, color) in [("blue", [0.0, 0.0, 1.0, 1.0]), ("red", [1.0, 0.0, 0.0, 1.0])] { + doc.layers.push(Layer::new(name, LayerContent::Raster(Surface::with_default(format, &color)))); + } + doc + } + + fn assert_same_pixels(actual: &crate::Buffer, expected: &crate::Buffer) { + assert_same_pixels_within(actual, expected, 1e-6); + } + + fn assert_same_pixels_within(actual: &crate::Buffer, expected: &crate::Buffer, tolerance: f32) { + assert_eq!(actual.rect, expected.rect); + assert_eq!(actual.px.len(), expected.px.len()); + for (a, b) in actual.px.iter().zip(&expected.px) { + assert!(a.iter().zip(b).all(|(a, b)| (a - b).abs() <= tolerance), "{a:?} != {b:?}"); + } + } + + fn u16_coverage(value: f32) -> f32 { + // Feathered masks use the existing U16 combined-mask surface, including its default. + (value.clamp(0.0, 1.0) * 65535.0 + 0.5).floor() / 65535.0 + } + + fn opacity_reference(doc: &Document, coverage: f32) -> Document { + let mut reference = doc.clone(); + reference.layers[1].vector_mask = None; + reference.layers[1].opacity *= coverage; + reference + } #[test] fn downsample_picks_every_kth_pixel() { @@ -134,4 +171,130 @@ mod tests { assert_eq!((s.pixel(7, 15)[0], s.pixel(8, 0)[0]), (1.0, 0.0)); assert!(proxy_document(&Document::new("n", Size::new(8, 8), ColorMode::Rgb, SampleType::U8), 4).selection.is_none()); } + + #[test] + fn proxy_accepts_empty_paths_but_keeps_geometry_and_effect_guards() { + let mut doc = two_colors(Size::new(32, 16), SampleType::F32); + doc.layers[1].vector_mask = Some(VectorMask::new(Path::new(vec![Subpath::default()]))); + assert!(proxy_faithful(&doc)); + // A lone knot has no fillable segments, but still carries document coordinates. + doc.layers[1].vector_mask.as_mut().unwrap().path.subpaths[0].knots.push(Knot::corner(12.0, 8.0)); + assert!(!proxy_faithful(&doc)); + doc.layers[1].vector_mask.as_mut().unwrap().enabled = false; + assert!(proxy_faithful(&doc)); + doc.layers[1].vector_mask = Some(VectorMask::new(Path::default())); + doc.layers[1].effects.items.push(Effect::default_drop_shadow()); + doc.layers[1].effects.enabled = true; + assert!(!proxy_faithful(&doc)); + doc.layers[1].effects.items[0].set_enabled(false); + assert!(proxy_faithful(&doc)); + } + + #[test] + fn empty_vector_masks_keep_constant_coverage_at_every_depth() { + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + let mut doc = two_colors(Size::new(32, 16), depth); + for path in [Path::default(), Path::new(vec![Subpath::default()])] { + for inverted in [false, true] { + for density in [0.0, 0.25, 1.0] { + for feather in [0.0, 4.0] { + let mut mask = VectorMask::new(path.clone()); + mask.path.inverted = inverted; + mask.density = density; + mask.feather = feather; + doc.layers[1].vector_mask = Some(mask); + assert!(proxy_faithful(&doc)); + let coverage = if inverted { 1.0 - density } else { 1.0 }; + let coverage = if feather > 0.0 { u16_coverage(coverage) } else { coverage }; + let expected = [coverage, 0.0, 1.0 - coverage, 1.0]; + let full = crate::render(&doc, doc.bounds()); + for pixel in &full.px { + assert!(pixel.iter().zip(expected).all(|(a, b)| (a - b).abs() < 1e-6), "{depth:?} {inverted} {density} {feather}: {pixel:?}"); + } + let proxy = proxy_document(&doc, 4); + assert_eq!(proxy.layers[1].vector_mask, doc.layers[1].vector_mask); + let reference = proxy_document(&opacity_reference(&doc, coverage), 4); + assert_same_pixels(&crate::render(&proxy, proxy.bounds()), &crate::render(&reference, reference.bounds())); + } + } + } + } + } + } + + #[test] + fn empty_vector_mask_multiplies_a_feathered_pixel_mask_on_the_proxy() { + let mut doc = two_colors(Size::new(32, 16), SampleType::F32); + let mut surface = Surface::with_default(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false), &[0.25]); + surface.fill_rect(Rect::new(0, 0, 16, 16), &[0.75]); + doc.layers[1].mask = Some(LayerMask { surface, density: 0.5, feather: 2.0, ..LayerMask::reveal_all() }); + let mut mask = VectorMask::new(Path { inverted: true, ..Path::default() }); + mask.density = 0.75; + mask.feather = 8.0; + doc.layers[1].vector_mask = Some(mask); + assert!(proxy_faithful(&doc)); + let reference = opacity_reference(&doc, 0.25); + for k in [1, 2, 4] { + let (actual, expected) = (proxy_document(&doc, k), proxy_document(&reference, k)); + // Q(0.25 * pixel) versus 0.25 * Q(pixel): U16 rounding differs by at most + // 0.625 / 65535. Allow one U16 level plus a small float arithmetic allowance. + assert_same_pixels_within(&crate::render(&actual, actual.bounds()), &crate::render(&expected, expected.bounds()), 1.0 / 65535.0 + 1e-6); + } + } + + #[test] + fn empty_vector_masks_keep_the_pixel_mask_gradient_frame() { + let mut doc = two_colors(Size::new(32, 16), SampleType::F32); + doc.layers[1].content = LayerContent::Fill(Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 0.0, 1.0, GradientStyle::Linear, false)); + let mut pixel = LayerMask::hide_all(); + pixel.surface.fill_rect(Rect::new(8, 4, 24, 12), &[1.0]); + doc.layers[1].mask = Some(pixel); + for inverted in [false, true] { + let mut mask = VectorMask::new(Path { inverted, ..Path::default() }); + mask.density = 0.5; + mask.feather = 3.0; + doc.layers[1].vector_mask = Some(mask); + assert!(proxy_faithful(&doc)); + assert_eq!(crate::fill_frame(&doc.layers[1], doc.bounds()), Rect::new(8, 4, 24, 12)); + let actual = proxy_document(&doc, 4); + assert_eq!(crate::fill_frame(&actual.layers[1], actual.bounds()), Rect::new(2, 1, 6, 3)); + let reference = proxy_document(&opacity_reference(&doc, u16_coverage(if inverted { 0.5 } else { 1.0 })), 4); + assert_same_pixels(&crate::render(&actual, actual.bounds()), &crate::render(&reference, reference.bounds())); + } + } + + #[test] + fn zero_density_geometry_still_blocks_the_proxy_and_anchors_a_gradient() { + let mut doc = Document::new("gradient", Size::new(64, 32), ColorMode::Rgb, SampleType::F32); + let fill = Fill::gradient(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], 0.0, 1.0, GradientStyle::Linear, false); + let mut layer = Layer::new("gradient", LayerContent::Fill(fill)); + let path = Path::new(vec![Subpath::polygon(&[(16.0, 8.0), (48.0, 8.0), (48.0, 24.0), (16.0, 24.0)])]); + let mut mask = VectorMask::new(path); + mask.density = 0.0; + layer.vector_mask = Some(mask); + doc.layers.push(layer); + assert!(!proxy_faithful(&doc)); + assert_eq!(crate::fill_frame(&doc.layers[0], doc.bounds()), Rect::new(16, 8, 48, 24)); + // Density zero reveals all pixels, but the unscaled path would still move the fill. + let forced_proxy = proxy_document(&doc, 4); + let exact = crate::render_reduced(&doc, 16, 8); + let wrong = crate::render(&forced_proxy, forced_proxy.bounds()); + assert!(exact.px.iter().zip(&wrong.px).any(|(a, b)| (a[0] - b[0]).abs() > 0.1)); + } + + #[test] + fn large_thumbnail_keeps_inverted_empty_mask_coverage() { + // Default-only surfaces exercise the large-document branch without allocating 17 MP. + let mut doc = two_colors(Size::new(4200, 4200), SampleType::F32); + let mut mask = VectorMask::new(Path { inverted: true, ..Path::default() }); + mask.density = 0.75; + mask.feather = 8.0; + doc.layers[1].vector_mask = Some(mask); + assert!(doc.size.area() > crate::PROXY_THUMBNAIL_PIXELS); + assert!(proxy_faithful(&doc)); + let actual = crate::thumbnail_buffer(&doc, 4); + assert_eq!(actual.rect, Rect::new(0, 0, 4, 4)); + let coverage = u16_coverage(0.25); + assert_eq!(actual.px, vec![[coverage, 0.0, 1.0 - coverage, 1.0]; 16]); + } } From e54adc250c5c706b1c3b1d6f633e38d8257c41ca Mon Sep 17 00:00:00 2001 From: Nigel Ihza Firdausy <106657905+Ni-zav@users.noreply.github.com> Date: Mon, 12 Oct 2026 18:12:55 +0700 Subject: [PATCH 09/24] feat(codecs): decode legacy PCX images and palettes (#3692) (#3701) Co-authored-by: Brandon Thomas Co-authored-by: Claude Opus 5.5 --- apps/photocraft/src/services.rs | 4 +- crates/codecs/src/codecs/mod.rs | 1 + crates/codecs/src/codecs/pcx.rs | 118 ++++++++++++++++++++++++++++++++ crates/codecs/src/format.rs | 16 ++++- crates/codecs/src/lib.rs | 4 +- crates/codecs/tests/pcx.rs | 100 +++++++++++++++++++++++++++ 6 files changed, 239 insertions(+), 4 deletions(-) create mode 100644 crates/codecs/src/codecs/pcx.rs create mode 100644 crates/codecs/tests/pcx.rs diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index 0b1a366a69..f6695717be 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -21,8 +21,8 @@ mod recovery_tests; /// (.kys), which go to the preset libraries and Edit › Keyboard Shortcuts. const OPEN_EXTS: &[&str] = &[ "pcraft", "pdn", "ora", "kra", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", "pbm", - "pgm", "ppm", "pam", "pfm", "fits", "fit", "fts", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", - "grd", "svg", "svgz", "aco", "ase", "kys", "af", "afdesign", "afphoto", "afpub", + "pgm", "ppm", "pam", "pfm", "pcx", "fits", "fit", "fts", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", + "abr", "grd", "svg", "svgz", "aco", "ase", "kys", "af", "afdesign", "afphoto", "afpub", ]; const SVG_EXTS: &[&str] = &["svg", "svgz"]; diff --git a/crates/codecs/src/codecs/mod.rs b/crates/codecs/src/codecs/mod.rs index ea70ccc2b8..22845d930b 100644 --- a/crates/codecs/src/codecs/mod.rs +++ b/crates/codecs/src/codecs/mod.rs @@ -5,6 +5,7 @@ pub(crate) mod fits; pub(crate) mod gif_frames; pub(crate) mod heif; pub(crate) mod jpeg; +pub(crate) mod pcx; pub(crate) mod png; pub(crate) mod pnm; pub(crate) mod tiff; diff --git a/crates/codecs/src/codecs/pcx.rs b/crates/codecs/src/codecs/pcx.rs new file mode 100644 index 0000000000..43a3e97302 --- /dev/null +++ b/crates/codecs/src/codecs/pcx.rs @@ -0,0 +1,118 @@ +//! ZSoft PCX (Paintbrush) reader: strictly bounded scanline RLE, 16/256-colour +//! palettes and 8-bit three-plane RGB. Read-only: modern saves should use PNG. + +use crate::SampleType; +use crate::error::CodecError; +use crate::format::Format; +use crate::image::{ChannelLayout, Image}; +use crate::options::Limits; + +const HEADER: usize = 128; + +fn bad(reason: impl std::fmt::Display) -> CodecError { + CodecError::malformed(Format::Pcx, reason) +} +fn le16(b: &[u8], i: usize) -> u16 { + u16::from_le_bytes([b[i], b[i + 1]]) +} + +/// PCX lacks a strong magic number. Require plausible complete header fields before +/// identifying it, rather than classifying every file starting with 0x0a as PCX. +pub(crate) fn looks_like_pcx(b: &[u8]) -> bool { + if b.len() < HEADER || b[0] != 0x0a || !matches!(b[1], 0 | 2 | 3 | 5) || b[2] != 1 { + return false; + } + let bits = b[3]; + let planes = b[65]; + let stride = u32::from(le16(b, 66)); + let (x0, y0, x1, y1) = (le16(b, 4), le16(b, 6), le16(b, 8), le16(b, 10)); + if x1 < x0 || y1 < y0 || !matches!(bits, 1 | 2 | 4 | 8) || !(1..=4).contains(&planes) { + return false; + } + let width = u32::from(x1 - x0) + 1; + let min_stride = (width * u32::from(bits)).div_ceil(8); + stride >= min_stride && stride > 0 && (bits != 8 || matches!(planes, 1 | 3)) && (bits == 8 || u32::from(bits) * u32::from(planes) <= 4) +} + +/// Read one compressed plane's row. RLE packets never cross a scanline. +fn read_row(b: &[u8], pos: &mut usize, out: &mut [u8]) -> Result<(), CodecError> { + let mut n = 0; + while n < out.len() { + let code = *b.get(*pos).ok_or_else(|| bad("truncated pixel RLE"))?; + *pos += 1; + let (count, value) = if code >= 0xc0 { + let count = usize::from(code & 0x3f); + let value = *b.get(*pos).ok_or_else(|| bad("truncated RLE packet"))?; + *pos += 1; + (count, value) + } else { + (1, code) + }; + if count == 0 || count > out.len() - n { + return Err(bad("RLE packet crosses a scanline or has zero length")); + } + out[n..n + count].fill(value); + n += count; + } + Ok(()) +} + +pub(crate) fn decode(b: &[u8], limits: &Limits) -> Result { + if !looks_like_pcx(b) { + return Err(bad("invalid PCX header or unsupported pixel layout")); + } + let (w, h) = (u32::from(le16(b, 8) - le16(b, 4)) + 1, u32::from(le16(b, 10) - le16(b, 6)) + 1); + limits.check(w, h, ChannelLayout::Rgb, SampleType::U8)?; + let (bits, planes, stride) = (usize::from(b[3]), usize::from(b[65]), usize::from(le16(b, 66))); + let row_len = stride.checked_mul(planes).ok_or_else(|| bad("row size overflow"))?; + let total = (w as usize).checked_mul(h as usize).and_then(|n| n.checked_mul(3)).ok_or_else(|| bad("pixel size overflow"))?; + // The last 769 bytes are the optional VGA palette for 8-bit indexed images. + let vga = bits == 8 && planes == 1 && b.len() >= HEADER + 769 && b[b.len() - 769] == 0x0c; + if bits == 8 && planes == 1 && !vga && le16(b, 68) != 2 { + return Err(bad("8-bit indexed PCX has no 256-colour palette")); + } + let image_end = if vga { b.len() - 769 } else { b.len() }; + let mut row = vec![0u8; row_len]; + let mut pixels = vec![0u8; total]; + let mut p = HEADER; + let width = w as usize; + for y in 0..h as usize { + for plane in row.chunks_mut(stride) { + read_row(&b[..image_end], &mut p, plane)?; + } + for x in 0..width { + let rgb = if bits == 8 && planes == 3 { + [row[x], row[stride + x], row[2 * stride + x]] + } else { + let index = if bits == 8 { + usize::from(row[x]) + } else { + let bit = x * bits; + let shift = 8 - bits - (bit % 8); + let mask = (1usize << bits) - 1; + (0..planes).fold(0usize, |v, plane| { + let sample = (usize::from(row[plane * stride + bit / 8]) >> shift) & mask; + v | sample << (plane * bits) + }) + }; + if vga { + let o = image_end + 1 + index * 3; + [b[o], b[o + 1], b[o + 2]] + } else if bits == 8 { + let g = index as u8; + [g, g, g] // palette-info 2: gray scale + } else { + let o = 16 + index * 3; + [b[o], b[o + 1], b[o + 2]] + } + }; + pixels[(y * width + x) * 3..(y * width + x + 1) * 3].copy_from_slice(&rgb); + } + } + let mut image = Image::from_u8(w, h, ChannelLayout::Rgb, pixels)?; + let (xdpi, ydpi) = (le16(b, 12), le16(b, 14)); + if xdpi > 0 && ydpi > 0 { + image.meta.dpi = Some((f32::from(xdpi), f32::from(ydpi))); + } + Ok(image) +} diff --git a/crates/codecs/src/format.rs b/crates/codecs/src/format.rs index 3d3fa5426e..ddb7587141 100644 --- a/crates/codecs/src/format.rs +++ b/crates/codecs/src/format.rs @@ -15,6 +15,8 @@ pub enum Format { Ico, /// Netpbm family: PBM/PGM/PPM (P1–P6), PAM (P7) and PFM (`PF`/`Pf`). Pnm, + /// ZSoft Paintbrush: 1/2/4-bit planar palettes, 8-bit indexed and 24-bit RGB. + Pcx, Qoi, OpenExr, /// Radiance RGBE. @@ -56,6 +58,10 @@ pub struct FormatCaps { /// Formats that are enabled but intentionally not symmetric, with the reason. /// The test-suite asserts that every other enabled format is read+write. pub const ASYMMETRIC_EXCEPTIONS: &[(Format, &str)] = &[ + ( + Format::Pcx, + "PCX is supported for opening legacy paint and clipart assets. New files should use PNG; writing obsolete indexed and planar variants is intentionally not provided.", + ), ( Format::Avif, "AVIF encode uses ravif (pure Rust) but decoding requires dav1d (C); read stays unsupported \ @@ -78,7 +84,7 @@ const ALL_LAYOUTS: &[ChannelLayout] = &[L::Gray, L::GrayA, L::Rgb, L::Rgba, L::C impl Format { /// Every format known to the crate (enabled or not). - pub const ALL: [Format; 15] = [ + pub const ALL: [Format; 16] = [ Format::Png, Format::Jpeg, Format::Tiff, @@ -88,6 +94,7 @@ impl Format { Format::Tga, Format::Ico, Format::Pnm, + Format::Pcx, Format::Qoi, Format::OpenExr, Format::Hdr, @@ -117,6 +124,7 @@ impl Format { Format::Tga => "TGA", Format::Ico => "ICO", Format::Pnm => "Netpbm", + Format::Pcx => "PCX", Format::Qoi => "QOI", Format::OpenExr => "OpenEXR", Format::Hdr => "Radiance HDR", @@ -139,6 +147,7 @@ impl Format { Format::Tga => &["tga", "icb", "vda", "vst"], Format::Ico => &["ico"], Format::Pnm => &["pnm", "pbm", "pgm", "ppm", "pam", "pfm"], + Format::Pcx => &["pcx"], Format::Qoi => &["qoi"], Format::OpenExr => &["exr"], Format::Hdr => &["hdr"], @@ -159,6 +168,7 @@ impl Format { Format::Tga => "image/x-tga", Format::Ico => "image/x-icon", Format::Pnm => "image/x-portable-anymap", + Format::Pcx => "image/x-pcx", Format::Qoi => "image/qoi", Format::OpenExr => "image/x-exr", Format::Hdr => "image/vnd.radiance", @@ -207,6 +217,7 @@ pub fn caps(format: Format) -> FormatCaps { Format::Tga => FormatCaps { layouts: RGB_GRAY, ..base }, Format::Ico => FormatCaps { layouts: &[L::Rgba], ..base }, Format::Pnm => FormatCaps { depths: &[S::U8, S::U16, S::F32], layouts: ALL_LAYOUTS, ..base }, + Format::Pcx => FormatCaps { read: true, write: false, layouts: &[L::Rgb], alpha: false, ..base }, Format::Qoi => base, Format::OpenExr => FormatCaps { depths: &[S::F16, S::F32], layouts: RGB_GRAY, ..base }, Format::Hdr => FormatCaps { depths: &[S::F32], layouts: &[L::Rgb], alpha: false, lossy: true, ..base }, @@ -266,6 +277,9 @@ pub fn detect(bytes: &[u8]) -> Option { if b.starts_with(b"SIMPLE =") { return Some(Format::Fits); } + if crate::codecs::pcx::looks_like_pcx(b) { + return Some(Format::Pcx); + } if looks_like_tga(b) { return Some(Format::Tga); } diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs index 424ec0b8aa..8278ac0d6b 100644 --- a/crates/codecs/src/lib.rs +++ b/crates/codecs/src/lib.rs @@ -43,7 +43,7 @@ pub use crate::resolution::{exif_resolution, export_exif, export_xmp, photoshop_ pub use crate::source_settings::{WebpEncoding, jpeg_quality, webp_encoding}; pub use half::f16; -use crate::codecs::{exr, fits, heif, jpeg, png, pnm, tiff, via_image, webp}; +use crate::codecs::{exr, fits, heif, jpeg, pcx, png, pnm, tiff, via_image, webp}; /// Detect the format and decode with default [`Limits`]. pub fn decode(bytes: &[u8]) -> Result { @@ -74,6 +74,7 @@ pub fn decode_as_with(format: Format, bytes: &[u8], opts: &DecodeOptions) -> Res Format::Tiff => tiff::decode(bytes, l), Format::WebP => webp::decode(bytes, l), Format::Pnm => pnm::decode(bytes, l), + Format::Pcx => pcx::decode(bytes, l), Format::Fits => fits::decode(bytes, l), Format::OpenExr => exr::decode(bytes, l), Format::Heif => heif::decode(bytes, l, opts.keep_orientation), @@ -216,6 +217,7 @@ pub fn encode(image: &Image, format: Format, opts: &EncodeOptions) -> Result tiff::encode(image, plan, opts), Format::WebP => webp::encode(image, plan, opts), Format::Pnm => pnm::encode(image, plan, opts), + Format::Pcx => Err(CodecError::unsupported(format, "PCX is import-only; save as PNG instead")), Format::Fits => fits::encode(image, plan, opts), Format::OpenExr => exr::encode(image, plan, opts), Format::Heif => Err(CodecError::unsupported(format, "encoding is not available in this build")), diff --git a/crates/codecs/tests/pcx.rs b/crates/codecs/tests/pcx.rs new file mode 100644 index 0000000000..89661cb8eb --- /dev/null +++ b/crates/codecs/tests/pcx.rs @@ -0,0 +1,100 @@ +use photocraft_codecs::{ChannelLayout, CodecError, Format, SampleType, caps, decode, decode_as, detect, encode, from_extension}; + +fn header(bits: u8, planes: u8, width: u16, height: u16, stride: u16) -> Vec { + let mut b = vec![0u8; 128]; + b[0] = 0x0a; // ZSoft + b[1] = 5; // PC Paintbrush 3.0+ + b[2] = 1; // RLE + b[3] = bits; + b[8..10].copy_from_slice(&(width - 1).to_le_bytes()); + b[10..12].copy_from_slice(&(height - 1).to_le_bytes()); + b[12..14].copy_from_slice(&300u16.to_le_bytes()); + b[14..16].copy_from_slice(&150u16.to_le_bytes()); + b[65] = planes; + b[66..68].copy_from_slice(&stride.to_le_bytes()); + b[68..70].copy_from_slice(&1u16.to_le_bytes()); + b +} + +fn rle_row(out: &mut Vec, row: &[u8]) { + for &value in row { + if value >= 0xc0 { + out.extend_from_slice(&[0xc1, value]); + } else { + out.push(value); + } + } +} + +#[test] +fn pcx_is_readable_but_not_writable() { + assert_eq!(from_extension("archive.PCX"), Some(Format::Pcx)); + assert!(caps(Format::Pcx).read && !caps(Format::Pcx).write); + let img = photocraft_codecs::Image::from_u8(1, 1, ChannelLayout::Rgb, vec![0, 0, 0]).unwrap(); + assert!(matches!(encode(&img, Format::Pcx, &Default::default()), Err(CodecError::Unsupported { .. }))); +} + +#[test] +fn decodes_three_plane_rgb_and_keeps_dpi() { + let mut b = header(8, 3, 2, 1, 2); + for row in [&[255, 0][..], &[0, 255][..], &[0, 0][..]] { + rle_row(&mut b, row); + } + assert_eq!(detect(&b), Some(Format::Pcx)); + let im = decode(&b).unwrap(); + assert_eq!(im.layout(), ChannelLayout::Rgb); + assert_eq!(im.sample_type(), SampleType::U8); + assert_eq!(im.dimensions(), (2, 1)); + assert_eq!(im.data(), &[255, 0, 0, 0, 255, 0]); + assert_eq!(im.meta.dpi, Some((300.0, 150.0))); +} + +#[test] +fn decodes_256_colour_vga_palette() { + let mut b = header(8, 1, 2, 1, 2); + rle_row(&mut b, &[1, 2]); + b.push(0x0c); + let mut palette = vec![0; 256 * 3]; + palette[3..6].copy_from_slice(&[255, 0, 0]); + palette[6..9].copy_from_slice(&[0, 255, 0]); + b.extend(palette); + assert_eq!(decode(&b).unwrap().data(), &[255, 0, 0, 0, 255, 0]); +} + +#[test] +fn decodes_4bit_and_monochrome_palettes() { + let mut four = header(4, 1, 2, 1, 2); + four[16 + 3..16 + 6].copy_from_slice(&[255, 0, 0]); + four[16 + 6..16 + 9].copy_from_slice(&[0, 0, 255]); + rle_row(&mut four, &[0x12, 0]); + assert_eq!(decode(&four).unwrap().data(), &[255, 0, 0, 0, 0, 255]); + + let mut one = header(1, 1, 2, 1, 2); + one[16 + 3..16 + 6].copy_from_slice(&[255, 0, 0]); + rle_row(&mut one, &[0x80, 0]); + assert_eq!(decode(&one).unwrap().data(), &[255, 0, 0, 0, 0, 0]); +} + +#[test] +fn rejects_truncated_and_overshooting_rle_without_panicking() { + let mut b = header(8, 3, 2, 1, 2); + assert!(decode_as(Format::Pcx, &b).is_err(), "header alone is truncated"); + b.extend([0xc5, 0xff]); // a five-pixel run cannot cross a two-byte row + assert!(decode_as(Format::Pcx, &b).is_err()); + let mut b = header(8, 3, 2, 1, 2); + b.extend([0xc1]); // missing run value + assert!(decode_as(Format::Pcx, &b).is_err()); + let mut b = header(8, 3, 2, 1, 2); + b[66..68].copy_from_slice(&0u16.to_le_bytes()); + assert_eq!(detect(&b), None, "invalid stride is not a PCX signature"); +} + +#[test] +fn refuses_headers_that_exceed_allocation_budget() { + let mut b = header(8, 3, 3000, 3000, 3000); + // The default decoder rejects the allocation before reading any scanline. + let opts = photocraft_codecs::DecodeOptions { limits: photocraft_codecs::Limits { max_alloc: 1024, ..Default::default() }, ..Default::default() }; + assert!(matches!(photocraft_codecs::decode_as_with(Format::Pcx, &b, &opts), Err(CodecError::LimitExceeded(_)))); + b[2] = 0; + assert_eq!(detect(&b), None, "unsupported uncompressed encoding"); +} From 0c2ca488aeac6f10ebd6f7af5a4569040931c052 Mon Sep 17 00:00:00 2001 From: Nicolas Falesy <112726756+nicolasfalesy@users.noreply.github.com> Date: Mon, 12 Oct 2026 07:13:06 -0400 Subject: [PATCH 10/24] fix(text): scale faux bold dilation with glyph scaling (#3705) (#3719) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When drawing faux-bold glyphs, the offset dilation was composed as `Xform(ox * r, oy * r).mul(&glyph)`. Because `Xform::mul(o)` applies `o` first (`self ∘ o`), the translation offset was added after the glyph's scaling transform, leaving faux bold dilation unscaled by horizontal and vertical font scaling. Applying the glyph transform to the offset transform (`glyph.mul(&offset)`) ensures dilation is performed in font-local coordinates and scaled proportionally with anisotropic glyph scaling, matching Photoshop. --- crates/text/src/render.rs | 2 +- crates/text/src/tests.rs | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/crates/text/src/render.rs b/crates/text/src/render.rs index 6068ae4a69..acd9d51132 100644 --- a/crates/text/src/render.rs +++ b/crates/text/src/render.rs @@ -72,7 +72,7 @@ fn draw(layout: &TextLayout, transform: &Xform, sink: &mut impl LineSink, only_c let offsets: &[(f64, f64)] = if bold { &[(-1.0, 0.0), (1.0, 0.0), (0.0, -1.0), (0.0, 1.0), (0.7, 0.7), (-0.7, -0.7), (0.7, -0.7), (-0.7, 0.7)] } else { &[(0.0, 0.0)] }; for &(ox, oy) in offsets { - let local = Xform([1.0, 0.0, 0.0, 1.0, ox * r, oy * r]).mul(&glyph); + let local = glyph.mul(&Xform([1.0, 0.0, 0.0, 1.0, ox * r, oy * r])); let settings = DrawSettings::unhinted(Size::new(face.size_px), LocationRef::new(&coords)); match warp { Some(w) => { diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 8df4d81b0e..75b775b783 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -381,6 +381,41 @@ fn styles_change_pixels() { assert!(hrect.width() as f32 > prect.width() as f32 * 1.7); } +/// #3705: Faux bold dilation must scale with horizontal and vertical glyph scaling. +#[test] +fn faux_bold_scales_with_glyph_scaling() { + let mut e = TextEngine::new(); + let base = CharStyle { size_pt: 40.0, ..Default::default() }; + let ink = |e: &mut TextEngine, s: CharStyle| { + let (_, r) = e.render(&TextLayer { transform: Affine::translate(5.0, 50.0), ..styled("Hi", s) }, 72.0, PixelFormat::RGBA8); + (alpha_sum(&r.surface, r.rect), r.rect) + }; + let (_plain, prect) = ink(&mut e, base.clone()); + let (_bold, brect) = ink(&mut e, CharStyle { faux_bold: true, ..base.clone() }); + let unscaled_extra_w = brect.width() - prect.width(); + let unscaled_extra_h = brect.height() - prect.height(); + + // With 2x horizontal scale, the horizontal dilation scales with the glyph: + let hscaled = CharStyle { size_pt: 40.0, horizontal_scale: 2.0, ..Default::default() }; + let (_, phrect) = ink(&mut e, hscaled.clone()); + let (_, bhrect) = ink(&mut e, CharStyle { faux_bold: true, ..hscaled }); + let hscaled_extra_w = bhrect.width() - phrect.width(); + assert!( + hscaled_extra_w >= unscaled_extra_w * 2 - 1 && hscaled_extra_w <= unscaled_extra_w * 2 + 1, + "hscaled extra width {hscaled_extra_w} vs unscaled {unscaled_extra_w}" + ); + + // With 2x vertical scale, the vertical dilation scales with the glyph: + let vscaled = CharStyle { size_pt: 40.0, vertical_scale: 2.0, ..Default::default() }; + let (_, pvrect) = ink(&mut e, vscaled.clone()); + let (_, bvrect) = ink(&mut e, CharStyle { faux_bold: true, ..vscaled }); + let vscaled_extra_h = bvrect.height() - pvrect.height(); + assert!( + vscaled_extra_h >= unscaled_extra_h * 2 - 1 && vscaled_extra_h <= unscaled_extra_h * 2 + 1, + "vscaled extra height {vscaled_extra_h} vs unscaled {unscaled_extra_h}" + ); +} + #[test] fn multicolor_runs() { let mut e = TextEngine::new(); From 89312de597dbad53ca7e502da0008344d6bb6036 Mon Sep 17 00:00:00 2001 From: Fabio Lussi Date: Mon, 12 Oct 2026 13:13:32 +0200 Subject: [PATCH 11/24] Answer a repeat auth with "already authenticated" (#3723) A second `auth` frame on an authenticated TCP connection fell through to the method dispatcher and came back as an unknown method, in both the headless serve server and the desktop control server. A shared `security::repeat_auth_reply` now answers it with `already authenticated` (keeping the request id) and the connection keeps serving. Fixes #3668 Co-authored-by: Fabio Lussi <198260595+itrycodinganditsbad@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- apps/photocraft/src/control_server.rs | 48 ++++++++++++++++++++++++++- crates/automation/src/rpc.rs | 34 +++++++++++++++++-- crates/automation/src/security.rs | 23 +++++++++++++ docs/control-protocol.md | 2 ++ 4 files changed, 104 insertions(+), 3 deletions(-) diff --git a/apps/photocraft/src/control_server.rs b/apps/photocraft/src/control_server.rs index 932e31ee60..b1282419d8 100644 --- a/apps/photocraft/src/control_server.rs +++ b/apps/photocraft/src/control_server.rs @@ -9,7 +9,7 @@ use std::time::Instant; use photocraft_automation::budgets::write_reply; use photocraft_automation::security::{ - ConnectionLimiter, LineRead, MAX_CONNECTIONS, MAX_REQUEST_BYTES, authentication_reply, configure_stream, read_bounded_line, + ConnectionLimiter, LineRead, MAX_CONNECTIONS, MAX_REQUEST_BYTES, authentication_reply, configure_stream, read_bounded_line, repeat_auth_reply, }; use photocraft_ui_egui::ControlRequest; use photocraft_ui_egui::control::{REPLY_DEADLINE, timeout_error}; @@ -79,6 +79,12 @@ fn serve(stream: TcpStream, token: &str, tx: Sender, ctx: egui:: } continue; } + if let Some(reply) = repeat_auth_reply(&line) { + if write_reply(&mut out, &reply).is_err() || out.flush().is_err() { + break; + } + continue; + } let reply = match serde_json::from_str::(&line) { Ok(msg) => { let id = msg.get("id").cloned().unwrap_or(Value::Null); @@ -202,4 +208,44 @@ mod tests { handler.join().unwrap(); server.join().unwrap(); } + + #[test] + fn repeat_auth_reports_already_authenticated_without_dispatching() { + const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let (tx, rx) = channel::(); + let server = std::thread::spawn(move || { + let (stream, _) = listener.accept().unwrap(); + serve(stream, TOKEN, tx, egui::Context::default()); + }); + let handler = std::thread::spawn(move || { + let req = rx.recv_timeout(Duration::from_secs(5)).unwrap(); + assert_eq!(req.method, "test.after", "a repeat auth must not reach the UI dispatcher"); + req.reply.send(json!({"ok": true, "result": "still serving"})).unwrap(); + }); + let mut stream = TcpStream::connect(addr).unwrap(); + stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut line = String::new(); + for id in ["auth", "again"] { + writeln!(stream, "{}", json!({"id": id, "method": "auth", "params": {"token": TOKEN}})).unwrap(); + line.clear(); + reader.read_line(&mut line).unwrap(); + } + let again: Value = serde_json::from_str(&line).unwrap(); + assert_eq!(again["id"], "again"); + assert_eq!(again["ok"], false); + assert_eq!(again["error"], "already authenticated"); + writeln!(stream, "{}", json!({"id": 9, "method": "test.after"})).unwrap(); + line.clear(); + reader.read_line(&mut line).unwrap(); + let after: Value = serde_json::from_str(&line).unwrap(); + assert_eq!(after["id"], 9); + assert_eq!(after["result"], "still serving"); + drop(reader); + drop(stream); + handler.join().unwrap(); + server.join().unwrap(); + } } diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index d513bfa889..875850460c 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -30,7 +30,7 @@ use serde_json::{Value, json}; use crate::budgets::{BatchReplyBudget, write_reply}; use crate::security::{ ConnectionLimiter, LineRead, MAX_BATCH_STEPS, MAX_CONNECTIONS, MAX_REQUEST_BYTES, authentication_reply, configure_stream, discard_rest_of_line, - read_bounded_line, + read_bounded_line, repeat_auth_reply, }; use crate::{AutomationError, Headless}; @@ -288,7 +288,7 @@ fn serve_tcp_connection(h: &Mutex, stream: std::net::TcpStream, token: LineRead::Line => {} } let reply = if authenticated { - respond(h, &line) + repeat_auth_reply(&line).unwrap_or_else(|| respond(h, &line)) } else { let (reply, ok) = authentication_reply(&line, token); authenticated = ok; @@ -780,6 +780,36 @@ mod tests { assert!(v["result"].as_array().unwrap().iter().any(|m| m == "batch")); } + #[test] + fn tcp_repeat_auth_reports_already_authenticated_and_keeps_serving() { + use std::io::{BufReader, Write as _}; + const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + let h = Arc::new(Mutex::new(Headless::new())); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let _ = serve_tcp("127.0.0.1:0", h, TOKEN.into(), move |a| tx.send(a).unwrap()); + }); + let addr = rx.recv().unwrap(); + let mut s = std::net::TcpStream::connect(addr).unwrap(); + let mut reader = BufReader::new(s.try_clone().unwrap()); + let mut line = String::new(); + for id in ["auth", "again"] { + writeln!(s, r#"{{"id":"{id}","method":"auth","params":{{"token":"{TOKEN}"}}}}"#).unwrap(); + line.clear(); + reader.read_line(&mut line).unwrap(); + } + let again: Value = serde_json::from_str(&line).unwrap(); + assert_eq!(again["id"], "again"); + assert_eq!(again["ok"], false); + assert_eq!(again["error"], "already authenticated"); + writeln!(s, r#"{{"id":"m","method":"methods"}}"#).unwrap(); + line.clear(); + reader.read_line(&mut line).unwrap(); + let v: Value = serde_json::from_str(&line).unwrap(); + assert_eq!(v["id"], "m"); + assert_eq!(v["ok"], true); + } + #[test] fn tcp_rejects_requests_before_authentication() { use std::io::{BufReader, Write as _}; diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index 075427c03f..4659a3ff17 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -118,6 +118,18 @@ pub fn authentication_reply(line: &str, expected_token: &str) -> (Value, bool) { } } +/// Answer a repeat `auth` frame on an already authenticated connection. Returns `None` for any +/// other frame, which the caller dispatches as usual. +/// Without this, a second `auth` fell through to the method dispatcher as an unknown method. +pub fn repeat_auth_reply(line: &str) -> Option { + let req: Value = serde_json::from_str(line).ok()?; + if req.get("method").and_then(Value::as_str) != Some(AUTH_METHOD) { + return None; + } + let id = req.get("id").cloned().unwrap_or(Value::Null); + Some(json!({"id": id, "ok": false, "error": "already authenticated"})) +} + fn read_token_file(path: &Path) -> Result { let token = std::fs::read_to_string(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?; let token = token.trim().to_owned(); @@ -294,6 +306,17 @@ mod tests { assert_eq!(reply["result"]["authenticated"], true); } + #[test] + fn repeat_auth_on_an_authenticated_connection_says_so() { + let line = json!({"id": 3, "method": AUTH_METHOD, "params": {"token": "anything"}}).to_string(); + let reply = repeat_auth_reply(&line).unwrap(); + assert_eq!(reply["id"], 3); + assert_eq!(reply["ok"], false); + assert_eq!(reply["error"], "already authenticated"); + assert!(repeat_auth_reply(r#"{"id":4,"method":"methods"}"#).is_none()); + assert!(repeat_auth_reply("{not json").is_none()); + } + #[test] fn token_file_round_trips_between_server_and_client() { let path = std::env::temp_dir().join(format!("photocraft-control-token-{}-{}.txt", std::process::id(), generate_token().unwrap())); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index c73a0be6a6..0d974c095f 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -23,6 +23,8 @@ The first request on every TCP connection must authenticate. No other method is {"id": "auth", "method": "auth", "params": {"token": "<64 hexadecimal characters>"}} ``` +Authenticate once per connection. A later `auth` frame on the same connection gets `{"ok": false, "error": "already authenticated"}` and the connection keeps serving. + After the successful authentication reply, each request is one JSON line: ```json From 6751a460032f4619d8eabd3ddec6fb890a040c94 Mon Sep 17 00:00:00 2001 From: Valentin Klein Date: Mon, 12 Oct 2026 13:13:45 +0200 Subject: [PATCH 12/24] Codecs: integer fast paths for Image::convert (#3717) (#3729) U8/U16 depth changes and pure channel-copy layout changes (alpha add/drop, gray to RGB) skip the two intermediate f32 buffers. Output is bit-identical to the f32 route. Co-authored-by: Claude Opus 5.5 --- crates/codecs/src/image.rs | 111 +++++++++++++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) diff --git a/crates/codecs/src/image.rs b/crates/codecs/src/image.rs index 01f5d4cad0..92d8fb5823 100644 --- a/crates/codecs/src/image.rs +++ b/crates/codecs/src/image.rs @@ -512,6 +512,8 @@ impl Image { out.extend_from_slice(&one); } out + } else if let Some(fast) = self.convert_int_direct(layout, sample) { + fast } else if layout == self.layout { quantize(&self.to_normalized(), sample) } else { @@ -531,6 +533,55 @@ impl Image { } } + /// Integer fast path of [`Image::convert`] for U8/U16 sources and targets whose result is + /// a pure channel copy: same colour model (alpha added as opaque, or dropped) or gray to + /// RGB. Bit-identical to the generic f32 route (see the equivalence tests) but without + /// the two intermediate f32 buffers. Returns `None` for everything else. + fn convert_int_direct(&self, layout: ChannelLayout, sample: SampleType) -> Option> { + let int = |s: SampleType| matches!(s, SampleType::U8 | SampleType::U16); + if !int(self.sample) || !int(sample) { + return None; + } + let gray_to_rgb = self.layout.is_gray() && layout.is_rgb(); + if !gray_to_rgb && !layout.same_model(self.layout) { + return None; + } + let one: &[u8] = match sample { + SampleType::U8 => &[u8::MAX], + _ => &u16::MAX.to_ne_bytes(), + }; + let (fc, tc) = (self.layout.channels(), layout.channels()); + let (sb, db) = (self.sample.bytes(), sample.bytes()); + let (src_color, dst_color) = (self.layout.color_channels(), layout.color_channels()); + let n = self.data.len() / (fc * sb); + let mut out = Vec::with_capacity(n.checked_mul(tc)?.checked_mul(db)?); + macro_rules! run { + ($conv:expr) => {{ + let conv = $conv; + for px in self.data.chunks_exact(fc * sb) { + for j in 0..dst_color { + let c = if src_color == 1 { 0 } else { j }; + conv(&px[c * sb..(c + 1) * sb], &mut out); + } + if layout.has_alpha() { + if self.layout.has_alpha() { + conv(&px[src_color * sb..(src_color + 1) * sb], &mut out); + } else { + out.extend_from_slice(one); + } + } + } + }}; + } + match (self.sample, sample) { + (SampleType::U8, SampleType::U8) => run!(|s: &[u8], o: &mut Vec| o.push(s[0])), + (SampleType::U16, SampleType::U16) => run!(|s: &[u8], o: &mut Vec| o.extend_from_slice(s)), + (SampleType::U8, SampleType::U16) => run!(|s: &[u8], o: &mut Vec| o.extend_from_slice(&(u16::from(s[0]) * 257).to_ne_bytes())), + _ => run!(|s: &[u8], o: &mut Vec| o.push(((u32::from(u16::from_ne_bytes([s[0], s[1]])) + 128) / 257) as u8)), + } + Some(out) + } + /// [`Image::convert`], borrowing `self` when it already has that layout and sample type /// (encoders use it so a full-size image isn't copied for nothing). pub fn converted(&self, layout: ChannelLayout, sample: SampleType) -> std::borrow::Cow<'_, Image> { @@ -661,6 +712,66 @@ mod tests { use super::*; + /// The generic f32 route `convert` used before the integer fast paths (the reference). + fn convert_via_f32(img: &Image, layout: ChannelLayout, sample: SampleType) -> Vec { + quantize(&convert_layout(&img.to_normalized(), img.layout, layout), sample) + } + + #[test] + fn int_fast_path_matches_f32_route_for_every_value() { + // Every U8 and every U16 value through every depth pair (alpha goes through the same per-sample conversion; covered by the layout test). + let all8: Vec = (0..=255).collect(); + let all16: Vec = (0..=65535).collect(); + for (src, to) in + [(SampleType::U8, SampleType::U8), (SampleType::U8, SampleType::U16), (SampleType::U16, SampleType::U8), (SampleType::U16, SampleType::U16)] + { + let img = if src == SampleType::U8 { + Image::from_u8(256, 1, ChannelLayout::Gray, all8.clone()).unwrap() + } else { + Image::from_u16(65536, 1, ChannelLayout::Gray, &all16).unwrap() + }; + for layout in [ChannelLayout::Gray, ChannelLayout::Rgb] { + assert_eq!(img.convert(layout, to).data(), &convert_via_f32(&img, layout, to)[..], "{src:?}->{to:?} {layout:?}"); + } + } + } + + #[test] + fn int_fast_path_matches_f32_route_for_every_layout() { + let mut seed = 0x9e3779b97f4a7c15u64; + let mut next = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + for from_s in [SampleType::U8, SampleType::U16] { + for from_l in ChannelLayout::ALL { + let n = 64 * from_l.channels(); + let mut vals = Vec::new(); + for i in 0..n { + // Edge values (0, 1, max-1, max, mid) mixed with random ones. + let r = next(); + let v = match i % 7 { + 0 => 0.0, + 1 => 1.0, + 2 => 1.0 / 255.0, + 3 => 254.0 / 255.0, + _ => (r % 65536) as f32 / 65535.0, + }; + vals.push(v); + } + let img = Image::from_normalized(64, 1, from_l, from_s, &vals).unwrap(); + for to_l in ChannelLayout::ALL { + for to_s in SampleType::ALL { + let got = img.convert(to_l, to_s); + assert_eq!(got.data(), &convert_via_f32(&img, to_l, to_s)[..], "{from_l:?}/{from_s:?} -> {to_l:?}/{to_s:?}"); + } + } + } + } + } + #[test] fn u8_u16_roundtrip_exact() { let v: Vec = (0..=255).collect(); From 3dd5fc1cdc631efcc213d849b86829602895b7ea Mon Sep 17 00:00:00 2001 From: Fabio Lussi Date: Mon, 12 Oct 2026 13:13:57 +0200 Subject: [PATCH 13/24] automation: say why a command is disabled in engine.commands (#3740) engine.commands, command.list and the MCP command_list tool now give each row a disabledReason (null when enabled, else the failed precondition) and needsDocument (true when the command is off because no document is open), so an agent can tell "open a document first" from "not runnable". enabled keeps its meaning. Both listings share one row builder in the engine. Fixes #3664 Co-authored-by: Fabio Lussi <198260595+itrycodinganditsbad@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/automation/src/headless.rs | 16 +--------------- crates/automation/src/server.rs | 4 +++- crates/automation/tests/mcp.rs | 6 ++++++ crates/engine/src/commands.rs | 26 ++++++++++++++------------ crates/engine/src/tests.rs | 27 +++++++++++++++++++++++++++ docs/control-protocol.md | 6 +++--- 6 files changed, 54 insertions(+), 31 deletions(-) diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 028ca09f14..dc18afe2f2 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -317,21 +317,7 @@ impl Headless { } pub fn command_list(&self) -> Value { - Value::Array( - command_specs() - .iter() - .map(|c| { - json!({ - "id": c.id, - "label": c.label, - "menu": c.menu, - "shortcut": c.shortcut, - "params": c.params, - "enabled": self.session.is_enabled(c.id), - }) - }) - .collect(), - ) + Value::Array(command_specs().iter().map(|c| photocraft_engine::commands::list_entry(&self.session, c, self.session.disabled_reason(c.id))).collect()) } pub fn command_run(&mut self, id: &str, params: Value) -> Result { diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index 909e221984..c2f18b8bd5 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -792,7 +792,9 @@ impl PhotocraftMcp { } } - #[tool(description = "List engine commands: id, label, menu path, shortcut, parameter doc, enabled now.")] + #[tool(description = "List engine commands: id, label, menu path, shortcut, parameter doc, enabled now. \ + `disabledReason` says why a command is off (null when enabled); `needsDocument` is true when it is off because no \ + document is open: create or open one first (doc_new, doc_open).")] async fn command_list(&self, Parameters(p): Parameters) -> Result { let all = if let Some(r) = self.headless_op(|h| Ok(h.command_list())).await { r diff --git a/crates/automation/tests/mcp.rs b/crates/automation/tests/mcp.rs index 3ec39ebcc0..af5459af1f 100644 --- a/crates/automation/tests/mcp.rs +++ b/crates/automation/tests/mcp.rs @@ -170,6 +170,12 @@ async fn command_list_filters() { let enabled = json_of(&call(&client, "command_list", json!({"enabled_only": true})).await); assert!(enabled.as_array().unwrap().iter().any(|c| c["id"] == "file.new")); assert!(!enabled.as_array().unwrap().iter().any(|c| c["id"] == "layer.new.layer"), "needs a document"); + // The full list says why a document command is off with no document open (#3664). + let layer = all.as_array().unwrap().iter().find(|c| c["id"] == "layer.new.layer").unwrap(); + assert_eq!((layer["enabled"].clone(), layer["needsDocument"].clone()), (json!(false), json!(true)), "{layer}"); + assert!(layer["disabledReason"].as_str().is_some_and(|r| r.starts_with("no document")), "{layer}"); + let new = all.as_array().unwrap().iter().find(|c| c["id"] == "file.new").unwrap(); + assert_eq!((new["needsDocument"].clone(), new["disabledReason"].clone()), (json!(false), Value::Null), "{new}"); client.cancel().await.unwrap(); } diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 3554e5690f..48caf85b28 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -136,6 +136,19 @@ pub fn command_specs() -> &'static [CommandSpec] { ®istry().specs } +/// One `command.list` / `engine.commands` row for `c`, given why it can't run now (`None` = it can). +/// `disabledReason` is that message; `needsDocument` is true when the reason is that no document is +/// open (#3664), so an agent can tell "open or create a document first" from a precondition that a +/// document alone won't meet (a selection, an empty clipboard). +pub fn list_entry(s: &Session, c: &CommandSpec, reason: Option) -> Value { + let needs_document = + s.active().is_none() && reason.as_deref().is_some_and(|r| ["no document", "no active document", "no open document"].iter().any(|p| r.starts_with(p))); + json!({ + "id": c.id, "label": c.label, "menu": c.menu, "shortcut": c.shortcut, "params": c.params, + "enabled": reason.is_none(), "disabledReason": reason, "needsDocument": needs_document, + }) +} + pub fn find(id: &str) -> Option<&'static CommandSpec> { let registry = registry(); registry.by_id.get(id).and_then(|&index| registry.specs.get(index)) @@ -1014,18 +1027,7 @@ fn build() -> Vec { shortcut: None, params: "{}", enabled: always, - run: |s, _| { - Ok(Value::Array( - command_specs() - .iter() - .map(|c| { - json!({ - "id": c.id, "label": c.label, "menu": c.menu, "shortcut": c.shortcut, "params": c.params, "enabled": (c.enabled)(s).is_ok(), - }) - }) - .collect(), - )) - }, + run: |s, _| Ok(Value::Array(command_specs().iter().map(|c| list_entry(s, c, (c.enabled)(s).err())).collect())), journal: false, }, CommandSpec { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e4cbfe57a5..a35a19bb43 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -767,6 +767,33 @@ fn command_list_reports_enablement() { assert_eq!(find("layer.new.layer")["enabled"], false); } +/// With no document open, a document command says so instead of only `enabled: false` (#3664). +#[test] +fn command_list_tells_no_document_from_other_preconditions() { + let mut s = Session::new(); + let list = s.execute("command.list", json!({})).unwrap(); + let find = |list: &Value, id: &str| list.as_array().unwrap().iter().find(|c| c["id"] == id).unwrap().clone(); + for id in ["paint.stroke", "layer.new.layer", "filter.blur.gaussianBlur"] { + let c = find(&list, id); + assert_eq!((c["enabled"].clone(), c["needsDocument"].clone()), (json!(false), json!(true)), "{id}: {c}"); + assert!(c["disabledReason"].as_str().is_some_and(|r| r.starts_with("no document")), "{id}: {c}"); + } + let new = find(&list, "file.new"); + assert_eq!((new["enabled"].clone(), new["needsDocument"].clone(), new["disabledReason"].clone()), (json!(true), json!(false), Value::Null)); + // A precondition that isn't the missing document keeps its own reason. + let paste = find(&list, "file.newFromClipboard"); + assert_eq!((paste["enabled"].clone(), paste["needsDocument"].clone()), (json!(false), json!(false))); + assert_eq!(paste["disabledReason"], "the clipboard is empty"); + // With a document, the same commands run; a missing selection is not a missing document. + let mut s = session_with_doc(); + let list = s.execute("command.list", json!({})).unwrap(); + assert_eq!(find(&list, "paint.stroke")["needsDocument"], false); + assert_eq!(find(&list, "paint.stroke")["disabledReason"], Value::Null); + let deselect = find(&list, "select.deselect"); + assert_eq!((deselect["enabled"].clone(), deselect["needsDocument"].clone()), (json!(false), json!(false))); + assert_eq!(deselect["disabledReason"], "no selection"); +} + #[test] fn translate_moves_pixels_and_respects_locks() { let mut s = session_with_doc(); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 0d974c095f..3f0be8ebe9 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -90,7 +90,7 @@ Change the UI language without restarting with `prefs.set`: are documented in [UI localisation](localization.md). `prefs.get` and the existing preference store expose and persist the same setting; scripts keep using canonical command IDs. -`engine.execute` runs any command by id. `engine.commands` (or the engine command `command.list`) lists them all, with labels, menu paths, shortcuts, a parameter description, and whether each is currently enabled. Examples: +`engine.execute` runs any command by id. `engine.commands` (or the engine command `command.list`) lists them all, with labels, menu paths, shortcuts, a parameter description, and whether each is currently enabled. Each row carries `enabled` (bool), `disabledReason` (`null` when enabled, otherwise the precondition that failed, such as `"no document open"`, `"no selection"` or `"the clipboard is empty"`) and `needsDocument` (true when the command is off because no document is open, so the first step is to create or open one; a command may still have its own precondition after that, such as an active text layer. False when enabled or off for another reason). With no document open, nearly every document command reports `enabled: false, needsDocument: true`; plan around `needsDocument` rather than reading `enabled` alone (#3664). Examples: | Command | Params | |---|---| @@ -263,7 +263,7 @@ How each MCP tool maps onto control methods in bridge mode: |---|---| | `command_run {id, params, wait?}` | `engine.execute {command: id, params, wait}` | | `jobs_list` / `jobs_cancel {job?}` | `jobs.list` / `jobs.cancel {job?}` | -| `command_list {filter?, enabled_only?}` | `engine.commands` (filtered by the MCP server) | +| `command_list {filter?, enabled_only?}` | `engine.commands` (filtered by the MCP server; rows keep `disabledReason` and `needsDocument`) | | `doc_new {…}` | `engine.execute {command: "file.new", params}` | | `doc_inspect` | `engine.execute {command: "document.inspect"}` | | `doc_open {path}` | `app.open {path}` | @@ -321,7 +321,7 @@ no MCP framing, no app start-up per command. Configure its file access with the |---|---| | `engine.execute` | `{command, params?, wait?}`: any engine command (`wait: false` starts a long one as a background job: `{job, pending}`) | | `jobs.list` / `jobs.cancel` | `{}` / `{job?}`: background jobs; cancel one or all. Every request (and MCP tool call) first applies the jobs that finished, so `doc.save`, `doc.inspect`, `doc.render` and `session.list` include a finished job's result without polling `jobs.list` first | -| `engine.commands` | `{filter?}`: registry with params docs and enablement | +| `engine.commands` | `{filter?}`: registry with params docs and enablement (`enabled`, `disabledReason`, `needsDocument`) | | `session.list` | open documents and the active index | | `doc.open` / `doc.new` | `{path}` / `file.new` params | | `doc.place` | `{path, scale? (percent), fit? (true), center? ([x, y]), index?}`: places a file as a Smart Object layer above the active one and returns `{layer, scale, bounds}`. `path` resolves beneath the read root, so this is the capability-scoped `file.placeEmbedded` — that command itself still refuses an ambient path | From 53d814f6437db8a26d5a469f0f8198ab8f5fb658 Mon Sep 17 00:00:00 2001 From: FinnNk Date: Mon, 12 Oct 2026 12:32:23 +0100 Subject: [PATCH 14/24] feat: Photoshop's layer and selection keys (Ctrl+, toggle, Ctrl+\, /, Ctrl+Alt+2, Ctrl+Alt+Backspace, Tab rename, Alt-click thumbnail) (#3710) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(engine): Ctrl+, toggles a layer's visibility and / its transparency lock Photoshop's Ctrl+, (Cmd+, on macOS) hides the selected layers and, once they are all hidden, shows them again: its Layer menu item then reads Show Layers. layer.hideLayers now does the same, so the key toggles: it shows them only when every targeted layer is hidden. The / key toggles Lock Transparent Pixels, as the Layers panel's first lock button does (layer.toggleLockTransparency). With several layers selected, any unlocked one means lock them all; the Background, which can't take this lock, is left out. Each press is one undoable step. Co-Authored-By: Claude Opus 5.5 * feat(engine): Ctrl+\ targets the layer mask and Ctrl+Alt+2 loads luminosity Photoshop's Ctrl+\ (Cmd+\) targets the active layer's mask, as clicking its thumbnail does, beside Ctrl+2 for the composite (channel.target.layerMask; greyed when the layer has no mask). Its Ctrl+Alt+2 (Cmd+Option+2) loads the image's luminosity as a selection, the Ctrl-click on the composite channel (select.loadLuminosity). Co-Authored-By: Claude Opus 5.5 * feat(engine): Ctrl+Alt+Backspace fills from history Photoshop's Ctrl+Alt+Backspace (Cmd+Option+Delete) fills the selection, or the layer, from the History Brush's source state. edit.fillHistory is edit.fill with contents "history": the oldest state still held, unless "state" names another. It joins the other fill keys, so it honours the Channels panel target and appears with them in Keyboard Shortcuts. Co-Authored-By: Claude Opus 5.5 * feat(ui): Tab renames the next layer; Alt-click a thumbnail fits the layer While a layer name is being edited, Tab commits it and starts renaming the layer below, and Shift+Tab the layer above, as in Photoshop; the Background, which isn't renamed in place, ends it. Alt-clicking a layer's thumbnail selects the layer and fits its content on screen (View › Fit Layer(s) on Screen). Key tests cover Ctrl+,, /, Ctrl+\, Ctrl+Alt+2 and Ctrl+Alt+Backspace through the shortcut dispatcher. docs/ui-parity.md lists the new keys. Co-Authored-By: Claude Opus 5.5 * fix(ui): an explicit channel target drives the Layers panel's mask target After Ctrl+\ targeted the layer mask, Ctrl+2 moved the Channels target back to the composite, but the Layers panel kept the mask targeted (its own flag, which only ever followed the engine towards the mask), so painting still went to the mask. The same happened after clicking the mask thumbnail. Any channel.target command (Ctrl+2, Ctrl+\, Ctrl+3…) now sets the panel's mask and vector-mask targets from the engine's target. Co-Authored-By: Claude Opus 5.5 * Use Document::is_background after #4036 removed extra_cmds::is_background Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Brandon Thomas --- crates/engine/src/channel_cmds.rs | 17 +++ crates/engine/src/channel_cmds/tests.rs | 27 ++++ crates/engine/src/extra_cmds.rs | 90 ++++++++++++- crates/engine/src/fill_key_cmds.rs | 52 +++++++- crates/ui-egui/src/layer_row_ui.rs | 18 ++- .../ui-egui/src/layer_row_ui/rename_tests.rs | 28 +++- crates/ui-egui/src/layer_shortcut_tests.rs | 124 ++++++++++++++++++ crates/ui-egui/src/lib.rs | 12 ++ crates/ui-egui/src/panels.rs | 15 +++ docs/ui-parity.md | 4 +- 10 files changed, 380 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/src/layer_shortcut_tests.rs diff --git a/crates/engine/src/channel_cmds.rs b/crates/engine/src/channel_cmds.rs index a85ff75b78..39ce9c8250 100644 --- a/crates/engine/src/channel_cmds.rs +++ b/crates/engine/src/channel_cmds.rs @@ -1804,6 +1804,16 @@ pub fn specs() -> Vec { journal: false, }, spec!("channel.target.composite", "Target Composite Channel", [], Some("Cmd+2"), "{}", has_doc, |s, _| target_slot(s, 2)), + // ⌘\ targets the active layer's mask, as clicking its thumbnail does. + spec!("channel.target.layerMask", "Target Layer Mask", [], Some("Cmd+\\"), "{}", has_layer_mask, |s, _| target_cmd( + s, + &serde_json::json!({"channel": "mask"}) + )), + // ⌘⌥2 loads the image's luminosity as a selection (⌘-click on the composite channel). + spec!("select.loadLuminosity", "Load Luminosity", [], Some("Cmd+Alt+2"), "{}", has_doc, |s, _| load_selection( + s, + &serde_json::json!({"channel": "composite"}) + )), spec!("channel.target.slot3", "Target Channel 3", [], Some("Cmd+3"), "{}", slot_ok::<3>, |s, _| target_slot(s, 3)), spec!("channel.target.slot4", "Target Channel 4", [], Some("Cmd+4"), "{}", slot_ok::<4>, |s, _| target_slot(s, 4)), spec!("channel.target.slot5", "Target Channel 5", [], Some("Cmd+5"), "{}", slot_ok::<5>, |s, _| target_slot(s, 5)), @@ -1814,6 +1824,13 @@ pub fn specs() -> Vec { ] } +/// Target Layer Mask: the active layer has a mask. +fn has_layer_mask(s: &Session) -> std::result::Result<(), String> { + let st = s.active().ok_or("no document open")?; + let layer = st.active_layer.and_then(|id| st.doc.layer(id)).ok_or("no active layer")?; + layer.mask.as_ref().map(|_| ()).ok_or_else(|| "the active layer has no layer mask".to_string()) +} + fn slot_ok(s: &Session) -> std::result::Result<(), String> { let d = s.active().ok_or("no document open")?; let colors = color_count(&d.doc); diff --git a/crates/engine/src/channel_cmds/tests.rs b/crates/engine/src/channel_cmds/tests.rs index 1223c0589b..17727dc8ad 100644 --- a/crates/engine/src/channel_cmds/tests.rs +++ b/crates/engine/src/channel_cmds/tests.rs @@ -741,6 +741,33 @@ fn clear_with_an_alpha_channel_or_quick_mask_targeted_fills_it_not_the_layer() { assert_eq!(px(&s, 5, 5), layer, "the layer is untouched in Quick Mask mode"); } +#[test] +fn command_backslash_targets_the_layer_mask_and_command_2_the_composite() { + let mut s = session(); + s.execute("layer.new.layer", json!({})).unwrap(); + assert!(!s.is_enabled("channel.target.layerMask"), "no mask yet"); + assert!(s.execute("channel.target.layerMask", json!({})).is_err()); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + s.execute("channel.target.composite", json!({})).unwrap(); + assert_eq!(crate::commands::find("channel.target.layerMask").and_then(|c| c.shortcut), Some("Cmd+\\")); + s.execute("channel.target.layerMask", json!({})).unwrap(); + assert_eq!(s.active().unwrap().channel_view.target, ChannelTarget::LayerMask); + s.execute("channel.target.composite", json!({})).unwrap(); + assert_eq!(s.active().unwrap().channel_view.target, ChannelTarget::Composite); +} + +#[test] +fn command_alt_2_loads_the_images_luminosity() { + let mut s = session(); + rect(&mut s, 0, 0, 20, 20, "replace"); + s.execute("edit.fill", json!({"contents": "black"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + assert_eq!(crate::commands::find("select.loadLuminosity").and_then(|c| c.shortcut), Some("Cmd+Alt+2")); + s.execute("select.loadLuminosity", json!({})).unwrap(); + assert!(sel_at(&s, 5, 5) < 0.01, "black: unselected"); + assert!(sel_at(&s, 30, 5) > 0.99, "white: selected"); +} + #[test] fn thumbnail_selection_shape_without_pixel_cache_uses_its_transparency() { for depth in [8, 16, 32] { diff --git a/crates/engine/src/extra_cmds.rs b/crates/engine/src/extra_cmds.rs index cebb9ec890..251acfb3f4 100644 --- a/crates/engine/src/extra_cmds.rs +++ b/crates/engine/src/extra_cmds.rs @@ -566,6 +566,35 @@ fn set_visible(s: &mut Session, p: &Value, visible: bool) -> Result { Ok(Value::Null) } +/// Layer › Hide Layers (⌘,): hide the targeted layers, or show them when every one is already +/// hidden, as Photoshop's item does (it reads Show Layers then), so ⌘, toggles. +fn hide_or_show(s: &mut Session, p: &Value) -> Result { + let st = s.active().ok_or(EngineError::NoDocument)?; + let targets = if crate::layer_multi_cmds::multi(s, p) { crate::layer_multi_cmds::selected(s) } else { vec![layer_param(s, p)?] }; + let all_hidden = targets.iter().all(|id| st.doc.layer(*id).is_some_and(|l| !l.visible)); + set_visible(s, p, all_hidden) +} + +/// `/`: Lock Transparent Pixels on or off for the targeted layers, as the Layers panel's first lock +/// button does. With several layers targeted, any unlocked one means lock them all. The +/// Background, which can't take this lock, is left out. +fn toggle_lock_transparency(s: &mut Session, p: &Value) -> Result { + let st = s.active().ok_or(EngineError::NoDocument)?; + let targets: Vec = if crate::layer_multi_cmds::multi(s, p) { crate::layer_multi_cmds::selected(s) } else { vec![layer_param(s, p)?] }; + let targets: Vec = targets.into_iter().filter(|id| st.doc.layer(*id).is_some_and(|l| !st.doc.is_background(l.id))).collect(); + if targets.is_empty() { + return Err(EngineError::Other("the Background layer can't lock transparent pixels".into())); + } + let lock = !targets.iter().all(|id| st.doc.layer(*id).is_some_and(|l| l.locks.transparency)); + s.edit(if lock { "Lock Transparent Pixels" } else { "Unlock Transparent Pixels" }, |doc, _| { + for id in &targets { + doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?.locks.transparency = lock; + } + Ok(()) + })?; + Ok(json!({"locked": lock})) +} + /// Is the layer at `path` shown alone: it and its enclosing groups visible, every layer outside /// it hidden (the layers inside a group keep their own visibility)? fn shown_alone(doc: &Document, path: &[usize]) -> bool { @@ -916,8 +945,25 @@ pub fn specs() -> Vec { }, ungroup ), - spec!("layer.hideLayers", "Hide Layers", &["Layer"], Some("Cmd+,"), r##"{"layer":id?}"##, has_layer, |s, p| set_visible(s, p, false)), + spec!( + "layer.hideLayers", + "Hide Layers", + &["Layer"], + Some("Cmd+,"), + r##"{"layer":id?} (shows them instead when every targeted layer is already hidden, so ⌘, toggles)"##, + has_layer, + hide_or_show + ), spec!("layer.showLayers", "Show Layers", &[], None, r##"{"layer":id?}"##, has_layer, |s, p| set_visible(s, p, true)), + spec!( + "layer.toggleLockTransparency", + "Lock Transparent Pixels", + &[], + Some("/"), + r##"{"layer":id?} (toggles; several layers selected: locks them all unless every one is locked)"##, + has_layer, + toggle_lock_transparency + ), spec!( "layer.showOnly", "Show Only This Layer", @@ -1496,6 +1542,48 @@ mod tests { assert_eq!(doc(&s).layers[0].name, "Background"); } + #[test] + fn hide_layers_toggles_once_every_target_is_hidden() { + let mut s = session(8); + s.execute("layer.new.layer", json!({})).unwrap(); + let b = active(&s).id; + let visible = |s: &Session| doc(s).layer(b).unwrap().visible; + // Select › All Layers leaves out the Background, as in Photoshop. + let all = |s: &Session| crate::layer_multi_cmds::selected(s).iter().map(|id| doc(s).layer(*id).unwrap().visible).collect::>(); + s.execute("layer.hideLayers", json!({})).unwrap(); + assert!(!visible(&s)); + s.execute("layer.hideLayers", json!({})).unwrap(); + assert!(visible(&s), "⌘, again shows it"); + // Several selected: any one still shown means hide them all; then they all come back. + s.execute("layer.hideLayers", json!({"layer": b.0})).unwrap(); + s.execute("select.allLayers", json!({})).unwrap(); + assert!(all(&s).len() > 1); + s.execute("layer.hideLayers", json!({})).unwrap(); + assert!(all(&s).iter().all(|v| !v)); + s.execute("layer.hideLayers", json!({})).unwrap(); + assert!(all(&s).iter().all(|v| *v)); + } + + #[test] + fn slash_toggles_lock_transparent_pixels_but_not_on_the_background() { + let mut s = session(8); + let bg = doc(&s).layers[0].id; + assert!(doc(&s).is_background(bg)); + s.execute("layer.new.layer", json!({})).unwrap(); + let top = active(&s).id; + let locked = |s: &Session, id: LayerId| doc(s).layer(id).unwrap().locks.transparency; + assert_eq!(s.execute("layer.toggleLockTransparency", json!({})).unwrap()["locked"], true); + assert!(locked(&s, top)); + s.execute("layer.toggleLockTransparency", json!({})).unwrap(); + assert!(!locked(&s, top)); + s.undo(); + assert!(locked(&s, top), "one undoable step each"); + let bg_locks = doc(&s).layer(bg).unwrap().locks; + assert!(s.execute("layer.toggleLockTransparency", json!({"layer": bg.0})).is_err()); + assert_eq!(doc(&s).layer(bg).unwrap().locks, bg_locks, "the Background is left alone"); + assert!(s.execute("layer.toggleLockTransparency", json!({"layer": 999_999})).is_err()); + } + #[test] fn layer_utilities() { let mut s = session(8); diff --git a/crates/engine/src/fill_key_cmds.rs b/crates/engine/src/fill_key_cmds.rs index 6235b629bb..2ae2fe4dfa 100644 --- a/crates/engine/src/fill_key_cmds.rs +++ b/crates/engine/src/fill_key_cmds.rs @@ -1,5 +1,6 @@ //! Photoshop's fill keys (#249): ⌥⌫ fills the selection (or the whole layer) with the foreground -//! colour, ⌘⌫ with the background colour, and with ⇧ added they preserve transparency. Photoshop +//! colour, ⌘⌫ with the background colour, and with ⇧ added they preserve transparency. ⌘⌥⌫ fills +//! from history: the History Brush's source state (the oldest state still held). Photoshop //! has no menu item for them; here they are ordinary commands with default shortcuts, so they //! appear in Edit › Keyboard Shortcuts (Tools) and can be rebound, recorded and driven by agents. //! @@ -12,7 +13,7 @@ use crate::commands::CommandSpec; use crate::{EngineError, Result, Session}; /// The fill-key command ids (routed to the Channels panel target like `edit.fill`). -pub const IDS: [&str; 4] = ["edit.fillForeground", "edit.fillBackground", "edit.fillForegroundPreserve", "edit.fillBackgroundPreserve"]; +pub const IDS: [&str; 5] = ["edit.fillForeground", "edit.fillBackground", "edit.fillForegroundPreserve", "edit.fillBackgroundPreserve", "edit.fillHistory"]; const PARAMS: &str = r##"{"layer":id?,"target":"pixels"|"mask"|"quickMask"|{"channel":i}?}"##; @@ -39,6 +40,22 @@ fn fill(s: &mut Session, p: &Value, cmd: &str, background: bool, preserve: bool) (edit_fill.run)(s, &Value::Object(q)) } +/// ⌘⌥⌫: `edit.fill` from history, the History Brush's source unless `state` names another. +fn fill_history(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "edit.fillHistory"; + let mut q: Map = match p { + Value::Object(m) => m.clone(), + Value::Null => Map::new(), + _ => return Err(EngineError::BadParams { cmd: CMD.into(), msg: "expected an object".into() }), + }; + for k in ["color", "contents", "pattern"] { + q.remove(k); + } + q.insert("contents".into(), json!("history")); + let edit_fill = crate::commands::find("edit.fill").ok_or_else(|| EngineError::Other("Fill is unavailable".into()))?; + (edit_fill.run)(s, &Value::Object(q)) +} + pub fn specs() -> Vec { vec![ CommandSpec { @@ -81,6 +98,16 @@ pub fn specs() -> Vec { run: |s, p| fill(s, p, "edit.fillBackgroundPreserve", true, true), journal: true, }, + CommandSpec { + id: "edit.fillHistory", + label: "Fill from History", + menu: &[], + shortcut: Some("Cmd+Alt+Backspace"), + params: r##"{"state":n? (default: the History Brush's source, the oldest state still held),"layer":id?,"target":"pixels"|"mask"|"quickMask"|{"channel":i}?,"preserveTransparency":bool?}"##, + enabled, + run: fill_history, + journal: true, + }, ] } @@ -133,6 +160,27 @@ mod tests { } } + #[test] + fn fill_from_history_restores_the_history_brush_source_in_the_selection() { + let mut s = session(); + assert_eq!(crate::commands::find("edit.fillHistory").and_then(|c| c.shortcut), Some("Cmd+Alt+Backspace")); + s.execute("edit.fillForeground", json!({})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 4, "height": 6})).unwrap(); + s.execute("edit.fillHistory", json!({})).unwrap(); + // The oldest state (the new, transparent layer) comes back inside the selection only. + assert_eq!(px(&s, 1, 1)[3], 0.0); + assert_eq!(px(&s, 6, 1), [1.0, 0.0, 0.0, 1.0]); + // A named state, and refused ones change nothing. + s.execute("select.deselect", json!({})).unwrap(); + let steps = s.active().unwrap().history.past_len(); + for bad in [json!({"state": 99}), json!({"state": "x"}), json!(7)] { + assert!(s.execute("edit.fillHistory", bad.clone()).is_err(), "{bad}"); + } + assert_eq!(s.active().unwrap().history.past_len(), steps); + s.execute("edit.fillHistory", json!({"state": 1})).unwrap(); + assert_eq!(px(&s, 1, 1), [1.0, 0.0, 0.0, 1.0], "state 1 is after the foreground fill"); + } + #[test] fn background_fills_only_the_selection() { let mut s = session(); diff --git a/crates/ui-egui/src/layer_row_ui.rs b/crates/ui-egui/src/layer_row_ui.rs index d265690597..fb229fcbc8 100644 --- a/crates/ui-egui/src/layer_row_ui.rs +++ b/crates/ui-egui/src/layer_row_ui.rs @@ -295,8 +295,20 @@ pub fn end_rename(ctx: &egui::Context, commit: bool) -> Option<(String, Value)> if commit { r.commit_action() } else { None } } +/// Where Tab or ⇧Tab sends a rename: the layer it left and whether the next one is above. +fn next_rename_id() -> egui::Id { + egui::Id::new("layer-rename-next") +} + +/// The rename that Tab (`up` false) or ⇧Tab (`up` true) just left on `layer`, for the Layers panel +/// to continue on the layer below or above, as Photoshop does. Taken once. +pub fn take_next_rename(ctx: &egui::Context) -> Option<(u64, bool)> { + ctx.data_mut(|d| d.remove_temp::<(u64, bool)>(next_rename_id())) +} + /// Draw the rename field of `layer` in `rect` when it is the one being renamed, and handle its -/// keys and focus. Returns the rename command when it was committed this frame. +/// keys and focus. Returns the rename command when it was committed this frame. Tab and ⇧Tab +/// commit too and ask for the next rename ([`take_next_rename`]). pub fn rename_field(ui: &mut egui::Ui, layer: u64, rect: Rect) -> Option<(String, Value)> { let ctx = ui.ctx().clone(); let mut r = rename(&ctx).filter(|r| r.layer == layer)?; @@ -316,6 +328,10 @@ pub fn rename_field(ui: &mut egui::Ui, layer: u64, rect: Rect) -> Option<(String return None; } let (enter, tab, esc) = ctx.input(|i| (i.key_pressed(egui::Key::Enter), i.key_pressed(egui::Key::Tab), i.key_pressed(egui::Key::Escape))); + if tab { + let up = ctx.input(|i| i.modifiers.shift); + ctx.data_mut(|d| d.insert_temp(next_rename_id(), (layer, up))); + } if esc { store(&ctx, None); None diff --git a/crates/ui-egui/src/layer_row_ui/rename_tests.rs b/crates/ui-egui/src/layer_row_ui/rename_tests.rs index a4e985a293..4a7ea135ff 100644 --- a/crates/ui-egui/src/layer_row_ui/rename_tests.rs +++ b/crates/ui-egui/src/layer_row_ui/rename_tests.rs @@ -1,6 +1,7 @@ //! #314: renaming a layer in place works like Photoshop. A click anywhere else, Enter or Tab //! commits; Esc cancels; only one rename is open at a time, and starting another (double-click, -//! the context menu or Layer › Rename Layer) commits the first. +//! the context menu or Layer › Rename Layer) commits the first. Tab then renames the layer below, +//! ⇧Tab the layer above. use egui::{Event, Key, Modifiers, PointerButton, Pos2, pos2, vec2}; use egui_kittest::Harness; @@ -127,7 +128,8 @@ fn enter_and_tab_commit_and_escape_cancels() { start(&mut h, b); type_text(&mut h, "By Tab"); key(&mut h, Key::Tab); - assert_eq!((name(&h, b), renaming(&h.ctx)), ("By Tab".into(), None)); + assert_eq!((name(&h, b), renaming(&h.ctx)), ("By Tab".into(), Some(a)), "Tab commits and renames the layer below"); + key(&mut h, Key::Escape); start(&mut h, c); type_text(&mut h, "Never"); @@ -143,6 +145,28 @@ fn enter_and_tab_commit_and_escape_cancels() { assert_eq!(name(&h, c), "Gamma"); } +#[test] +fn shift_tab_renames_the_layer_above_and_tab_at_the_bottom_ends() { + let (mut h, [a, b, c]) = harness(1.0); + start(&mut h, b); + type_text(&mut h, "Middle"); + h.event(Event::ModifiersChanged(Modifiers::SHIFT)); + h.event(Event::Key { key: Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::SHIFT }); + h.event(Event::Key { key: Key::Tab, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::SHIFT }); + h.run_steps(1); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(2); + assert_eq!((name(&h, b), renaming(&h.ctx)), ("Middle".into(), Some(c)), "⇧Tab renames the layer above"); + // Typing replaces the next layer's name too, as the whole name starts selected. + type_text(&mut h, "Top"); + key(&mut h, Key::Enter); + assert_eq!((name(&h, c), renaming(&h.ctx)), ("Top".into(), None)); + // Tab from the lowest layer ends the rename: the Background below isn't renamed in place. + start(&mut h, a); + key(&mut h, Key::Tab); + assert_eq!(renaming(&h.ctx), None); +} + #[test] fn starting_another_rename_commits_the_first_and_only_one_is_open() { for ppp in [1.0, 2.0] { diff --git a/crates/ui-egui/src/layer_shortcut_tests.rs b/crates/ui-egui/src/layer_shortcut_tests.rs new file mode 100644 index 0000000000..a363c340bf --- /dev/null +++ b/crates/ui-egui/src/layer_shortcut_tests.rs @@ -0,0 +1,124 @@ +//! Photoshop's layer and selection keys reach their commands: ⌘, toggles visibility, ⌘\ targets +//! the mask, / toggles Lock Transparent Pixels, ⌘⌥2 loads luminosity, ⌘⌥⌫ fills from history. + +use egui::{Key, Modifiers}; +use serde_json::json; + +use crate::PhotocraftApp; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 20, "height": 10})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app +} + +fn press(app: &mut PhotocraftApp, key: Key, modifiers: Modifiers) { + let ctx = egui::Context::default(); + let raw = egui::RawInput { + events: vec![egui::Event::ModifiersChanged(modifiers), egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }], + ..Default::default() + }; + ctx.begin_pass(raw); + crate::shortcuts::handle(app, &ctx); + ctx.end_pass().textures_delta.clear(); +} + +fn active(app: &PhotocraftApp) -> &photocraft_doc::Layer { + let st = app.session.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap() +} + +#[test] +fn command_comma_toggles_the_layers_visibility() { + let mut app = app(); + press(&mut app, Key::Comma, Modifiers::COMMAND); + assert!(!active(&app).visible); + press(&mut app, Key::Comma, Modifiers::COMMAND); + assert!(active(&app).visible); +} + +#[test] +fn slash_toggles_lock_transparent_pixels() { + let mut app = app(); + press(&mut app, Key::Slash, Modifiers::NONE); + assert!(active(&app).locks.transparency); + press(&mut app, Key::Slash, Modifiers::NONE); + assert!(!active(&app).locks.transparency); +} + +#[test] +fn command_backslash_targets_the_layer_mask() { + let mut app = app(); + app.run("layer.layerMask.revealAll", json!({})).unwrap(); + app.run("channel.target.composite", json!({})).unwrap(); + press(&mut app, Key::Backslash, Modifiers::COMMAND); + assert_eq!(app.session.active().unwrap().channel_view.target, photocraft_engine::channel_cmds::ChannelTarget::LayerMask); + assert!(app.ui.mask_target && app.layer_mask_targeted(), "the Layers panel targets the mask too"); + // Ctrl+2 goes back to the layer's pixels, in the Layers panel and for the tools. + press(&mut app, Key::Num2, Modifiers::COMMAND); + assert_eq!(app.session.active().unwrap().channel_view.target, photocraft_engine::channel_cmds::ChannelTarget::Composite); + assert!(!app.ui.mask_target && !app.layer_mask_targeted()); + // The same after targeting the mask by its thumbnail (the panel's own flag). + app.ui.mask_target = true; + app.sync_mask_targets(); + press(&mut app, Key::Num2, Modifiers::COMMAND); + assert!(!app.ui.mask_target && !app.layer_mask_targeted()); +} + +#[test] +fn command_alt_2_loads_luminosity() { + let mut app = app(); + press(&mut app, Key::Num2, Modifiers::COMMAND | Modifiers::ALT); + assert!(app.session.active().unwrap().doc.selection.is_some(), "the white image's luminosity selects it all"); +} + +#[test] +fn command_alt_backspace_fills_from_history() { + // The Background exists in the oldest state, so its pixels come back from there. + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 20, "height": 10})).unwrap(); + app.run("tools.setColors", json!({"foreground": "#ff0000"})).unwrap(); + app.run("edit.fillForeground", json!({})).unwrap(); + assert_eq!(active(&app).surface().unwrap().pixel(3, 3)[1], 0.0, "red"); + press(&mut app, Key::Backspace, Modifiers::COMMAND | Modifiers::ALT); + assert_eq!(active(&app).surface().unwrap().pixel(3, 3)[1], 1.0, "white again"); +} + +/// ⌥-click a layer's thumbnail: select it and fit its content on screen. +#[test] +fn alt_click_on_a_layer_thumbnail_fits_the_layer() { + use egui::{Event, PointerButton, pos2, vec2}; + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 400, "height": 300})).unwrap(); + let small = s.execute("layer.new.layer", json!({"name": "Small"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("select.rect", json!({"x": 300, "y": 200, "width": 20, "height": 10})).unwrap(); + s.execute("edit.fill", json!({"contents": "black"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Top"})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1440.0, 900.0)).with_step_dt(1.0 / 60.0).with_max_steps(64).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + PhotocraftApp::new(s, crate::Services::default()) + }); + let ctx = h.ctx.clone(); + let (r, _) = crate::control::ControlRequest::new("ui.set", json!({"dock": {"collapsed": ["color", "properties", "history", "navigator"]}})); + crate::control::handle(h.state_mut(), &ctx, &r); + h.run_steps(8); + let before = h.state().ui.views[0].clone(); + let row = crate::layer_row_ui::recorded(&h.ctx).into_iter().find(|r| r.layer == small).unwrap().row; + let at = pos2(row.left() + 46.0, row.center().y); + h.hover_at(at); + h.event(Event::ModifiersChanged(Modifiers::ALT)); + h.run_steps(1); + h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::ALT }); + h.run_steps(1); + h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::ALT }); + h.run_steps(1); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(3); + let app = h.state(); + assert_eq!(app.session.active().unwrap().active_layer, Some(photocraft_doc::LayerId(small))); + let v = &app.ui.views[0]; + assert_eq!(v.center, [310.0, 205.0], "centred on the layer's content"); + assert!(v.zoom > before.zoom * 4.0, "zoomed in on 20 × 10 px: {} -> {}", before.zoom, v.zoom); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 1115b94962..7705e35645 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -890,6 +890,16 @@ impl PhotocraftApp { if gate.is_some() { self.session.authorize = None; } + // An explicit channel target (⌘2, ⌘\, ⌘3…) decides what the Layers panel targets too: + // ⌘2 after the mask was targeted goes back to the layer's pixels. + if result.is_ok() && id.starts_with("channel.target") { + if let Some(t) = self.session.active().map(|st| st.channel_view.target) { + use photocraft_engine::channel_cmds::ChannelTarget; + self.ui.mask_target = t == ChannelTarget::LayerMask; + self.ui.vector_mask_target = t == ChannelTarget::VectorMask; + } + self.sync_mask_targets(); + } result } @@ -2266,6 +2276,8 @@ mod pen_variants_tests; #[cfg(test)] mod color_replacement_tests; #[cfg(test)] +mod layer_shortcut_tests; +#[cfg(test)] mod pencil_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 086d1c0604..d908af7afa 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -2254,6 +2254,16 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let below = Rect::from_min_max(pos2(last_rect.left(), last_rect.bottom()), pos2(last_rect.right(), ui.clip_rect().bottom())); layer_drop_zone(app, &ctx, ui, below, (last, last_rect), "below", &mut actions); } + // Tab / ⇧Tab in a rename: rename the layer below / above next, as in Photoshop. The + // Background isn't renamed in place (double-clicking it converts it), so it ends there. + if let Some((from, up)) = crate::layer_row_ui::take_next_rename(ui.ctx()) + && let Some(at) = drawn.iter().position(|(id, _)| id.0 == from) + && let Some(&(next, _)) = if up { at.checked_sub(1).and_then(|i| drawn.get(i)) } else { drawn.get(at + 1) } + && let Some(l) = doc.layer(next).filter(|l| !crate::doc_props_ui::is_background(&doc, l)) + && let Some(done) = crate::layer_row_ui::start_rename(ui.ctx(), next.0, &l.name) + { + actions.push(done); + } // ⌥-click the line between two layers: clip / release the upper one (#967). crate::clip_line_ui::show(ui, &doc, &mut actions); // A rename whose row is gone (deleted, filtered out, inside a closed group) ends, @@ -2754,6 +2764,11 @@ fn layer_row( } else if on_thumb || !row.primary { actions.push(("ui.maskTarget".into(), json!(false))); } + // ⌥-click the layer thumbnail: fit the layer on screen, as Photoshop does. + let m = ui.input(|i| i.modifiers); + if on_thumb && m.alt && !m.shift && !m.command { + actions.push(("view.fitLayersOnScreen".into(), Value::Null)); + } } // Double-click: the name renames in place (over the row's full height, not just the glyphs: // #651); the Background, which can't be renamed while it's locked, becomes a normal layer; an diff --git a/docs/ui-parity.md b/docs/ui-parity.md index d168db4dff..3daee822c7 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity: tools, handles, modifiers and feel -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** minor (⇧-dragged guides land on ruler ticks) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-11 · **Change:** minor (⇧-dragged guides land on ruler ticks; layer and selection keys) · **Target:** Adobe Photoshop 2026 How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, the handles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation, @@ -183,6 +183,7 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme | `.kys` import | done (`engine/src/kys.rs`) | | | Shortcut glyphs per platform | done (UI-217-19) | | | Brush size/hardness keys on non-US layouts | done (#3109): `[` `]` need AltGr on many layouts, so Photoshop uses other keys there (German: Ö / #, ⇧ for hardness). `layout_keys.rs` has a data table of such layouts (`LAYOUTS`, add rows to support one more) and a fallback for all others: the keys at the US `[` / `]` positions act as `[` / `]` when they don't type brackets. Off once a real bracket is typed; Edit › Keyboard Shortcuts overrides still apply | | +| Layer and selection keys: ⌘, toggles visibility, ⌘\ targets the mask, / locks transparency, ⌘⌥2 loads luminosity, ⌘⌥⌫ fills from history, Tab / ⇧Tab rename the next layer, ⌥-click a thumbnail fits the layer | done (2026-10-11) | | ## Panels and workspace @@ -215,3 +216,4 @@ Paragraph; the rest open as in-app floating windows. | 2026-10-11 | minor | Flick panning done: releasing a moving Hand drag (tool, Space or middle button) glides and decays, gated by Enable Flick Panning | | 2026-10-11 | minor | History snapshots: the camera button takes one, snapshot rows return to it as a new state, rename and delete it (#2966) | | 2026-10-11 | minor | ⇧-drag a guide out of a ruler lands on the nearest ruler tick (#3770) | +| 2026-10-11 | minor | Layer and selection keys from Photoshop's shortcut set: ⌘, toggles, ⌘\, /, ⌘⌥2, ⌘⌥⌫, Tab rename-next, ⌥-click thumbnail to fit | From edc1b1e77412decd51a5d61f295fe51677187b14 Mon Sep 17 00:00:00 2001 From: JGF <44821497+bommerts@users.noreply.github.com> Date: Mon, 12 Oct 2026 07:47:33 -0400 Subject: [PATCH 15/24] View: remember Extras, Show and Snap To across restarts (#3762) (#3787) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * View: remember Extras, Show and Snap To across restarts (#3762) View › Extras, the View › Show items (Pixel Grid, Grid, Guides, …) and the View › Snap To targets reset to their defaults on every launch. They are now saved in Preferences (`viewExtras`) as they change and restored at startup, as Photoshop keeps them between sessions. Only items that differ from their defaults are stored, so a default changed in a later release still reaches users who never touched it. A hand-edited file can't break them: unknown keys and non-boolean values keep their defaults. Co-Authored-By: Claude Opus 5.5 * View: rustfmt the view-extras restart test (#3762) Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/prefs.rs | 4 ++ crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/prefs_ui.rs | 34 +++++++++++ crates/ui-egui/src/view_cmds.rs | 100 ++++++++++++++++++++++++++++++++ 4 files changed, 140 insertions(+) diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 93a52d2d10..c99c3cbb71 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -994,6 +994,10 @@ pub struct Preferences { /// differ from their defaults, saved as the user changes them and restored at launch, as /// Photoshop remembers each tool's options between sessions. JSON owned by the shell. pub tool_options: Value, + /// View › Extras, the View › Show items (Pixel Grid, Grid, Guides, …) and the View › Snap To + /// targets that differ from their defaults, saved as the user toggles them and restored at + /// launch, as Photoshop keeps them between sessions (#3762). JSON owned by the shell. + pub view_extras: Value, /// File › Scripts › Script Events Manager: event → script bindings. pub script_events: crate::automate_cmds::ScriptEvents, } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7705e35645..323d559a8e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1725,6 +1725,8 @@ impl eframe::App for PhotocraftApp { brush_picker::persist(self, &ctx); // Tool options are remembered between launches the same way (#2814). tool_memory::persist(self, &ctx); + // So are View › Extras, Show and Snap To (#3762). + view_cmds::persist(self, &ctx); self.automation_input = false; shape_stroke_ui::finish_frame(self, &ctx); native_menu::sync(self, &ctx); diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rs index 5b15e7bc9c..202944b58a 100644 --- a/crates/ui-egui/src/prefs_ui.rs +++ b/crates/ui-egui/src/prefs_ui.rs @@ -218,6 +218,7 @@ pub fn load(app: &mut PhotocraftApp) { crate::brush_picker::restore(app); sync_rulers(app); crate::tool_memory::restore(app); + crate::view_cmds::restore(app); app.sync_recent(); app.prefs_rt.saved_rev = app.session.prefs.rev(); app.prefs_rt.saved_value = Some(app.session.prefs_value()); @@ -2649,6 +2650,39 @@ mod tests { } } + #[test] + fn view_show_items_survive_a_restart() { + let (mut app, store) = app_with_store(); + let ctx = egui::Context::default(); + tick(&mut app, &ctx); + // Untouched: nothing is stored, so later default changes still reach the user. + crate::view_cmds::persist(&mut app, &ctx); + tick(&mut app, &ctx); + assert!(stored(&store).get("viewExtras").is_none_or(Value::is_null)); + // The menu commands, as a user toggles them (#3762: Pixel Grid off). + for id in ["view.show.pixelGrid", "view.show.grid", "view.snapTo.layers", "view.extras"] { + crate::menus::invoke(&mut app, &ctx, id, json!({})).unwrap(); + } + crate::view_cmds::persist(&mut app, &ctx); + tick(&mut app, &ctx); + assert_eq!(stored(&store)["viewExtras"], json!({"extras": false, "grid": true, "show": {"pixelGrid": false}, "snapTo": {"layers": false}})); + // A restart gets them back. + let saved = store.lock().unwrap().clone().unwrap(); + let (mut app2, _) = app_with_saved(Some(saved)); + tick(&mut app2, &ctx); + let v = &app2.ui.view; + assert!(!v.extras && !v.show.pixel_grid && !v.snap_to.layers && app2.ui.extras.grid); + assert!(v.show.selection_edges && v.snap_to.guides && app2.ui.extras.guides, "the rest keep their defaults"); + // A hand-edited file: unknown keys and non-booleans keep the defaults, good ones still load. + for bad in [json!("junk"), json!({"extras": 0, "show": {"pixelGrid": "no", "mesh": true, "bogus": true}, "snapTo": [1]})] { + let (mut app3, _) = app_with_saved(Some(json!({"viewExtras": bad}).to_string())); + tick(&mut app3, &ctx); + let v = &app3.ui.view; + assert!(v.extras && v.show.pixel_grid && v.snap_to.layers, "{bad}"); + assert_eq!(v.show.mesh, bad.is_object()); + } + } + #[test] fn show_tooltips_preferences_turn_tooltips_off() { let (mut app, _) = app_with_store(); diff --git a/crates/ui-egui/src/view_cmds.rs b/crates/ui-egui/src/view_cmds.rs index f0404633cf..cb75e28032 100644 --- a/crates/ui-egui/src/view_cmds.rs +++ b/crates/ui-egui/src/view_cmds.rs @@ -214,6 +214,106 @@ fn snap_slot<'a>(s: &'a mut SnapTo, key: &str) -> Option<&'a mut bool> { }) } +/// Every [`show_slot`] key. +const SHOW_KEYS: [&str; 13] = [ + "layerEdges", + "selectionEdges", + "targetPath", + "pixelGrid", + "smartGuides", + "brushPreview", + "slices", + "notes", + "mesh", + "editPins", + "count", + "canvasGuides", + "artboardGuides", +]; +/// Every [`snap_slot`] key. +const SNAP_KEYS: [&str; 5] = ["guides", "grid", "layers", "slices", "documentBounds"]; + +/// The flags of `now` that differ from `def`, by key (`None` when none do). +fn changed_flags(now: T, def: T, keys: &[&str], slot: impl for<'a> Fn(&'a mut T, &str) -> Option<&'a mut bool>) -> Option { + let (mut now, mut def) = (now, def); + let diff: Map = keys + .iter() + .filter_map(|k| { + let v = *slot(&mut now, k)?; + (Some(v) != slot(&mut def, k).copied()).then(|| ((*k).to_string(), Value::Bool(v))) + }) + .collect(); + (!diff.is_empty()).then_some(Value::Object(diff)) +} + +/// View › Extras, Show and Snap To as remembered across restarts (`Preferences::view_extras`): +/// only what differs from the defaults, so a default changed in a later release still reaches +/// users who never touched that item. `Null` when nothing differs. +fn remembered(app: &PhotocraftApp) -> Value { + let (v, e, def) = (&app.ui.view, &app.ui.extras, crate::state::Extras::default()); + let mut m = Map::new(); + if v.extras != ViewOptions::default().extras { + m.insert("extras".into(), Value::Bool(v.extras)); + } + // View › Show › Grid and Guides live in `UiState::extras` beside the rulers and snapping. + if e.grid != def.grid { + m.insert("grid".into(), Value::Bool(e.grid)); + } + if e.guides != def.guides { + m.insert("guides".into(), Value::Bool(e.guides)); + } + if let Some(show) = changed_flags(v.show, Show::default(), &SHOW_KEYS, show_slot) { + m.insert("show".into(), show); + } + if let Some(snap) = changed_flags(v.snap_to, SnapTo::default(), &SNAP_KEYS, snap_slot) { + m.insert("snapTo".into(), snap); + } + if m.is_empty() { Value::Null } else { Value::Object(m) } +} + +/// Remember View › Extras, Show and Snap To in the preferences once the user lets go of the +/// pointer (#3762). Cheap: a small JSON compare per frame. Run every frame, so items set by the +/// control channel or the Show Extras Options dialog are remembered too. +pub fn persist(app: &mut PhotocraftApp, ctx: &egui::Context) { + if ctx.input(|i| i.pointer.any_down()) { + return; + } + let now = remembered(app); + if app.session.prefs().view_extras != now { + app.session.prefs.edit(|p| p.view_extras = now); + } +} + +/// Restore the remembered View › Extras, Show and Snap To items at launch. A hand-edited file +/// can't break them: an unknown key or a value that isn't a boolean keeps its default. +pub fn restore(app: &mut PhotocraftApp) { + let saved = app.session.prefs().view_extras.clone(); + if !saved.is_null() && !saved.is_object() { + log::warn!("Preferences: the remembered View › Show items are not an object; using the defaults"); + return; + } + let flag = |k: &str| saved.get(k).and_then(Value::as_bool); + if let Some(on) = flag("extras") { + app.ui.view.extras = on; + } + if let Some(on) = flag("grid") { + app.ui.extras.grid = on; + } + if let Some(on) = flag("guides") { + app.ui.extras.guides = on; + } + for (k, v) in saved.get("show").and_then(Value::as_object).into_iter().flatten() { + if let (Some(slot), Some(on)) = (show_slot(&mut app.ui.view.show, k), v.as_bool()) { + *slot = on; + } + } + for (k, v) in saved.get("snapTo").and_then(Value::as_object).into_iter().flatten() { + if let (Some(slot), Some(on)) = (snap_slot(&mut app.ui.view.snap_to, k), v.as_bool()) { + *slot = on; + } + } +} + /// Window › : (panel, dock tab) for panels that live as tabs of a dock card. fn panel_tab(app: &PhotocraftApp, id: &str) -> Option<(&'static str, usize)> { let pro = app.ui.theme.is_pro(); From 224cebbd8ab104f1c94f7008a80ee14eddee0219 Mon Sep 17 00:00:00 2001 From: buivanvu94 <125793064+buivanvu94@users.noreply.github.com> Date: Mon, 12 Oct 2026 18:48:03 +0700 Subject: [PATCH 16/24] fix(automation): warn when text falls back from a missing font (#3391) (#3630) * fix(automation): warn when text falls back from a missing font (#3391) * cargo fmt Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Brandon Thomas Co-authored-by: Claude Opus 5.5 --- apps/photocraft-cli/src/lib.rs | 2 +- crates/automation/src/headless.rs | 7 ++- .../automation/tests/missing_font_warnings.rs | 57 +++++++++++++++++++ crates/engine/src/type_cmds.rs | 36 +++++++++++- crates/engine/src/type_extra_cmds.rs | 27 +++++++++ 5 files changed, 123 insertions(+), 6 deletions(-) create mode 100644 crates/automation/tests/missing_font_warnings.rs diff --git a/apps/photocraft-cli/src/lib.rs b/apps/photocraft-cli/src/lib.rs index 1743665d90..560eaf71fc 100644 --- a/apps/photocraft-cli/src/lib.rs +++ b/apps/photocraft-cli/src/lib.rs @@ -240,7 +240,7 @@ fn convert(a: &Args, _out: &mut dyn Write, err: &mut dyn Write) -> R { let opts = export_opts(a)?; let o = files::open(Path::new(input)).map_err(|e| e.to_string())?; warn_all(err, &o.warnings); - warn_all(err, &missing_font_warnings(photocraft_engine::type_extra_cmds::missing_fonts(&o.document))); + warn_all(err, &photocraft_engine::type_extra_cmds::missing_font_warnings(&o.document)); let ws = files::save(&o.document, Path::new(output), a.get("--format"), &opts, None).map_err(|e| e.to_string())?; warn_all(err, &ws); Ok(()) diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index dc18afe2f2..cd92f584a2 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -96,13 +96,15 @@ impl Headless { st.source_read_only = o.source_read_only; } let d = &self.session.documents()[index]; + let mut warnings = o.warnings; + warnings.extend(photocraft_engine::type_extra_cmds::missing_font_warnings(&d.doc)); Ok(json!({ "index": index, "name": d.doc.name, "width": d.doc.size.width, "height": d.doc.size.height, "layers": d.doc.layer_count(), - "warnings": o.warnings, + "warnings": warnings, })) } @@ -240,7 +242,7 @@ impl Headless { } }; let target_text = target.to_str().ok_or_else(|| AutomationError::BadRequest("automation paths must be valid UTF-8".into()))?; - let warnings = match &self.filesystem { + let mut warnings = match &self.filesystem { Filesystem::Denied => return Err(AutomationError::BadRequest("automation filesystem access is not granted: write authority is absent".into())), Filesystem::TrustedLocal => { let writer = self.writers.entry(doc.id.0).or_default(); @@ -252,6 +254,7 @@ impl Headless { warnings } }; + warnings.extend(photocraft_engine::type_extra_cmds::missing_font_warnings(&doc)); // A layered document save (PSD, PSB, OpenRaster or .pcraft) is a full write, not a flattened copy: // record the current revision as saved so the session stops reporting `dirty`, and make // the file the document's path. A flat export (PNG, JPEG, …) is a copy and leaves both diff --git a/crates/automation/tests/missing_font_warnings.rs b/crates/automation/tests/missing_font_warnings.rs new file mode 100644 index 0000000000..fe66e5c062 --- /dev/null +++ b/crates/automation/tests/missing_font_warnings.rs @@ -0,0 +1,57 @@ +//! #3391: `doc.save`, `doc.open`, and type commands emit warnings when text uses a missing font. + +use photocraft_automation::Headless; +use serde_json::json; + +fn tmp_dir() -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!( + "pc-font-warn-{}-{}", + std::process::id(), + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos() + )); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +#[test] +fn missing_font_warnings_emitted_in_headless_and_type_commands() { + let dir = tmp_dir(); + let psd_path = dir.join("card.psd"); + let png_path = dir.join("card.png"); + + let mut h = Headless::trusted_local(); + h.handle("doc.new", json!({"width": 600, "height": 300, "background": "white"})).unwrap(); + + // 1. type.create with missing font + let created = h + .handle("engine.execute", json!({"command": "type.create", "params": {"x": 30, "y": 100, "text": "Headline", "font": "NoSuchFamily123", "size": 40}})) + .unwrap(); + assert_eq!(created["warnings"], json!(["font 'NoSuchFamily123' is not installed; text may render using a fallback face"])); + + // 2. doc.save card.psd + let saved_psd = h.handle("doc.save", json!({"path": psd_path.to_str().unwrap()})).unwrap(); + let warnings = saved_psd["warnings"].as_array().expect("warnings array in doc.save"); + assert!( + warnings.iter().any(|w| w == "font 'NoSuchFamily123' is not installed; text may render using a fallback face"), + "doc.save PSD warning: {saved_psd}" + ); + + // 3. doc.save card.png + let saved_png = h.handle("doc.save", json!({"path": png_path.to_str().unwrap()})).unwrap(); + let warnings = saved_png["warnings"].as_array().expect("warnings array in doc.save"); + assert!( + warnings.iter().any(|w| w == "font 'NoSuchFamily123' is not installed; text may render using a fallback face"), + "doc.save PNG warning: {saved_png}" + ); + + // 4. doc.close then doc.open + h.handle("doc.close", json!({})).unwrap(); + let opened = h.handle("doc.open", json!({"path": psd_path.to_str().unwrap()})).unwrap(); + let warnings = opened["warnings"].as_array().expect("warnings array in doc.open"); + assert!( + warnings.iter().any(|w| w.as_str().unwrap_or("").contains("is not installed; text may render using a fallback face")), + "doc.open warning: {opened}" + ); + + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/engine/src/type_cmds.rs b/crates/engine/src/type_cmds.rs index e59ce9258e..4a4cb347bf 100644 --- a/crates/engine/src/type_cmds.rs +++ b/crates/engine/src/type_cmds.rs @@ -639,7 +639,8 @@ fn info(s: &Session, p: &Value) -> Result { .map(|ln| json!({ "start": char_at(text, ln.range.start), "end": char_at(text, ln.range.end), "baseline": ln.baseline, "x0": ln.x0, "x1": ln.x1, "ascent": ln.ascent, "descent": ln.descent })) .collect(); let bounds = t.cache.as_ref().map(|c| c.content_bounds()).map(|r| json!([r.x0, r.y0, r.x1, r.y1])); - Ok(json!({ + let warnings = crate::type_extra_cmds::missing_font_warnings_for_layer(t); + let mut out = json!({ "layer": id.0, "text": text, "shape": t.shape, @@ -652,7 +653,11 @@ fn info(s: &Session, p: &Value) -> Result { "lines": lines, "bounds": bounds, "pxPerPt": layout.px_per_pt, - })) + }); + if !warnings.is_empty() { + out["warnings"] = json!(warnings); + } + Ok(out) } /// A type layer (not yet rendered or added) from `type.create`'s params: text, point `x`/`y` or @@ -723,7 +728,14 @@ pub fn specs() -> Vec { Ok(id) })?; let bounds = s.active().and_then(|d| d.doc.layer(id)).and_then(|l| l.surface()).map(|c| c.content_bounds()); - Ok(json!({ "layer": id.0, "bounds": bounds.map(|r| [r.x0, r.y0, r.x1, r.y1]) })) + let mut out = json!({ "layer": id.0, "bounds": bounds.map(|r| [r.x0, r.y0, r.x1, r.y1]) }); + if let Some(LayerContent::Text(t)) = s.active().and_then(|d| d.doc.layer(id)).map(|l| &l.content) { + let warnings = crate::type_extra_cmds::missing_font_warnings_for_layer(t); + if !warnings.is_empty() { + out["warnings"] = json!(warnings); + } + } + Ok(out) }, }, CommandSpec { @@ -1582,4 +1594,22 @@ mod tests { assert!(s.active().unwrap().doc.layer(LayerId(id)).is_none()); } } + + #[test] + fn missing_font_emits_warning_in_create_set_style_and_edit() { + let mut s = session(); + let r = s.execute("type.create", json!({"x": 10, "y": 20, "text": "Hello", "font": "NoSuchFamily123"})).unwrap(); + assert_eq!(r["warnings"], json!(["font 'NoSuchFamily123' is not installed; text may render using a fallback face"])); + let id = r["layer"].as_u64().unwrap(); + let styled = s.execute("type.setStyle", json!({"layer": id, "font": "StillNoSuchFamily456"})).unwrap(); + assert_eq!(styled["warnings"], json!(["font 'StillNoSuchFamily456' is not installed; text may render using a fallback face"])); + let edited = s.execute("type.edit", json!({"layer": id, "runs": [{"start": 0, "end": 2, "font": "AnotherMissingFont789"}]})).unwrap(); + assert_eq!( + edited["warnings"], + json!([ + "font 'AnotherMissingFont789' is not installed; text may render using a fallback face", + "font 'StillNoSuchFamily456' is not installed; text may render using a fallback face" + ]) + ); + } } diff --git a/crates/engine/src/type_extra_cmds.rs b/crates/engine/src/type_extra_cmds.rs index 022146f113..e460a975b6 100644 --- a/crates/engine/src/type_extra_cmds.rs +++ b/crates/engine/src/type_extra_cmds.rs @@ -436,6 +436,33 @@ pub fn missing_fonts(doc: &Document) -> Vec { out } +/// Font families used by a type layer that the font database cannot supply. +pub fn missing_fonts_in_layer(t: &TextLayer) -> Vec { + let have = installed_families(); + let mut out: Vec = Vec::new(); + for r in t.char_runs() { + let f = r.style.font_family; + if !f.is_empty() && !have.contains(&f.to_lowercase()) && !out.contains(&f) { + out.push(f); + } + } + out +} + +/// Warnings for missing font families in `doc`. +pub fn missing_font_warnings(doc: &Document) -> Vec { + fonts_to_warnings(missing_fonts(doc)) +} + +/// Warnings for missing font families in `layer`. +pub fn missing_font_warnings_for_layer(t: &TextLayer) -> Vec { + fonts_to_warnings(missing_fonts_in_layer(t)) +} + +fn fonts_to_warnings(fonts: Vec) -> Vec { + fonts.into_iter().map(|font| format!("font '{font}' is not installed; text may render using a fallback face")).collect() +} + /// Replace missing families per `map` (missing → installed; unmapped ones → the default family). fn replace_fonts(s: &mut Session, map: &serde_json::Map, all: bool) -> Result { let d = s.active().ok_or(EngineError::NoDocument)?; From 56c5fd5797338cb88a93b9fc5d5c14619af1f077 Mon Sep 17 00:00:00 2001 From: MrCloudy2 <123890706+MrCloudy2@users.noreply.github.com> Date: Mon, 12 Oct 2026 13:48:14 +0200 Subject: [PATCH 17/24] fix(effects): Satin at distance 0 draws as 1 px, as Photoshop does (#3744) Photoshop 27.11 draws Satin Distance 0 as a 1 px offset (an edge band of 2/size), not as two copies that cancel out. PhotoCraft drew nothing. Measured on a #808080 square with a Linear contour at sizes 5, 10 and 20; the other 12 cases already matched within 1 level. Applied to the CPU and GPU paths and to the effect reach. Co-authored-by: Claude Opus 5.5 --- crates/compose/src/effects.rs | 32 ++++++++++++++++++++++++++++++-- crates/gpu/src/fx.rs | 2 +- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rs index 915eb3ddd3..c594e5bd87 100644 --- a/crates/compose/src/effects.rs +++ b/crates/compose/src/effects.rs @@ -43,7 +43,7 @@ pub fn margin(layer: &Layer) -> i32 { Effect::DropShadow(s) | Effect::InnerShadow(s) => s.distance + s.size, Effect::OuterGlow(g) | Effect::InnerGlow(g) => g.size, Effect::Stroke(s) => s.size, - Effect::Satin(s) => s.distance + s.size, + Effect::Satin(s) => satin_distance(s) + s.size, Effect::BevelEmboss(b) => b.size + b.soften, _ => 0.0, }; @@ -1689,8 +1689,14 @@ impl FxMaps { } } +/// The distance the two satin copies are offset by. Photoshop draws Distance 0 as 1 px (an +/// edge band of 2/size, measured in Photoshop 27.11), not as two copies cancelling out. +pub fn satin_distance(s: &photocraft_doc::effects::Satin) -> f32 { + s.distance.max(1.0) +} + fn satin_map(shape: &Map, s: &photocraft_doc::effects::Satin) -> Map { - let (dx, dy) = offset(s.angle, s.distance); + let (dx, dy) = offset(s.angle, satin_distance(s)); let mut a = shape.shifted(dx, dy, 0.0); let mut b = shape.shifted(-dx, -dy, 0.0); // Two box passes of the satin size (fitted: 0.2 % mean error on psd-tools layer_effects). @@ -3008,6 +3014,28 @@ mod tests { m } + #[test] + fn satin_at_distance_zero_matches_photoshop() { + // Photoshop 27.11, Satin black 100 %, angle 90°, Linear contour, distance 0, size 5 over a + // #808080 square: the rows from the top edge read 82, 102, 123, 128. + let s = photocraft_doc::effects::Satin { + common: photocraft_doc::FxCommon::new(BlendMode::Normal, 1.0), + color: photocraft_color::Color::BLACK, + angle: 90.0, + distance: 0.0, + size: 5.0, + contour: Contour::Linear, + anti_alias: false, + invert: false, + }; + let m = satin_map(&square_shape(60), &s); + for (row, gray) in [(5, 82.0), (7, 102.0), (9, 123.0), (11, 128.0), (30, 128.0)] { + let want = 1.0 - gray / 128.0; + let got = m.v[row * 60 + 30]; + assert!((got - want).abs() < 0.02, "row {row}: {got} vs {want}"); + } + } + fn shadow(noise: f32, origin: (i32, i32)) -> Map { let s = Shadow { common: photocraft_doc::FxCommon::new(BlendMode::Multiply, 1.0), diff --git a/crates/gpu/src/fx.rs b/crates/gpu/src/fx.rs index 13cea90af8..10f9272620 100644 --- a/crates/gpu/src/fx.rs +++ b/crates/gpu/src/fx.rs @@ -353,7 +353,7 @@ pub(crate) fn program_with(e: &Effect, light: &GlobalLight, vector_shape: bool, } Effect::Satin(s) => { // satin_map - let (dx, dy) = offset(s.angle, s.distance); + let (dx, dy) = offset(s.angle, photocraft_compose::effects::satin_distance(s)); let a = b.shift(In::Shape, dx, dy, 0.0, false); let a = b.conv(a, photocraft_compose::effects::tent_kernel(s.size)); let c = b.shift(In::Shape, -dx, -dy, 0.0, false); From b071929ecb9dd8c7fe474e1489dac3081205897d Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 12 Oct 2026 13:48:24 +0200 Subject: [PATCH 18/24] Type: editing text keeps its ligatures and OpenType alternates (#3617) (#3747) Photoshop keeps Stylistic Sets, Contextual Alternates, Swash, Fractions, Ordinals, Titling and Stylistic Alternates and Ornaments only in a PSD's Txt2, not in EngineData. Import now reads them into the runs' font features, so the layout drawn while the type is edited keeps Photoshop's glyphs instead of falling back to the default ones. Co-authored-by: Claude Opus 5.5 (1M context) --- crates/text/src/psd.rs | 60 ++++++++++++++++++++++++++++++++++------ crates/text/src/tests.rs | 58 ++++++++++++++++++++++++++++++++++++-- 2 files changed, 107 insertions(+), 11 deletions(-) diff --git a/crates/text/src/psd.rs b/crates/text/src/psd.rs index 2c0ca38af5..b1359f31bb 100644 --- a/crates/text/src/psd.rs +++ b/crates/text/src/psd.rs @@ -140,9 +140,11 @@ pub fn parse_txt2(data: &[u8]) -> Option { ed::parse(&wrapped).ok().filter(|v| matches!(v, E::Dict(_))) } -/// Applies the automatic kerning modes that Photoshop keeps only in `Txt2` (EngineData writes -/// Optical and "0" alike as `AutoKerning true`) to `layer`, read from `tysh`. Only when the -/// layer's `TextIndex` entry still holds the layer's text (an edit elsewhere leaves `Txt2` +/// Applies what Photoshop keeps only in `Txt2` to `layer`, read from `tysh`: the automatic +/// kerning modes (EngineData writes Optical and "0" alike as `AutoKerning true`) and the +/// OpenType settings besides (discretionary) ligatures: stylistic sets, contextual alternates, +/// swashes and the rest ([`TXT2_FEATURES`]), which Photoshop leaves out of EngineData. Only when +/// the layer's `TextIndex` entry still holds the layer's text (an edit elsewhere leaves `Txt2` /// stale). /// /// Observed layout: `Txt2 /1` is the list of text objects; an object's `/0` is its text model @@ -168,11 +170,10 @@ pub fn apply_txt2(layer: &mut TextLayer, tysh: &[u8], txt2: &E) { let Some(style_runs) = model.path(&["6", "0"]).and_then(E::as_array) else { return; }; - let modes: Vec<(f64, Option)> = - style_runs.iter().map(|r| (r.get("1").and_then(E::as_f64).unwrap_or(0.0), r.path(&["0", "0", "6", "11"]).and_then(E::as_i64))).collect(); - let lens = utf16_to_byte_lengths(text, &modes.iter().map(|m| m.0).collect::>()); - // Auto-kern mode per byte segment, then split the model runs at segment boundaries. - let mut segs: Vec<(usize, Option)> = lens.into_iter().zip(modes.iter().map(|m| m.1)).collect(); + let styles: Vec<(f64, Option<&E>)> = style_runs.iter().map(|r| (r.get("1").and_then(E::as_f64).unwrap_or(0.0), r.path(&["0", "0", "6"]))).collect(); + let lens = utf16_to_byte_lengths(text, &styles.iter().map(|m| m.0).collect::>()); + // Txt2 style per byte segment, then split the model runs at segment boundaries. + let mut segs: Vec<(usize, Option<&E>)> = lens.into_iter().zip(styles.iter().map(|m| m.1)).collect(); segs.retain(|s| s.0 > 0); let runs = layer.char_runs(); let mut out: Vec = Vec::new(); @@ -187,14 +188,18 @@ pub fn apply_txt2(layer: &mut TextLayer, tysh: &[u8], txt2: &E) { } let piece_end = if at < seg_end { end.min(seg_end) } else { end }; let mut style = r.style.clone(); + let txt2_style = segs.get(si).and_then(|s| s.1).filter(|_| at < seg_end); // Txt2 has the exact mode (EngineData's reading also marks neighbours of manual // kerns manual, like Photoshop's legacy reader). - match segs.get(si).and_then(|s| s.1).filter(|_| at < seg_end) { + match txt2_style.and_then(|st| st.get("11")).and_then(E::as_i64) { Some(0) => style.kerning = Kerning::Off, Some(1) => style.kerning = Kerning::Metrics, Some(2) => style.kerning = Kerning::Optical, _ => {} } + if let Some(st) = txt2_style { + add_txt2_features(&mut style, st); + } let len = piece_end - at; match out.last_mut() { Some(last) if last.style == style => last.len += len, @@ -207,6 +212,43 @@ pub fn apply_txt2(layer: &mut TextLayer, tysh: &[u8], txt2: &E) { layer.sync_summary(); } +/// OpenType settings of a `Txt2` style that are on/off flags, by style key, as Photoshop +/// writes them (each turned on alone in the Character panel's OpenType settings and read back): +/// `/20` Contextual Alternates, `/23` Fractions, `/24` Ordinals, `/25` Swash, `/26` Titling +/// Alternates, `/28` Stylistic Alternates, `/29` Ornaments. (`/18` and `/19` are the standard and +/// discretionary ligatures, which EngineData carries too; `/27` is Arabic connection forms.) +pub const TXT2_FEATURES: [(&str, &str); 7] = [("20", "calt"), ("23", "frac"), ("24", "ordn"), ("25", "swsh"), ("26", "titl"), ("28", "salt"), ("29", "ornm")]; + +/// The `Txt2` style key holding the Stylistic Sets as a bit mask: bit n is set n + 1 +/// (`ss01`..`ss20`). +pub const TXT2_STYLISTIC_SETS: &str = "85"; + +/// Sets in `style` the OpenType features a `Txt2` style dictionary turns on ([`TXT2_FEATURES`] +/// and the Stylistic Sets mask). A feature the style already sets keeps its value. A flag that is +/// off changes nothing, except Contextual Alternates: shapers apply `calt` by default, Photoshop +/// only when it is on (its default is off), so off is written as `calt` 0. +fn add_txt2_features(style: &mut CharStyle, txt2_style: &E) { + let mut set = |tag: String, value: u16| { + if !style.features.iter().any(|f| f.tag == tag) { + style.features.push(photocraft_doc::text::FontFeature { tag, value }); + } + }; + for (key, tag) in TXT2_FEATURES { + match txt2_style.get(key).and_then(E::as_bool) { + Some(true) => set(tag.to_string(), 1), + Some(false) if tag == "calt" => set(tag.to_string(), 0), + _ => {} + } + } + // A mask beyond the 20 sets is not Photoshop's: ignore it. + let sets = txt2_style.get(TXT2_STYLISTIC_SETS).and_then(E::as_i64).filter(|m| (0..1 << 20).contains(m)).unwrap_or(0); + for n in 0..20 { + if sets & (1 << n) != 0 { + set(format!("ss{:02}", n + 1), 1); + } + } +} + /// Builds a [`TextLayer`] (model, text and transform; no cache, no `psd_raw`) from `TySh` data. pub fn text_layer_from_tysh(data: &[u8], dpi: f32) -> Option { let t = parse_tysh(data)?; diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 75b775b783..b1a1949cac 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -682,6 +682,11 @@ fn warp_bends_rendered_text_and_outlines() { /// `Txt2` as Photoshop writes it (a bare `/key value` sequence; text objects at `/1 /1`, style /// runs at `/0 /6 /0`, auto-kern mode at `/11`), for the layer text `text`. fn txt2_with_modes(text: &str, modes: &[(usize, i64)]) -> Vec { + txt2_with_styles(text, &modes.iter().map(|(len, m)| (*len, format!("/11 {m}"))).collect::>()) +} + +/// [`txt2_with_modes`] with each style run's keys given as EngineData text (`"/11 1 /85 2"`). +fn txt2_with_styles(text: &str, styles: &[(usize, String)]) -> Vec { let mut v = b"\n\n/98 << /0 14 >> /0 << >> /1 << /1 [ << /0 << /0 (\xfe\xff".to_vec(); for u in format!("{text}\r").encode_utf16() { let b = u.to_be_bytes(); @@ -693,8 +698,8 @@ fn txt2_with_modes(text: &str, modes: &[(usize, i64)]) -> Vec { } } v.extend_from_slice(b") /6 << /0 [ "); - for (len, m) in modes { - v.extend_from_slice(format!("<< /0 << /0 << /0 (\u{fe}\u{ff}) /6 << /0 0 /11 {m} >> >> >> /1 {len} >> ").as_bytes()); + for (len, keys) in styles { + v.extend_from_slice(format!("<< /0 << /0 << /0 (\u{fe}\u{ff}) /6 << /0 0 {keys} >> >> >> /1 {len} >> ").as_bytes()); } v.extend_from_slice(b"] >> >> >> ] >>"); v @@ -741,6 +746,55 @@ fn txt2_carries_optical_kerning() { assert!(l.char_runs().iter().all(|r| r.style.kerning == Kerning::Optical)); } +/// #3617: Photoshop keeps Stylistic Sets, Contextual Alternates, Swash and the other OpenType +/// settings besides (discretionary) ligatures only in `Txt2`. Import reads them, so the layout +/// our engine draws when the type is edited keeps Photoshop's glyphs instead of falling back to +/// the default ones. +#[test] +fn txt2_carries_opentype_features() { + let feats = |l: &TextLayer| l.char_runs().iter().map(|r| r.style.features.iter().map(|f| (f.tag.clone(), f.value)).collect::>()).collect::>(); + let f = |tag: &str, value: u16| (tag.to_string(), value); + // "Il->36" plus the engine's closing break: Stylistic Set 2 (mask 2), Contextual Alternates + // and Swash on "Il"; Contextual Alternates off (Photoshop's default), Stylistic Set 1 and + // Fractions on the rest. + let text = "Il->36"; + let plain = styled(text, CharStyle { font_family: "Inter".into(), ..Default::default() }); + let tysh = with_text_index(&crate::psd::build_tysh(&plain, 72.0, None), 0); + let styles = [(2, "/11 1 /18 true /19 false /20 true /25 true /85 2".to_string()), (5, "/11 1 /20 false /23 true /85 1".to_string())]; + let txt2 = crate::psd::parse_txt2(&txt2_with_styles(text, &styles)).unwrap(); + let mut back = crate::psd::text_layer_from_tysh(&tysh, 72.0).unwrap(); + assert_eq!(feats(&back), vec![Vec::<(String, u16)>::new()], "EngineData alone doesn't have them"); + crate::psd::apply_txt2(&mut back, &tysh, &txt2); + assert_eq!(feats(&back), vec![vec![f("calt", 1), f("swsh", 1), f("ss02", 1)], vec![f("calt", 0), f("frac", 1), f("ss01", 1)]]); + assert_eq!(back.char_runs().iter().map(|r| r.len).collect::>(), vec![2, 4]); + // What editing shows (our layout) has Photoshop's glyphs: Inter's `ss02` draws another I and + // l, `ss01` another 3 and 6, and `->` stays two glyphs without `calt` (with it, an arrow). + let mut e = TextEngine::new(); + let ids = |e: &mut TextEngine, t: &TextLayer| e.layout(t, 72.0).glyphs.iter().map(|g| g.id).collect::>(); + let with = |len: usize, tags: &[(&str, u16)]| TextRun { + len, + style: CharStyle { + features: tags.iter().map(|(tag, value)| FontFeature { tag: (*tag).into(), value: *value }).collect(), + ..back.char_runs()[0].style.clone() + }, + }; + let mut expected = back.clone(); + expected.runs = vec![with(2, &[("ss02", 1)]), with(4, &[("calt", 0), ("ss01", 1)])]; + let shown = ids(&mut e, &back); + assert_eq!(shown, ids(&mut e, &expected)); + let defaults = ids(&mut e, &crate::psd::text_layer_from_tysh(&tysh, 72.0).unwrap()); + assert_eq!((shown.len(), defaults.len()), (6, 5), "`->` is two glyphs, as in Photoshop, not an arrow"); + assert!(shown.first() != defaults.first() && shown.last() != defaults.last(), "{shown:?} vs {defaults:?}"); + // A feature the style already sets (from EngineData, read first) keeps its value; masks and + // flags of the wrong type, masks beyond the 20 sets and unknown keys change nothing. + let mut t = crate::psd::text_layer_from_tysh(&tysh, 72.0).unwrap(); + t.runs = vec![TextRun { len: text.len(), style: CharStyle { features: vec![FontFeature { tag: "ss01".into(), value: 0 }], ..Default::default() } }]; + let odd = + [(1, "/85 1".to_string()), (1, "/85 (x) /20 (x) /25 (true)".to_string()), (1, "/85 -1".to_string()), (4, "/85 99999999999 /999 true".to_string())]; + crate::psd::apply_txt2(&mut t, &tysh, &crate::psd::parse_txt2(&txt2_with_styles(text, &odd)).unwrap()); + assert_eq!(feats(&t), vec![vec![f("ss01", 0)]]); +} + /// A `Txt2` written by [`crate::psd::build_txt2`] (what PSD export writes for the type layers) /// restores every auto-kern mode on import (#1348: a new Optical layer used to reopen as /// Metrics, because EngineData's `AutoKerning true` covers both). From 81bff2aaa4267a2da9a4b6c85cdea451339628da Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 12 Oct 2026 13:48:35 +0200 Subject: [PATCH 19/24] Brushes: Photoshop's texture Height/Subtract modes, Brightness and Contrast (#3340) (#3749) Imported brushes whose Texture uses Height or Linear Height at a low depth (common in Photoshop brush packs) painted nothing: the modes were modelled backwards (paint only on the brightest texels, more of it with more depth). Measured against Photoshop with single dabs over a 0..255 ramp pattern: - Height: paint reaches 12 x depth x coverage into the pattern and fills what lies below it (dark valleys first; a brighter pattern takes paint away, which is why the reporter had to flip Brightness's sign). Linear Height grades the shallow end by the pattern instead. - Subtract takes depth x pattern away (white removes the most paint); Color Dodge/Burn scale the pattern toward their neutral with depth. These now live in texture_combine; the Dual Brush keeps mask_combine. - Brightness shifts the pattern by value/255 (not value/150); positive Contrast steepens by 1/(1-c/100) after the shift, negative flattens by 1+c/100 before it. Texture::level is shared by the renderer and the Brush Settings swatch. - ABR import mapped textureContrast with /50 for both signs; positive values are now /100, matching the model and the Brush Settings field. Built-in Subtract presets get Invert so they look as before. Co-authored-by: Claude Opus 5.5 (1M context) --- crates/io/src/abr_map.rs | 4 +- crates/io/src/abr_map/tests.rs | 49 ++++++++++++- crates/paint/src/brush.rs | 17 ++++- crates/paint/src/brush_tests.rs | 104 ++++++++++++++++++++++++++- crates/paint/src/presets.rs | 6 +- crates/paint/src/render.rs | 43 +++++++++-- crates/ui-egui/src/brush_sections.rs | 7 +- 7 files changed, 212 insertions(+), 18 deletions(-) diff --git a/crates/io/src/abr_map.rs b/crates/io/src/abr_map.rs index 225869ea79..6230e27649 100644 --- a/crates/io/src/abr_map.rs +++ b/crates/io/src/abr_map.rs @@ -389,7 +389,9 @@ impl Mapper<'_> { t.invert = boolean(d, "InvT").unwrap_or(false); t.scale = pct(d, "textureScale").unwrap_or(1.0).clamp(0.01, 10.0); t.brightness = (num(d, "textureBrightness").unwrap_or(0.0) / 150.0).clamp(-1.0, 1.0) as f32; - t.contrast = (num(d, "textureContrast").unwrap_or(0.0) / 50.0).clamp(-1.0, 2.0) as f32; + // Photoshop's -50..100 onto the model's -1..1 (negative and positive scale apart). + let c = num(d, "textureContrast").unwrap_or(0.0); + t.contrast = (if c < 0.0 { c / 50.0 } else { c / 100.0 }).clamp(-1.0, 1.0) as f32; t.mode = mask_mode(enum_value(d, "textureBlendMode")).unwrap_or(MaskMode::Multiply); t.depth = pct(d, "textureDepth").unwrap_or(1.0).clamp(0.0, 1.0); let mut dj = self.dynamic(obj(d, "textureDepthDynamics")); diff --git a/crates/io/src/abr_map/tests.rs b/crates/io/src/abr_map/tests.rs index 9837f4ea4f..013f307f81 100644 --- a/crates/io/src/abr_map/tests.rs +++ b/crates/io/src/abr_map/tests.rs @@ -153,7 +153,7 @@ fn v6_settings_map_onto_brush_sections() { assert_eq!((sc.count, sc.scatter.jitter, sc.scatter.control, sc.scatter.fade_steps, sc.count_jitter.jitter), (3, 2.5, Control::Fade, 40, 0.5)); let tx = &b.texture; assert!(tx.enabled && tx.each_tip && tx.invert); - assert_eq!((tx.scale, tx.brightness, tx.contrast, tx.mode, tx.depth), (1.5, -0.5, 0.5, MaskMode::ColorBurn, 0.6)); + assert_eq!((tx.scale, tx.brightness, tx.contrast, tx.mode, tx.depth), (1.5, -0.5, 0.25, MaskMode::ColorBurn, 0.6)); assert_eq!((tx.depth_jitter.jitter, tx.depth_jitter.minimum), (0.3, 0.2)); let Pattern::Tile(pt) = &tx.pattern else { panic!("embedded pattern expected, got {:?}", tx.pattern) }; assert_eq!((pt.width, pt.height, pt.data[3]), (4, 2, 65535)); @@ -330,3 +330,50 @@ fn sampled_tip_paints_the_brush_colour_never_black() { assert!(painted > 0, "the imported tip painted nothing"); assert!(painted < 64 * 64, "the tip covered everything - coverage was treated as solid colour"); } + +/// #3340: Photoshop's texture Contrast runs -50..100; the model maps -50..0 and 0..100 onto +/// -1..0 and 0..1 (as Brush Settings shows it), so +24 must not read back as +48. +#[test] +fn texture_contrast_maps_both_halves() { + for (c, want) in [(24, 0.24), (100, 1.0), (-30, -0.6), (-50, -1.0), (0, 0.0)] { + let preset = Descriptor::new("brushPreset") + .with("Nm ", t("C")) + .with("Brsh", Value::Descriptor(Descriptor::new("computedBrush").with("Dmtr", u(b"#Pxl", 20.0)))) + .with("useTexture", Value::Boolean(true)) + .with("textureContrast", Value::Integer(c)); + let bytes = write_v6(2, &[], &[], &[preset], false).unwrap(); + let imp = read_abr(&bytes, "Test").unwrap(); + let got = imp.presets[0].brush.texture.contrast; + assert!((got - want).abs() < 1e-6, "contrast {c}: {got}"); + } +} + +/// #3340: a Height-mode brush at a low depth with a darkened pattern (how Photoshop's own +/// "Pen" presets in the reported file are set up) imported but painted nothing. +#[test] +fn low_depth_height_texture_brush_paints() { + use photocraft_color::PixelFormat; + use photocraft_paint::StrokePoint; + use photocraft_paint::render::render_stroke; + use photocraft_raster::Surface; + + for mode in ["Hght", "linearHeight"] { + let preset = Descriptor::new("brushPreset") + .with("Nm ", t("Pen")) + .with("Brsh", Value::Descriptor(Descriptor::new("computedBrush").with("Dmtr", u(b"#Pxl", 20.0)).with("Hrdn", prc(100.0)).with("Spcn", prc(5.0)))) + .with("useTexture", Value::Boolean(true)) + .with("textureBlendMode", en("BlnM", mode)) + .with("textureDepth", prc(13.0)) + .with("textureBrightness", Value::Integer(-87)) + .with("textureContrast", Value::Integer(5)) + .with("Txtr", Value::Descriptor(Descriptor::new("Ptrn").with("Nm ", t("Grit")).with("Idnt", t("pat-uuid")))); + let bytes = write_v6(2, &[], &[grit_pattern()], &[preset], false).unwrap(); + let imp = read_abr(&bytes, "Test").unwrap(); + let b = imp.presets[0].brush.clone(); + let mut s = Surface::new(PixelFormat::RGBA32F); + render_stroke(&mut s, &b, &[StrokePoint::new(10.0, 20.0, 1.0), StrokePoint::new(50.0, 20.0, 1.0)], None, false, 1.0); + let covered = (12..48).filter(|&x| s.rgba(x, 20)[3] > 0.5).count(); + // 13 % depth reaches 1.55 pattern ranges: above the whole darkened Grit pattern. + assert_eq!(covered, 36, "{mode}: the stroke painted {covered} of 36 pixels"); + } +} diff --git a/crates/paint/src/brush.rs b/crates/paint/src/brush.rs index 25ebea5ef2..48e7f48d31 100644 --- a/crates/paint/src/brush.rs +++ b/crates/paint/src/brush.rs @@ -270,7 +270,7 @@ pub struct Texture { pub scale: f32, /// -1..1 (Photoshop's -150..150 mapped to ±1). pub brightness: f32, - /// -1..1. + /// -1..1: Photoshop's -50..0 mapped to -1..0 and its 0..100 to 0..1. pub contrast: f32, /// Apply the texture to every dab (enables depth jitter) instead of once to the stroke. pub each_tip: bool, @@ -281,6 +281,21 @@ pub struct Texture { pub depth_jitter: Dynamic, } +impl Texture { + /// A pattern value (0..1) after Brightness, Contrast and Invert: the value the mode combines + /// with the brush. Measured against Photoshop (#3340): Brightness shifts the pattern by + /// `brightness / 255` (±150 moves it 150 levels of 255, not all the way to white or black); + /// positive Contrast steepens it around mid-grey by `1 / (1 − c/100)` after the shift (100 is + /// a threshold), negative Contrast flattens it by `1 + c/100` before the shift; Invert is last. + pub fn level(&self, v: f32) -> f32 { + let b = if self.brightness.is_finite() { self.brightness.clamp(-1.0, 1.0) * (150.0 / 255.0) } else { 0.0 }; + let c = if self.contrast.is_finite() { self.contrast.clamp(-1.0, 1.0) } else { 0.0 }; + let x = if c >= 0.0 { (v + b - 0.5) / (1.0 - c).max(1e-4) + 0.5 } else { (v - 0.5) * (1.0 + c / 2.0) + 0.5 + b }; + let x = if x.is_finite() { x.clamp(0.0, 1.0) } else { 0.5 }; + if self.invert { 1.0 - x } else { x } + } +} + impl Default for Texture { fn default() -> Self { Self { diff --git a/crates/paint/src/brush_tests.rs b/crates/paint/src/brush_tests.rs index a68f84f1f7..664aca9c06 100644 --- a/crates/paint/src/brush_tests.rs +++ b/crates/paint/src/brush_tests.rs @@ -6,7 +6,7 @@ use photocraft_raster::Surface; use crate::brush::*; use crate::dynamics::{Smoother, smooth_points}; -use crate::render::{BrushContext, StrokeRenderer, mask_combine, render_stroke}; +use crate::render::{BrushContext, StrokeRenderer, mask_combine, render_stroke, texture_combine}; use crate::tile::GrayTile; use crate::{Dab, Stroke, StrokePoint, dabs}; @@ -525,7 +525,9 @@ fn texture_modulates_coverage() { b.texture.invert = false; b.texture.brightness = 1.0; let s = paint(&b, &line(20.0, 80.0, 30.0), 100, 60); - assert!(s.rgba(46, 30)[3] > 0.9); + // +150 lifts a black texel by 150 levels of 255, not to white (#3340). + let lifted = s.rgba(46, 30)[3]; + assert!((lifted - 150.0 / 255.0).abs() < 0.02, "{lifted}"); // All modes keep zero coverage at zero and stay in range. for m in [ MaskMode::Multiply, @@ -544,6 +546,12 @@ fn texture_modulates_coverage() { let v = mask_combine(m, 0.7, t, 0.8); assert!((0.0..=1.0).contains(&v), "{m:?}"); } + for t in [0.0, 0.3, 1.0] { + assert_eq!(texture_combine(m, 0.0, t, 1.0), 0.0, "{m:?}"); + let v = texture_combine(m, 0.7, t, 0.8); + assert!((0.0..=1.0).contains(&v), "{m:?}"); + } + assert!((0.0..=1.0).contains(&texture_combine(m, 0.7, f32::NAN, f32::INFINITY)), "{m:?}"); // Full-white texture never reduces multiply-like masks below the brush. assert!(mask_combine(m, 0.6, 1.0, 1.0) >= 0.6 - 1e-5 || matches!(m, MaskMode::Overlay), "{m:?}"); } @@ -555,6 +563,98 @@ fn texture_modulates_coverage() { assert!(d.iter().any(|x| x.depth < 0.6)); } +/// Texture Brightness and Contrast as Photoshop applies them, measured by stroking a 0..255 grey +/// ramp pattern in Multiply mode at 100 % depth (the stroke's opacity is then the pattern value): +/// (setting, ramp value, opacity read back), in levels of 255 (#3340). +#[test] +fn texture_brightness_and_contrast_match_photoshop() { + let level = |brightness: f32, contrast: f32, invert: bool, v: f32| { + // The model's ranges: brightness ±150 → ±1; contrast -50..0 → -1..0, 0..100 → 0..1. + let c = if contrast < 0.0 { contrast / 50.0 } else { contrast / 100.0 }; + let t = Texture { brightness: brightness / 150.0, contrast: c, invert, ..Default::default() }; + t.level(v / 255.0) * 255.0 + }; + for (b, c, inv, v, want) in [ + (87.0, 0.0, false, 8.0, 95.0), + (87.0, 0.0, false, 200.0, 255.0), + (-87.0, 0.0, false, 104.0, 17.0), + (150.0, 0.0, false, 8.0, 158.0), + (0.0, 50.0, false, 104.0, 81.0), + (0.0, 50.0, false, 136.0, 145.0), + (0.0, -50.0, false, 8.0, 67.0), + (0.0, -50.0, false, 248.0, 188.0), + (0.0, 100.0, false, 120.0, 0.0), + (0.0, 100.0, false, 136.0, 255.0), + // Positive contrast after the shift, negative contrast before it. + (40.0, 50.0, false, 104.0, 161.0), + (40.0, 50.0, false, 40.0, 33.0), + (-40.0, -30.0, false, 120.0, 82.0), + (-40.0, -30.0, false, 248.0, 172.0), + // Invert comes last. + (40.0, 0.0, true, 8.0, 207.0), + (0.0, 50.0, true, 72.0, 238.0), + ] { + let got = level(b, c, inv, v); + assert!((got - want).abs() <= 2.0, "brightness {b}, contrast {c}, invert {inv}, ramp {v}: {got} (Photoshop {want})"); + } +} + +/// The Texture modes that differ from the Dual Brush's, against single Photoshop dabs over a +/// 0..255 ramp: (mode, depth, brush coverage, ramp value, opacity read back), in levels of 255. +#[test] +fn texture_modes_match_photoshop() { + use MaskMode::*; + for (m, d, v, t, want) in [ + // Height: a low depth paints the dark valleys only, more depth fills the pattern. + (Height, 0.0, 255.0, 8.0, 0.0), + (Height, 0.01, 255.0, 8.0, 28.0), + (Height, 0.05, 255.0, 8.0, 148.0), + (Height, 0.05, 255.0, 136.0, 20.0), + (Height, 0.13, 255.0, 8.0, 255.0), + (Height, 0.13, 255.0, 152.0, 244.0), + (Height, 0.13, 255.0, 248.0, 148.0), + (Height, 0.13, 186.0, 88.0, 201.0), + (Height, 0.13, 142.0, 104.0, 116.0), + (Height, 0.25, 255.0, 248.0, 255.0), + // Linear Height: graded by the pattern while the reach stays below its top. + (LinearHeight, 0.01, 255.0, 152.0, 15.0), + (LinearHeight, 0.05, 255.0, 8.0, 151.0), + (LinearHeight, 0.05, 255.0, 152.0, 63.0), + (LinearHeight, 0.10, 255.0, 72.0, 240.0), + (LinearHeight, 0.13, 101.0, 120.0, 82.0), + (LinearHeight, 0.13, 142.0, 104.0, 130.0), + // Subtract: the light parts take paint away. + (Subtract, 1.0, 255.0, 8.0, 247.0), + (Subtract, 1.0, 255.0, 248.0, 7.0), + (Subtract, 0.5, 224.0, 72.0, 188.0), + // Color Burn / Color Dodge below full depth. + (ColorBurn, 0.5, 224.0, 72.0, 207.0), + (ColorDodge, 0.5, 99.0, 120.0, 130.0), + // Unchanged modes. + (Multiply, 0.13, 255.0, 8.0, 223.0), + (Darken, 0.5, 255.0, 8.0, 131.0), + ] { + let got = texture_combine(m, v / 255.0, t / 255.0, d) * 255.0; + assert!((got - want).abs() <= 3.0, "{m:?} depth {d}, coverage {v}, ramp {t}: {got} (Photoshop {want})"); + } +} + +/// #3340: an imported Height-mode brush at a low depth with a darkened pattern painted nothing. +#[test] +fn low_depth_height_texture_paints() { + let tile = GrayTile::from_fn(8, 8, |x, y| if (x + y) % 2 == 0 { 0.45 } else { 0.6 }); + for mode in [MaskMode::Height, MaskMode::LinearHeight] { + let b = BrushSettings { + size: 40.0, + texture: Texture { enabled: true, pattern: Pattern::Tile(tile.clone()), mode, depth: 0.13, brightness: -87.0 / 150.0, ..Default::default() }, + ..brush() + }; + let s = paint(&b, &line(20.0, 80.0, 30.0), 100, 60); + let a = s.rgba(50, 30)[3]; + assert!(a > 0.95, "{mode:?}: {a}"); + } +} + #[test] fn dual_brush_intersects() { // Dual tip: small dabs far apart → the stroke survives only where they land. diff --git a/crates/paint/src/presets.rs b/crates/paint/src/presets.rs index 621565188d..cbba537e1c 100644 --- a/crates/paint/src/presets.rs +++ b/crates/paint/src/presets.rs @@ -107,7 +107,9 @@ fn dry_media(base: &BrushSettings) -> Vec { spacing: 0.12, shape_dynamics: ShapeDynamics { enabled: true, size: pressure_min(0.5), angle: Dynamic::controlled(Control::Direction), ..Default::default() }, transfer: transfer(pressure_min(0.3), Dynamic::default()), - texture: Texture { mode: MaskMode::Subtract, ..paper(5, 0.7) }, + // Subtract takes paint away where the pattern is light (#3340); inverting keeps + // these presets as they were designed, with the dark parts taking it away. + texture: Texture { mode: MaskMode::Subtract, invert: true, ..paper(5, 0.7) }, ..base.clone() }, ), @@ -129,6 +131,7 @@ fn dry_media(base: &BrushSettings) -> Vec { pattern: Pattern::Procedural { style: PatternStyle::Canvas, size: 64, seed: 2 }, depth: 0.55, mode: MaskMode::Subtract, + invert: true, ..Default::default() }, ..base.clone() @@ -379,6 +382,7 @@ fn special_effects(base: &BrushSettings) -> Vec { enabled: true, pattern: Pattern::Procedural { style: PatternStyle::Canvas, size: 64, seed: 1 }, mode: MaskMode::Subtract, + invert: true, depth: 0.7, ..Default::default() }, diff --git a/crates/paint/src/render.rs b/crates/paint/src/render.rs index a92b75fbda..94ac63a793 100644 --- a/crates/paint/src/render.rs +++ b/crates/paint/src/render.rs @@ -108,6 +108,40 @@ pub fn mask_combine(mode: MaskMode, v: f32, t: f32, d: f32) -> f32 { r.clamp(0.0, 1.0) } +/// How far a Height-mode dab at full depth and coverage reaches into the pattern, in pattern +/// ranges (measured against Photoshop, #3340). +const HEIGHT_REACH: f32 = 12.0; + +/// Combine brush coverage `v` with a Texture pattern value `t` at `depth` (Brush Settings › +/// Texture). Where it differs from [`mask_combine`] (still used for the Dual Brush) it follows +/// Photoshop as measured with single dabs over a grey ramp (#3340): +/// - Subtract takes `depth × t` away, so a white pattern removes the most paint. +/// - Color Dodge and Color Burn move the pattern toward their neutral colour as depth falls. +/// - Height treats the pattern as a height field the brush presses into: the paint reaches +/// `12 × depth × v` and fills whatever lies below that, so a low depth paints only the dark +/// valleys, from about 17 % the whole pattern is under the paint, and a brighter pattern +/// takes paint away. +/// - Linear Height is Height, but where the reach stays below the top of the pattern the paint +/// fades with the pattern instead of being cut off. +pub fn texture_combine(mode: MaskMode, v: f32, t: f32, d: f32) -> f32 { + if v <= 0.0 { + return 0.0; + } + let r = match mode { + MaskMode::Subtract => v - d * t, + MaskMode::ColorDodge => v / (1.0 - d * t).max(1e-3), + MaskMode::ColorBurn => 1.0 - (1.0 - v) / (1.0 - d + d * t).max(1e-3), + // Photoshop steps the depth in 1/255ths here, which shows at the lowest depths. + MaskMode::Height => HEIGHT_REACH * (d * 255.0).round() / 255.0 * v - t, + MaskMode::LinearHeight => { + let reach = HEIGHT_REACH * (d * 255.0).round() / 255.0 * v; + if reach < 1.0 { reach * (1.0 - t) } else { reach - t } + } + _ => mask_combine(mode, v, t, d), + }; + if r.is_finite() { r.clamp(0.0, 1.0) } else { 0.0 } +} + /// A stroke-ready brush: the settings plus prepared tip mips and texture. #[derive(Clone, Debug)] pub struct BrushContext { @@ -129,11 +163,8 @@ fn prepare_pattern(b: &BrushSettings) -> Option> { _ => return None, }, }; - let (br, ct) = (t.brightness.clamp(-1.0, 1.0), t.contrast.clamp(-1.0, 1.0)); for v in &mut img.data { - let mut x = (*v - 0.5) * (1.0 + ct) + 0.5 + br; - x = x.clamp(0.0, 1.0); - *v = if t.invert { 1.0 - x } else { x }; + *v = t.level(*v); } Some(Arc::new(img)) } @@ -326,7 +357,7 @@ impl BrushContext { val += (hard - val) * 0.7; } if tex_tip { - val = mask_combine(b.texture.mode, val, self.texture_at(x, y), d.depth); + val = texture_combine(b.texture.mode, val, self.texture_at(x, y), d.depth); } if wet { val *= wet_factor(rn); @@ -366,7 +397,7 @@ impl BrushContext { m = mask_combine(b.dual_brush.mode, m, dv, 1.0); } if self.texture.is_some() && !b.texture.each_tip { - m = mask_combine(b.texture.mode, m, self.texture_at(x, y), b.texture.depth.clamp(0.0, 1.0)); + m = texture_combine(b.texture.mode, m, self.texture_at(x, y), b.texture.depth.clamp(0.0, 1.0)); } m } diff --git a/crates/ui-egui/src/brush_sections.rs b/crates/ui-egui/src/brush_sections.rs index 7fae63ffd0..16332e4d08 100644 --- a/crates/ui-egui/src/brush_sections.rs +++ b/crates/ui-egui/src/brush_sections.rs @@ -395,14 +395,9 @@ fn pattern_swatch(ui: &mut egui::Ui, tx: &paint::Texture) { _ => paint::tile::PatternImage { width: 1, height: 1, data: vec![0.5] }, }, }; - let (br, ct) = (tx.brightness.clamp(-1.0, 1.0), tx.contrast.clamp(-1.0, 1.0)); let px: Vec = (0..n * n) .flat_map(|i| { - let v = img.sample_wrap((i % n) as f32, (i / n) as f32); - let mut x = ((v - 0.5) * (1.0 + ct) + 0.5 + br).clamp(0.0, 1.0); - if tx.invert { - x = 1.0 - x; - } + let x = tx.level(img.sample_wrap((i % n) as f32, (i / n) as f32)); let g = (x * 255.0).round() as u8; [g, g, g, 255] }) From e4e3f00f484a0aa345e551f59bf268e1983f1087 Mon Sep 17 00:00:00 2001 From: Dennis <34663561+Madcat71@users.noreply.github.com> Date: Mon, 12 Oct 2026 13:48:45 +0200 Subject: [PATCH 20/24] Camera raw colour fit: read a Sony Adobe RGB preview as Adobe RGB, not sRGB (#3760) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The per-file colour fit (`fit_preview_look`) converted the embedded JPEG to sRGB only when the JPEG carried an ICC profile, and otherwise read it as sRGB. A Sony body set to Adobe RGB writes no profile into its previews; it states the colour space only in the raw's EXIF (ColorSpace Uncalibrated with InteropIndex "R03", the DCF option file for Adobe RGB). The fit then targeted a desaturated, hue-shifted reference, and the developed raw came out that way. `photocraft_raw::embedded_preview_color_space` reads that EXIF (sRGB, Adobe RGB or unstated; never for a DNG, whose previews are the converter's), and `preview_profile` uses it when the preview has no ICC profile of its own. A preview's own profile still wins. LightCraft reads the same tags for the same reason (storytold/lightcraft#778). Measured on 19 private Sony ILCE-1M2 ARWs, all shot in Adobe RGB, against the camera's JPEG read as Adobe RGB (median CIE76 ΔE at 240 px): full-frame 400 mm shots against blue sky 5.6-7.0 → 1.5-2.4, their mean a* offset +4.3…+4.9 → +0.7…+1.1; every file improved, mean of the medians 4.9 → 2.2. Tests: `exif_colour_space_of_the_previews` (sRGB, Adobe RGB; R98, a missing interop IFD, other values, a DNG and junk are unstated) and `a_preview_without_a_profile_takes_the_raws_exif_colour_space` (fails without the EXIF fallback; the preview's own ICC profile wins). The hostile-input harness calls the new function. Co-authored-by: Claude Opus 5.5 --- crates/io/src/raw.rs | 56 ++++++++++++++++++++++++------ crates/raw/src/lib.rs | 2 +- crates/raw/src/preview.rs | 69 +++++++++++++++++++++++++++++++++++++ crates/raw/src/tiff.rs | 4 +++ crates/raw/tests/hostile.rs | 1 + 5 files changed, 120 insertions(+), 12 deletions(-) diff --git a/crates/io/src/raw.rs b/crates/io/src/raw.rs index 6ff2f59042..7e1f916481 100644 --- a/crates/io/src/raw.rs +++ b/crates/io/src/raw.rs @@ -14,7 +14,7 @@ use std::sync::Arc; use photocraft_cms::{Builtin, Intent, Profile, Transform}; use photocraft_codecs::{self as codecs, ChannelLayout, Format, Image, SampleType}; -use photocraft_raw::{CameraLook, DevelopOptions, Limits, RawError, Reference, Sensor, WhiteBalance}; +use photocraft_raw::{CameraLook, DevelopOptions, Limits, PreviewColorSpace, RawError, Reference, Sensor, WhiteBalance}; use crate::flat::image_to_document; use crate::{ImportResult, IoError}; @@ -133,10 +133,23 @@ pub fn import_raw(name: &str, bytes: &[u8]) -> Result { /// the fit grid is at most `PROXY_EDGE` cells and wants about two pixels per cell). const FIT_PREVIEW_EDGE: u32 = 2 * photocraft_raw::PROXY_EDGE as u32; +/// The colour space of a raw's decoded preview when it is not sRGB: its own ICC profile, else the +/// one the raw's EXIF states (a Sony body set to Adobe RGB writes no profile into the JPEG). +/// `None` means sRGB. +fn preview_profile(raw: &[u8], icc: Option<&[u8]>) -> Result>, String> { + let src = match icc { + Some(icc) => Cow::Owned(Profile::parse(icc).map_err(|e| format!("the preview's ICC profile does not parse: {e}"))?), + None if photocraft_raw::embedded_preview_color_space(raw) == Some(PreviewColorSpace::AdobeRgb) => Cow::Borrowed(Builtin::AdobeRgbCompat.profile()), + None => return Ok(None), + }; + Ok((!src.same_colors(Builtin::Srgb.profile())).then_some(src)) +} + /// Fits the colour of a decoded raw to the camera's embedded JPEG (see /// [`photocraft_raw::fit_look`]): picks the smallest preview at least /// `FIT_PREVIEW_EDGE` pixels long (else the largest), decodes it, turns it upright and -/// converts it to sRGB when it carries another ICC profile. `Err` says why there is no fit. +/// converts it to sRGB when it is in another colour space ([`preview_profile`]). `Err` says +/// why there is no fit. pub fn fit_preview_look(raw: &[u8], sensor: &Sensor, opts: &DevelopOptions) -> Result { let previews = photocraft_raw::embedded_previews(raw); let long = |p: &photocraft_raw::Preview| p.width.max(p.height); @@ -152,15 +165,11 @@ pub fn fit_preview_look(raw: &[u8], sensor: &Sensor, opts: &DevelopOptions) -> R } let (w, h) = img.dimensions(); let mut rgb: Cow<[u8]> = Cow::Borrowed(img.data()); - if let Some(icc) = img.icc.as_deref() { - let srgb = Builtin::Srgb.profile(); - let src = Profile::parse(icc).map_err(|e| format!("the preview's ICC profile does not parse: {e}"))?; - if !src.same_colors(srgb) { - let t = Transform::new(&src, srgb, Intent::RelativeColorimetric, false).map_err(|e| e.to_string())?; - let mut out = vec![0u8; rgb.len()]; - t.convert_u8(&rgb, 3, &mut out, 3, false); - rgb = Cow::Owned(out); - } + if let Some(src) = preview_profile(raw, img.icc.as_deref())? { + let t = Transform::new(&src, Builtin::Srgb.profile(), Intent::RelativeColorimetric, false).map_err(|e| e.to_string())?; + let mut out = vec![0u8; rgb.len()]; + t.convert_u8(&rgb, 3, &mut out, 3, false); + rgb = Cow::Owned(out); } photocraft_raw::fit_look(sensor, opts, &Reference { width: w, height: h, rgb: &rgb }).map_err(|e| e.to_string()) } @@ -223,4 +232,29 @@ mod tests { assert_eq!(camera_name(None, Some("X")), "X"); assert_eq!(camera_name(Some("Panasonic"), Some("DC-G9")), "Panasonic DC-G9"); } + + /// A Sony body set to Adobe RGB says so only in the raw's EXIF (ColorSpace Uncalibrated, InteropIndex "R03"): + /// its preview, which has no ICC profile, is read as Adobe RGB for the colour fit, not as sRGB. + #[test] + fn a_preview_without_a_profile_takes_the_raws_exif_colour_space() { + use photocraft_raw::testgen::{TiffBuilder, Val}; + let raw = |color_space: u16, index: &str| { + let mut t = TiffBuilder::default(); + let interop = t.ifd(vec![(0x0001, Val::Ascii(index.into()))]); + let exif = t.ifd(vec![(0xA001, Val::Short(vec![color_space])), (0xA005, Val::Ifds(vec![interop]))]); + t.chain = vec![t.ifd(vec![(271, Val::Ascii("SONY".into())), (34665, Val::Ifds(vec![exif]))])]; + t.build() + }; + let adobe = raw(0xFFFF, "R03"); + let srgb = raw(1, "R98"); + assert!(preview_profile(&adobe, None).unwrap().unwrap().same_colors(Builtin::AdobeRgbCompat.profile())); + assert!(preview_profile(&srgb, None).unwrap().is_none()); + assert!(preview_profile(b"not a raw", None).unwrap().is_none(), "unstated: sRGB"); + // the preview's own profile wins over the raw's EXIF + let srgb_icc = Builtin::Srgb.profile().to_bytes().to_vec(); + assert!(preview_profile(&adobe, Some(srgb_icc.as_slice())).unwrap().is_none()); + let p3_icc = Builtin::DisplayP3.profile().to_bytes().to_vec(); + assert!(preview_profile(&srgb, Some(p3_icc.as_slice())).unwrap().unwrap().same_colors(Builtin::DisplayP3.profile())); + assert!(preview_profile(&adobe, Some(b"not an ICC profile")).is_err()); + } } diff --git a/crates/raw/src/lib.rs b/crates/raw/src/lib.rs index b9f4f1c6ec..9a702f2ddb 100644 --- a/crates/raw/src/lib.rs +++ b/crates/raw/src/lib.rs @@ -74,7 +74,7 @@ pub use crate::develop::{DevelopOptions, Developed, RawInfo, WhiteBalance, devel pub use crate::error::RawError; pub use crate::look::{CameraLook, LookRejected, PROXY_EDGE, Reference, ToneCurve, fit_look}; pub use crate::opcodes::GainMap; -pub use crate::preview::{Preview, embedded_preview, embedded_previews}; +pub use crate::preview::{Preview, PreviewColorSpace, embedded_preview, embedded_preview_color_space, embedded_previews}; pub use crate::sensor::{BlackLevels, Cfa, Rect, Sensor}; use crate::tiff::{Tiff, tag}; diff --git a/crates/raw/src/preview.rs b/crates/raw/src/preview.rs index 4007706035..ec0c041fb5 100644 --- a/crates/raw/src/preview.rs +++ b/crates/raw/src/preview.rs @@ -97,3 +97,72 @@ pub fn embedded_previews(bytes: &[u8]) -> Vec> { }); found } + +/// The colour space a raw file states for its embedded previews, which carry no ICC profile of their own. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PreviewColorSpace { + Srgb, + AdobeRgb, +} + +/// The colour space the raw's EXIF gives for the camera's JPEG rendering, for a preview that declares none itself: +/// ColorSpace (0xA001) 1 = sRGB, or Uncalibrated (0xFFFF) with the Interoperability IFD's InteropIndex "R03", the +/// DCF option file for Adobe RGB (as a Sony body set to Adobe RGB writes; Exif and DCF specifications). `None` when +/// the file doesn't say, and for a DNG, whose EXIF describes the original capture while its previews are the +/// converter's. A preview's own ICC profile takes precedence over this. +pub fn embedded_preview_color_space(bytes: &[u8]) -> Option { + let t = Tiff::new(bytes)?; + let ifd0 = t.ifd_at(t.first_ifd, 0)?; + if ifd0.has(tag::DNG_VERSION) { + return None; + } + let exif = t.ifd_at(t.tag_uint(&ifd0, tag::EXIF_IFD)? as usize, 0)?; + match t.tag_uint(&exif, tag::COLOR_SPACE)? { + 1 => Some(PreviewColorSpace::Srgb), + 0xFFFF => { + let interop = t.ifd_at(t.tag_uint(&exif, tag::INTEROP_IFD)? as usize, 0)?; + t.raw(interop.get(tag::INTEROP_INDEX)?)?.starts_with(b"R03").then_some(PreviewColorSpace::AdobeRgb) + } + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testgen::{TiffBuilder, Val}; + + /// A raw-like TIFF whose EXIF IFD has `color_space` and, when given, an Interoperability IFD with `index`. + fn raw_with(color_space: Option, index: Option<&str>, dng: bool) -> Vec { + let mut t = TiffBuilder::default(); + let mut exif = Vec::new(); + if let Some(cs) = color_space { + exif.push((tag::COLOR_SPACE, Val::Short(vec![cs]))); + } + if let Some(index) = index { + let interop = t.ifd(vec![(tag::INTEROP_INDEX, Val::Ascii(index.into()))]); + exif.push((tag::INTEROP_IFD, Val::Ifds(vec![interop]))); + } + let exif = t.ifd(exif); + let mut ifd0 = vec![(tag::MAKE, Val::Ascii("SONY".into())), (tag::EXIF_IFD, Val::Ifds(vec![exif]))]; + if dng { + ifd0.push((tag::DNG_VERSION, Val::Byte(vec![1, 6, 0, 0]))); + } + t.chain = vec![t.ifd(ifd0)]; + t.build() + } + + #[test] + fn exif_colour_space_of_the_previews() { + assert_eq!(embedded_preview_color_space(&raw_with(Some(1), Some("R98"), false)), Some(PreviewColorSpace::Srgb)); + assert_eq!(embedded_preview_color_space(&raw_with(Some(0xFFFF), Some("R03"), false)), Some(PreviewColorSpace::AdobeRgb)); + for (cs, index) in [(Some(0xFFFF), Some("R98")), (Some(0xFFFF), None), (Some(2), Some("R03")), (None, Some("R03"))] { + assert_eq!(embedded_preview_color_space(&raw_with(cs, index, false)), None, "{cs:?} {index:?}"); + } + // a DNG's previews are the converter's, whatever the capture was + assert_eq!(embedded_preview_color_space(&raw_with(Some(0xFFFF), Some("R03"), true)), None); + for junk in [&b""[..], b"II*\0", b"II*\0\x08\0\0\0\xff\xff", b"not a tiff at all"] { + assert_eq!(embedded_preview_color_space(junk), None); + } + } +} diff --git a/crates/raw/src/tiff.rs b/crates/raw/src/tiff.rs index 17b9b8af76..671ab11fbe 100644 --- a/crates/raw/src/tiff.rs +++ b/crates/raw/src/tiff.rs @@ -36,6 +36,10 @@ pub(crate) mod tag { pub const EXIF_IFD: u16 = 34665; pub const EXIF_CFA_PATTERN: u16 = 41730; pub const MAKER_NOTE: u16 = 37500; + pub const COLOR_SPACE: u16 = 40961; + pub const INTEROP_IFD: u16 = 40965; + /// In the Interoperability IFD. + pub const INTEROP_INDEX: u16 = 1; pub const DNG_VERSION: u16 = 50706; pub const UNIQUE_CAMERA_MODEL: u16 = 50708; pub const CFA_PLANE_COLOR: u16 = 50710; diff --git a/crates/raw/tests/hostile.rs b/crates/raw/tests/hostile.rs index dabe9ffe9e..4b91f2f103 100644 --- a/crates/raw/tests/hostile.rs +++ b/crates/raw/tests/hostile.rs @@ -88,6 +88,7 @@ fn exercise(b: &[u8]) { let _ = identify(b); let _ = embedded_preview(b); let _ = embedded_previews(b); + let _ = embedded_preview_color_space(b); let opts = DevelopOptions { limits: Limits { max_alloc: 64 << 20, ..Limits::default() }, ..Default::default() }; if let Ok(s) = decode(b, &opts.limits) { for m in [Demosaic::Bilinear, Demosaic::Ahd] { From e35671ffa9d99b107aa471f75c875619c6e54fba Mon Sep 17 00:00:00 2001 From: Unemars <62496697+Unemars@users.noreply.github.com> Date: Mon, 12 Oct 2026 13:48:55 +0200 Subject: [PATCH 21/24] Shadows/Highlights: Photoshop's, measured (#3765) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Image › Adjustments › Shadows/Highlights follows Photoshop 25.4, measured as a black box: per-channel screen curves (1 - (1 - v)^q blended over q = 1, 2, 4, 8), the Tone mask as a Beta distribution function of an 8-bit neighbourhood brightness, an edge-aware (guided bilateral) neighbourhood, the luma of the result with the colour differences scaled by Color, and the Midtone S-curve. Co-authored-by: Claude Opus 5.5 (1M context) --- crates/algo/src/tone.rs | 131 +------ crates/algo/src/tone/shadows_highlights.rs | 423 +++++++++++++++++++++ 2 files changed, 427 insertions(+), 127 deletions(-) create mode 100644 crates/algo/src/tone/shadows_highlights.rs diff --git a/crates/algo/src/tone.rs b/crates/algo/src/tone.rs index 2050d8138d..8592b3dda2 100644 --- a/crates/algo/src/tone.rs +++ b/crates/algo/src/tone.rs @@ -4,7 +4,8 @@ //! All work on straight (non-premultiplied) RGBA buffers in 0..=1, row-major `w × h`, so callers //! convert any colour model / bit depth to RGBA first (as `Image › Adjustments` does for the //! per-pixel adjustments). Formulas are documented approximations of Photoshop's behaviour, -//! derived from its manual and observation, not from its implementation. +//! derived from its manual and observation, not from its implementation; Shadows/Highlights is +//! measured on Photoshop (see [`shadows_highlights`]). use photocraft_color::convert::{lab_to_srgb, srgb_to_lab}; use serde::{Deserialize, Serialize}; @@ -17,18 +18,6 @@ fn luma(c: [f32; 3]) -> f32 { 0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2] } -fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 { - let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0); - t * t * (3.0 - 2.0 * t) -} - -/// Blurred luminance (Gaussian, `radius` px ≈ 2σ like Photoshop's radius fields). -fn blurred_luma(px: &[[f32; 4]], w: usize, h: usize, radius: f32) -> Vec { - let mut l: Vec = px.iter().map(|p| luma([p[0], p[1], p[2]])).collect(); - gauss_blur_n(&mut l, w, h, 1, radius.max(0.0) / 2.0); - l -} - /// Image › Adjustments › Shadows/Highlights parameters (Photoshop's dialog, percentages as 0..=100). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ShadowsHighlights { @@ -64,95 +53,8 @@ impl Default for ShadowsHighlights { } } -/// Local tone mapping: a blurred-luminance mask selects shadows (dark neighbourhoods, up to the -/// tonal width) and highlights; shadows are lifted and highlights pulled down by a gain that -/// preserves hue, then saturation is corrected where the gain moved tones, midtone contrast is -/// applied, and the result is stretched by the clip percentages. -pub fn shadows_highlights(px: &mut [[f32; 4]], w: usize, h: usize, p: &ShadowsHighlights) { - if px.is_empty() { - return; - } - let ls = blurred_luma(px, w, h, p.shadow_radius); - let lh = if (p.highlight_radius - p.shadow_radius).abs() < 1e-3 { ls.clone() } else { blurred_luma(px, w, h, p.highlight_radius) }; - let (sa, ha) = (p.shadow_amount / 100.0, p.highlight_amount / 100.0); - let (st, ht) = ((p.shadow_tone / 100.0).max(0.01), (p.highlight_tone / 100.0).max(0.01)); - let color = p.color / 100.0; - let mid = p.midtone / 100.0; - par_rows(px, w, 1, |y, pxrow| { - for (x, q) in pxrow.iter_mut().enumerate() { - let i = y * w + x; - if q[3] <= 0.0 { - continue; - } - let c = [q[0], q[1], q[2]]; - // Mask weights: 1 in deep shadows (resp. bright highlights), fading out at the tonal width. - let ms = 1.0 - smoothstep(0.0, st, ls[i]); - let mh = smoothstep(1.0 - ht, 1.0, lh[i]); - let mut out = c; - if sa > 0.0 && ms > 0.0 { - // Lift: a gamma-like curve on the pixel, stronger for darker neighbourhoods. - let g = 1.0 / (1.0 + 2.0 * sa * ms); - out = out.map(|v| v.max(0.0).powf(g)); - } - if ha > 0.0 && mh > 0.0 { - let g = 1.0 / (1.0 + 2.0 * ha * mh); - out = out.map(|v| 1.0 - (1.0 - v.min(1.0)).powf(g)); - } - if mid != 0.0 { - let k = 1.0 + mid * (1.0 - ms - mh).clamp(0.0, 1.0); - out = out.map(|v| (v - 0.5) * k + 0.5); - } - let changed = (ms * sa + mh * ha).min(1.0); - if color != 0.0 && changed > 0.0 { - let l1 = luma(out); - let s = 1.0 + color * changed; - out = out.map(|v| l1 + (v - l1) * s); - } - q[0] = out[0].clamp(0.0, 1.0); - q[1] = out[1].clamp(0.0, 1.0); - q[2] = out[2].clamp(0.0, 1.0); - } - }); - clip_stretch(px, p.black_clip, p.white_clip); -} - -/// Stretches levels so `black`% of pixels clip to 0 and `white`% to 1 (luminance histogram). -fn clip_stretch(px: &mut [[f32; 4]], black: f32, white: f32) { - if black <= 0.0 && white <= 0.0 { - return; - } - let mut hist = [0u32; 1024]; - let mut n = 0u32; - for q in px.iter().filter(|q| q[3] > 0.0) { - hist[((luma([q[0], q[1], q[2]]).clamp(0.0, 1.0)) * 1023.0).round() as usize] += 1; - n += 1; - } - if n == 0 { - return; - } - let find = |pct: f32, rev: bool| -> f32 { - let target = (pct.clamp(0.0, 50.0) / 100.0 * n as f32) as u32; - let mut acc = 0; - for k in 0..1024 { - let i = if rev { 1023 - k } else { k }; - acc += hist[i]; - if acc > target { - return i as f32 / 1023.0; - } - } - if rev { 0.0 } else { 1.0 } - }; - let lo = find(black, false); - let hi = find(white, true); - if hi - lo < 1e-3 { - return; - } - for q in px.iter_mut().filter(|q| q[3] > 0.0) { - for v in &mut q[..3] { - *v = ((*v - lo) / (hi - lo)).clamp(0.0, 1.0); - } - } -} +mod shadows_highlights; +pub use shadows_highlights::shadows_highlights; /// Image › Adjustments › Replace Color: Color Range-style selection (fuzziness in 0..=200 levels) /// around `color`, then a hue (±180°), saturation and lightness (±100) shift weighted by it. @@ -378,31 +280,6 @@ mod tests { .collect() } - #[test] - fn shadows_lift_dark_pixels_more_than_bright() { - let mut px = ramp(32, 8); - let orig = px.clone(); - shadows_highlights(&mut px, 32, 8, &ShadowsHighlights { black_clip: 0.0, white_clip: 0.0, ..Default::default() }); - let gain = |i: usize| luma([px[i][0], px[i][1], px[i][2]]) - luma([orig[i][0], orig[i][1], orig[i][2]]); - assert!(gain(3) > 0.02, "{}", gain(3)); - assert!(gain(3) > gain(30), "{} {}", gain(3), gain(30)); - // Zero amounts and no clipping: identity. - let mut px2 = orig.clone(); - let id = ShadowsHighlights { shadow_amount: 0.0, highlight_amount: 0.0, color: 0.0, black_clip: 0.0, white_clip: 0.0, ..Default::default() }; - shadows_highlights(&mut px2, 32, 8, &id); - assert_eq!(px2, orig); - } - - #[test] - fn highlights_darken_bright_pixels() { - let mut px = ramp(32, 8); - let orig = px.clone(); - let p = ShadowsHighlights { shadow_amount: 0.0, highlight_amount: 80.0, black_clip: 0.0, white_clip: 0.0, ..Default::default() }; - shadows_highlights(&mut px, 32, 8, &p); - assert!(px[30][0] < orig[30][0]); - assert!((px[1][0] - orig[1][0]).abs() < 1e-6); - } - #[test] fn replace_color_only_touches_matching_pixels() { let mut px = vec![[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0]]; diff --git a/crates/algo/src/tone/shadows_highlights.rs b/crates/algo/src/tone/shadows_highlights.rs new file mode 100644 index 0000000000..0b5feaee2d --- /dev/null +++ b/crates/algo/src/tone/shadows_highlights.rs @@ -0,0 +1,423 @@ +//! Image › Adjustments › Shadows/Highlights, as Photoshop 25.4 does it. +//! +//! Measured on Photoshop as a black box (synthetic 16-bit images through the adjustment, results +//! read back exactly); no Photoshop code was read. The pieces: +//! +//! - **Neighbourhood brightness.** Per pixel, the mean of its brightest channel and its Rec. 601 +//! luma. Its neighbourhood value is an edge-aware average: a Gaussian of σ = 1.14 · Radius whose +//! weights fall linearly with the difference from the pixel's own (lightly blurred) brightness, +//! so pixels across a strong edge count less and halos stay small. It is quantised to 8 bits. +//! - **Tonal mask.** Tone sets which neighbourhoods are treated: shadows take the complement of a +//! Beta distribution function of the neighbourhood brightness, from Beta(1.95, 23) at Tone 0 to +//! 1 − L at Tone 95 and over; highlights take the same of 1 − L. +//! - **Curve.** Amount sets a curve that screens the image with itself: 1 − (1 − v)^q, blended +//! between q = 1, 2, 4 and 8 by a strength s = 3 at 100, 2 at 50 and 1 near 15. Shadows lift each +//! channel by mask × (curve − v); highlights darken with the mirrored curve. +//! - **Colour.** Only the luma of that result is kept: the pixel's own colour differences are +//! added back, scaled by the Color slider (by exp(h · ΔY / max Y) for positive values, by +//! 1 + h · ΔY / max Y for negative ones) and shortened where they would leave the gamut. +//! - **Midtone** is a global S-curve on the luma, k · (Y − ½) · (4Y(1 − Y))^p. + +use crate::fxutil::gauss_blur_n; +use crate::photo_util::par_rows; + +use super::ShadowsHighlights; + +const W: [f32; 3] = [0.299, 0.587, 0.114]; + +fn luma(c: [f32; 3]) -> f32 { + W[0] * c[0] + W[1] * c[1] + W[2] * c[2] +} + +/// Neighbourhood σ per pixel of Radius. +const SPATIAL: f32 = 1.1424; +/// σ of the blur of the pixel's own brightness the edge weights compare with. +const GUIDE: f32 = 1.3559; +/// Brightness difference at which a neighbour's weight reaches zero. +const RANGE: f32 = 1.0152; +/// Brightness levels of the piecewise-linear edge-aware average. +const LEVELS: usize = 17; + +/// Edge-aware neighbourhood brightness of `lum` (`w × h`) for Photoshop's Radius. +fn neighbourhood(lum: &[f32], w: usize, h: usize, radius: f32) -> Vec { + let mut guide = lum.to_vec(); + gauss_blur_n(&mut guide, w, h, 1, GUIDE); + let sigma = SPATIAL * radius; + if sigma < 0.3 { + return guide; + } + // The average at each of a few brightness levels, interpolated at the pixel's own level + // (Durand and Dorsey, "Fast bilateral filtering", 2002). The averages are smooth, so they are + // taken on a grid `d` times coarser, with σ ≥ 4 cells there. + let d = ((sigma / 4.0).floor() as usize).max(1); + let (rw, rh) = (w.div_ceil(d), h.div_ceil(d)); + let cells = rw * rh; + let step = 1.0 / (LEVELS - 1) as f32; + let mut avg = vec![0.0f32; LEVELS * cells]; + let mut buf = vec![0.0f32; 2 * cells]; + for (k, out) in avg.chunks_exact_mut(cells).enumerate() { + let g = k as f32 * step; + buf.fill(0.0); + for (i, &l) in lum.iter().enumerate() { + let wgt = (1.0 - (l - g).abs() / RANGE).max(0.0); + let c = 2 * ((i / w) / d * rw + (i % w) / d); + buf[c] += wgt * l; + buf[c + 1] += wgt; + } + gauss_blur_n(&mut buf, rw, rh, 2, sigma / d as f32); + for (o, b) in out.iter_mut().zip(buf.as_chunks::<2>().0) { + *o = if b[1] > 1e-6 { b[0] / b[1] } else { g }; + } + } + let mut out = vec![0.0f32; lum.len()]; + par_rows(&mut out, w, 1, |y, row| { + let fy = ((y as f32 + 0.5) / d as f32 - 0.5).clamp(0.0, (rh - 1) as f32); + let (y0, ty) = (fy.floor() as usize, fy.fract()); + let y1 = (y0 + 1).min(rh - 1); + for (x, o) in row.iter_mut().enumerate() { + let fx = ((x as f32 + 0.5) / d as f32 - 0.5).clamp(0.0, (rw - 1) as f32); + let (x0, tx) = (fx.floor() as usize, fx.fract()); + let x1 = (x0 + 1).min(rw - 1); + let at = |k: usize| { + let a = &avg[k * cells..(k + 1) * cells]; + let top = a[y0 * rw + x0] + (a[y0 * rw + x1] - a[y0 * rw + x0]) * tx; + let bot = a[y1 * rw + x0] + (a[y1 * rw + x1] - a[y1 * rw + x0]) * tx; + top + (bot - top) * ty + }; + let t = (guide[y * w + x].clamp(0.0, 1.0) / step).min((LEVELS - 1) as f32 - 1e-4); + let k = t.floor() as usize; + let f = t - k as f32; + *o = at(k) * (1.0 - f) + at(k + 1) * f; + } + }); + out +} + +/// Beta(α, β) parameters of the tonal mask for Tone 0, 5, …, 95 (fitted to Photoshop's masks +/// within 2/255). +const MASK_BETA: [(f32, f32); 20] = [ + (1.9468, 22.9366), + (1.7770, 18.3471), + (1.6403, 14.7559), + (1.5270, 11.9346), + (1.4269, 9.6467), + (1.3470, 7.8430), + (1.2807, 6.4038), + (1.2240, 5.2384), + (1.1772, 4.2967), + (1.1373, 3.5350), + (1.1021, 2.9109), + (1.0755, 2.4186), + (1.0508, 2.0189), + (1.0307, 1.7034), + (1.0140, 1.4583), + (1.0015, 1.2758), + (1.0, 1.1403), + (1.0, 1.0510), + (1.0, 1.0002), + (1.0, 1.0), +]; + +/// The tonal mask for `tone` (0..=100) at the 256 neighbourhood levels: 1 − I_L(α, β). +fn tonal_mask(tone: f32) -> [f32; 256] { + let t = (tone.clamp(0.0, 95.0)) / 5.0; + let i = (t.floor() as usize).min(MASK_BETA.len() - 2); + let f = t - i as f32; + let (a0, b0) = MASK_BETA[i]; + let (a1, b1) = MASK_BETA[i + 1]; + let (a, b) = ((a0 + (a1 - a0) * f) as f64, (b0 + (b1 - b0) * f) as f64); + // Midpoint sums of the Beta density, 16 per level. + const SUB: usize = 16; + let n = 255 * SUB; + let dens = |x: f64| ((a - 1.0) * x.ln() + (b - 1.0) * (1.0 - x).ln()).exp(); + let mut cum = vec![0.0f64; 256]; + let mut acc = 0.0; + for j in 0..n { + acc += dens((j as f64 + 0.5) / n as f64); + if (j + 1) % SUB == 0 { + cum[(j + 1) / SUB] = acc; + } + } + let total = acc.max(f64::MIN_POSITIVE); + std::array::from_fn(|k| (1.0 - cum[k] / total) as f32) +} + +/// Curve strength for Amount `a` (0..=100): 0 at 0, 1 near 15, 2 at 50, 3 at 100. +fn strength(a: f32) -> f32 { + let u = (a.clamp(0.0, 100.0) / 100.0).powf(0.6216); + if u <= 0.3 { u / 0.3 } else { (1.0 + 20.0 * u) / 7.0 } +} + +/// The full-strength curve of strength `s`: 1 − (1 − v)^q between q = 2^⌊s⌋ and 2^(⌊s⌋+1). +fn lift(s: f32, v: f32) -> f32 { + let n = (s.floor() as i32).clamp(0, 2); + let t = (s - n as f32).clamp(0.0, 1.0); + let c = (1.0 - v).clamp(0.0, 1.0); + let lo = c.powi(1 << n); + let hi = lo * lo; + 1.0 - ((1.0 - t) * lo + t * hi) +} + +/// Linear interpolation in a table of `(x, y)` sorted by `x`. +fn interp(table: &[(f32, f32)], x: f32) -> f32 { + let Some(&(x0, y0)) = table.first() else { return 0.0 }; + if x <= x0 { + return y0; + } + for p in table.windows(2) { + let ((xa, ya), (xb, yb)) = (p[0], p[1]); + if x <= xb { + return ya + (yb - ya) * (x - xa) / (xb - xa); + } + } + table.last().map_or(0.0, |p| p.1) +} + +/// Color: the h of the colour-difference gain for positive values (exp(h · F))… +const COLOR_UP: [(f32, f32); 12] = [ + (0.0, 0.0), + (1.0, 0.1566), + (2.0, 0.2271), + (5.0, 0.3776), + (10.0, 0.5653), + (20.0, 0.8669), + (30.0, 1.1299), + (40.0, 1.3748), + (50.0, 1.6093), + (60.0, 1.8375), + (75.0, 2.1721), + (100.0, 2.7193), +]; +/// … and for negative values (1 + h · F), by −Color. +const COLOR_DOWN: [(f32, f32); 9] = + [(0.0, 0.0), (1.0, -0.0145), (5.0, -0.0709), (10.0, -0.1373), (20.0, -0.2570), (30.0, -0.3612), (50.0, -0.5312), (75.0, -0.6866), (100.0, -0.7968)]; + +/// Midtone: (value, k, p) of k · (Y − ½) · (4Y(1 − Y))^p. +const MIDTONE: [(f32, f32, f32); 11] = [ + (-100.0, -0.6955, 2.267), + (-75.0, -0.5873, 2.362), + (-50.0, -0.4429, 2.492), + (-25.0, -0.2514, 2.667), + (-10.0, -0.1088, 2.803), + (0.0, 0.0, 2.9), + (10.0, 0.1206, 3.016), + (25.0, 0.3262, 3.216), + (50.0, 0.7423, 3.625), + (75.0, 1.2635, 4.160), + (100.0, 1.9032, 4.850), +]; + +fn midtone(m: f32, y: f32) -> f32 { + if m == 0.0 { + return y; + } + let ks: Vec<(f32, f32)> = MIDTONE.iter().map(|r| (r.0, r.1)).collect(); + let ps: Vec<(f32, f32)> = MIDTONE.iter().map(|r| (r.0, r.2)).collect(); + let (k, p) = (interp(&ks, m), interp(&ps, m)); + (y + k * (y - 0.5) * (4.0 * y * (1.0 - y)).max(0.0).powf(p)).clamp(0.0, 1.0) +} + +fn level(v: f32) -> usize { + (v.clamp(0.0, 1.0) * 255.0).round() as usize +} + +/// Image › Adjustments › Shadows/Highlights on straight RGBA `w × h`. +pub fn shadows_highlights(px: &mut [[f32; 4]], w: usize, h: usize, p: &ShadowsHighlights) { + if px.is_empty() || px.len() != w * h { + return; + } + let (sa, ha) = (p.shadow_amount, p.highlight_amount); + let lum: Vec = px.iter().map(|q| (q[0].max(q[1]).max(q[2]) + luma([q[0], q[1], q[2]])) / 2.0).collect(); + let ls = (sa > 0.0).then(|| neighbourhood(&lum, w, h, p.shadow_radius)); + let lh = (ha > 0.0).then(|| match &ls { + Some(l) if (p.highlight_radius - p.shadow_radius).abs() < 1e-3 => l.clone(), + _ => neighbourhood(&lum, w, h, p.highlight_radius), + }); + let (ms, mh) = (tonal_mask(p.shadow_tone), tonal_mask(p.highlight_tone)); + let (ss, hs) = (strength(sa), strength(ha)); + // The new luma of every pixel. + let mut y2 = vec![0.0f32; px.len()]; + par_rows(&mut y2, w, 1, |y, row| { + for (x, out) in row.iter_mut().enumerate() { + let i = y * w + x; + let q = px[i]; + let mut adj = [q[0], q[1], q[2]]; + if let Some(l) = &ls { + let m = ms[level(l[i])]; + for v in &mut adj { + *v += m * (lift(ss, *v) - *v); + } + } + if let Some(l) = &lh { + let m = mh[255 - level(l[i])]; + for (v, &o) in adj.iter_mut().zip(&q[..3]) { + *v -= m * (lift(hs, 1.0 - o) - (1.0 - o)); + } + } + *out = midtone(p.midtone, luma(adj).clamp(0.0, 1.0)); + } + }); + clip_levels(&mut y2, px, p.black_clip, p.white_clip); + let gain = |f: f32| { + if p.color >= 0.0 { (interp(&COLOR_UP, p.color) * f).exp() } else { 1.0 + interp(&COLOR_DOWN, -p.color) * f } + }; + par_rows(px, w, 1, |y, row| { + for (x, q) in row.iter_mut().enumerate() { + if q[3] <= 0.0 { + continue; + } + let y1 = luma([q[0], q[1], q[2]]); + let yn = y2[y * w + x]; + let f = (yn - y1).abs() / yn.max(y1).max(1e-6); + let g = gain(f); + let d = [(q[0] - y1) * g, (q[1] - y1) * g, (q[2] - y1) * g]; + // Shorten the colour difference where it would leave 0..=1. + let mut k = 1.0f32; + for v in d { + if v > 1e-9 { + k = k.min((1.0 - yn) / v); + } else if v < -1e-9 { + k = k.min(yn / -v); + } + } + let k = k.clamp(0.0, 1.0); + for c in 0..3 { + q[c] = (yn + k * d[c]).clamp(0.0, 1.0); + } + } + }); +} + +/// Black and White Clip: stretches the new luma so `black`% of pixels reach 0 and `white`% reach 1. +fn clip_levels(y2: &mut [f32], px: &[[f32; 4]], black: f32, white: f32) { + if black <= 0.0 && white <= 0.0 { + return; + } + let mut hist = vec![0u32; 4096]; + let mut n = 0u32; + for (&y, q) in y2.iter().zip(px) { + if q[3] > 0.0 { + hist[(y.clamp(0.0, 1.0) * 4095.0).round() as usize] += 1; + n += 1; + } + } + if n == 0 { + return; + } + let find = |pct: f32, rev: bool| -> f32 { + let target = (pct.clamp(0.0, 50.0) / 100.0 * n as f32) as u32; + let mut acc = 0; + for k in 0..4096 { + let i = if rev { 4095 - k } else { k }; + acc += hist[i]; + if acc > target { + return i as f32 / 4095.0; + } + } + if rev { 0.0 } else { 1.0 } + }; + let (lo, hi) = (if black > 0.0 { find(black, false) } else { 0.0 }, if white > 0.0 { find(white, true) } else { 1.0 }); + if hi - lo < 1e-3 { + return; + } + for y in y2.iter_mut() { + *y = ((*y - lo) / (hi - lo)).clamp(0.0, 1.0); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A flat `w × h` grey or colour image with one different pixel in the middle; returns that + /// pixel after Shadows/Highlights. + fn probe(bg: [f32; 3], px: [f32; 3], p: &ShadowsHighlights) -> [f32; 3] { + let (w, h) = (121, 121); + let mut img = vec![[bg[0], bg[1], bg[2], 1.0]; w * h]; + img[60 * w + 60] = [px[0], px[1], px[2], 1.0]; + shadows_highlights(&mut img, w, h, p); + let q = img[60 * w + 60]; + [q[0], q[1], q[2]] + } + + fn levels(v: [i32; 3]) -> [f32; 3] { + v.map(|c| c as f32 / 32768.0) + } + + fn off(a: [f32; 3], b: [f32; 3]) -> f32 { + a.iter().zip(b).map(|(x, y)| (x - y).abs() * 255.0).fold(0.0, f32::max) + } + + /// Photoshop 25.4's results (16-bit levels of 32768) for grey pixels lifted by the default + /// Shadows (35 %, Tone 50 %, Radius 30 px; Color 0), in black surroundings and in grey 0.5. + #[test] + fn grey_matches_photoshop() { + let p = ShadowsHighlights { color: 0.0, black_clip: 0.0, white_clip: 0.0, ..Default::default() }; + for (bg, want) in [(0.0, [11389, 19422, 28451, 31931]), (0.5, [5211, 9909, 18229, 25700])] { + for (v, w) in [0.125f32, 0.25, 0.5, 0.749969].into_iter().zip(want) { + let got = probe([bg; 3], [v; 3], &p); + assert!(off(got, levels([w; 3])) < 2.0, "bg {bg} v {v}: {} vs {}", got[0] * 32768.0, w); + } + } + } + + /// Colour pixels keep their colour differences, scaled by Color (+20 here; Amount 35 %, + /// Radius 10 px), in black, 0.15 and 0.3 grey surroundings: Photoshop's results. + #[test] + fn colour_matches_photoshop() { + let p = ShadowsHighlights { shadow_radius: 10.0, black_clip: 0.0, white_clip: 0.0, ..Default::default() }; + for (bg, px, want) in [ + (0.0, [3277, 1638, 0], [8235, 5202, 2170]), + (0.0, [8192, 6554, 4915], [19350, 16514, 13676]), + (4915.0 / 32768.0, [4915, 3277, 1638], [10124, 7424, 4723]), + (9830.0 / 32768.0, [11469, 9830, 8192], [16540, 14376, 12214]), + ] { + let got = probe([bg; 3], levels(px), &p); + assert!(off(got, levels(want)) < 2.0, "{px:?} on {bg}: {:?} vs {want:?}", got.map(|c| (c * 32768.0).round())); + } + } + + /// Across a strong edge the neighbourhood barely leaks (Amount 100 %, Tone 100 %, Radius + /// 10 px; 0.1 | 0.9): Photoshop's results 8, 2 and 1 pixels either side. + #[test] + fn edge_matches_photoshop() { + let (w, h) = (200, 24); + let (a, b) = (3277.0 / 32768.0, 29491.0 / 32768.0); + let mut img: Vec<[f32; 4]> = (0..w * h).map(|i| if i % w < 100 { [a, a, a, 1.0] } else { [b, b, b, 1.0] }).collect(); + let p = ShadowsHighlights { + shadow_amount: 100.0, + shadow_tone: 100.0, + shadow_radius: 10.0, + color: 0.0, + black_clip: 0.0, + white_clip: 0.0, + ..Default::default() + }; + shadows_highlights(&mut img, w, h, &p); + let row = &img[12 * w..13 * w]; + for (x, want) in [(92, 16370), (98, 14439), (99, 12146), (100, 30891), (101, 30403), (102, 30146), (108, 29979)] { + let got = row[x][0] * 32768.0; + assert!((got - want as f32).abs() / 32768.0 * 255.0 < 6.0, "x {x}: {got} vs {want}"); + } + } + + #[test] + fn strength_and_curve_follow_photoshop() { + assert!((strength(50.0) - 2.0).abs() < 2e-3 && (strength(100.0) - 3.0).abs() < 1e-4); + assert!((strength(15.0) - 1.02).abs() < 0.01 && (strength(1.0) - 0.19).abs() < 0.01); + // Amount 50 is the image screened with itself twice: 1 − (1 − v)^4. + for v in [0.1f32, 0.3, 0.6] { + assert!((lift(2.0, v) - (1.0 - (1.0 - v).powi(4))).abs() < 1e-6); + } + } + + #[test] + fn tonal_mask_spans_photoshop_tones() { + let m95 = tonal_mask(95.0); + assert!((m95[128] - (1.0 - 128.0 / 255.0)).abs() < 1e-3, "{}", m95[128]); + assert_eq!(tonal_mask(100.0), m95); + // Tone 0 still reaches about 7 % into the levels (Photoshop: half at level 18). + let m0 = tonal_mask(0.0); + assert!(m0[0] > 0.999 && (m0[18] - 0.5).abs() < 0.03 && m0[60] < 0.02, "{} {}", m0[18], m0[60]); + } +} From 836fd52089f5de988accba94e929f288a7313438 Mon Sep 17 00:00:00 2001 From: MrCloudy2 <123890706+MrCloudy2@users.noreply.github.com> Date: Mon, 12 Oct 2026 13:49:05 +0200 Subject: [PATCH 22/24] fix(adjust): Black & White tints like the Color blend mode, as Photoshop does (#3780) Photoshop's Black & White tint keeps the grey's luminosity and takes the tint's hue and saturation (SetLum + ClipColor, luma 0.30/0.59/0.11), the same as the Color blend mode. PhotoCraft mixed half the grey with twice the grey times the tint, up to 141 levels off. Measured in Photoshop 27.11 on 9 cases (4 tint colours over a grey ramp and hue sweeps): all within 3 levels now. Corpus: photoshop adjustments/rgb8 and rgb16 black-white-tint go from 69 levels max / 77 % bad pixels to 1-3 / <=0.5 %. CPU and GPU paths. Co-authored-by: Claude Opus 5.5 --- crates/compose/src/adjust.rs | 29 ++++++++++++++++++++++++++++- crates/gpu/src/compose.wgsl | 2 +- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/crates/compose/src/adjust.rs b/crates/compose/src/adjust.rs index 357d8ac0d8..f4e6bede26 100644 --- a/crates/compose/src/adjust.rs +++ b/crates/compose/src/adjust.rs @@ -188,7 +188,9 @@ pub fn apply_depth(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer, depth Adjustment::BlackWhite { weights, tint } => map_rgb(buf, |c| { let g = black_white_gray(c, weights); match tint { - Some(t) => std::array::from_fn(|i| (g * t[i] * 2.0).clamp(0.0, 1.0) * 0.5 + g * 0.5), + // Photoshop tints like the Color blend mode: the tint's hue and saturation at the + // grey's luminosity (SetLum + ClipColor), measured in Photoshop 27.11. + Some(t) => photocraft_color::blend::set_lum(*t, g).map(|v| v.clamp(0.0, 1.0)), None => [g; 3], } }), @@ -1294,6 +1296,31 @@ mod tone_tests { assert!(black_white_gray([1.0, 0.0, 0.0], &w) > black_white_gray([1.0, 0.0, 0.0], &d)); } + /// Photoshop 27.11, measured: Black & White (default weights) with Tint over greys. The tint + /// is blended like the Color blend mode: its hue and saturation at the grey's luminosity. + #[test] + fn black_white_tint_matches_photoshop() { + let weights = [40.0, 60.0, 40.0, 60.0, 20.0, 80.0]; + let measured: [([u8; 3], u8, [u8; 3]); 6] = [ + ([255, 0, 0], 24, [81, 1, 1]), + ([255, 0, 0], 120, [255, 64, 64]), + ([255, 0, 0], 240, [255, 235, 235]), + ([0xe1, 0xd3, 0xb3], 120, [133, 119, 87]), + ([0xe1, 0xd3, 0xb3], 24, [33, 24, 1]), + ([0x40, 0x20, 0x10], 120, [144, 112, 96]), + ]; + for (tint, grey, want) in measured { + let tint = Some(tint.map(|v| v as f32 / 255.0)); + let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[grey as f32 / 255.0; 4]] }; + b.px[0][3] = 1.0; + apply(&Adjustment::BlackWhite { weights, tint }, &mut b); + for (i, w) in want.iter().enumerate() { + let got = b.px[0][i] * 255.0; + assert!((got - *w as f32).abs() <= 2.5, "tint {tint:?} grey {grey} channel {i}: {got} vs {w}"); + } + } + } + #[test] fn gradient_map_dither_stays_close() { let stops = vec![(0.0, [0.0; 3]), (1.0, [1.0; 3])]; diff --git a/crates/gpu/src/compose.wgsl b/crates/gpu/src/compose.wgsl index 5a3a6fe58e..790b217552 100644 --- a/crates/gpu/src/compose.wgsl +++ b/crates/gpu/src/compose.wgsl @@ -686,7 +686,7 @@ fn adjust(c: vec3) -> vec3 { if (c.b <= c.r && c.b <= c.g) { secondary = 1; } else if (c.r <= c.g) { secondary = 3; } let g = clamp(mn + (mid - mn) * w[secondary] / 100.0 + (mx - mid) * w[primary] / 100.0, 0.0, 1.0); if (p1.z > 0.5) { - return clamp(g * p2.rgb * 2.0, vec3(0.0), vec3(1.0)) * 0.5 + g * 0.5; + return clamp(set_lum(p2.rgb, g, 1.0), vec3(0.0), vec3(1.0)); // Color blend of the tint } return vec3(g); } From c5da1a0d5f2cc215d986d1b014bb250c96dacfd5 Mon Sep 17 00:00:00 2001 From: MrCloudy2 <123890706+MrCloudy2@users.noreply.github.com> Date: Mon, 12 Oct 2026 13:49:16 +0200 Subject: [PATCH 23/24] Hue/Saturation: Photoshop's saturation curve, lightness order and Colorize lightness (#3781) * fix(adjust): Hue/Saturation saturation, lightness order and Colorize as in Photoshop Measured in Photoshop 27.11: - Raising Saturation divides it by (1 - s): +50 doubles it. PhotoCraft multiplied by (1 + s), up to 26 levels off. - Master Lightness applies first; hue and saturation then work on the result. Fixes the corpus file adjustments/rgb8/hue-saturation (Hue +40, Saturation +25, Lightness -10): 17 levels / 11.8 % bad -> 2 / 0 %. - Colorize builds the colour at the lightened lightness, so black with Lightness +30 is a 30 % lightness colour, not grey (was 78 off). - A colour range's positive Lightness lightens towards the pixel's brightest channel, not towards white (Blues +50 was 71 off). All 18 Hue/Saturation probe cases are within 4 levels. Corpus: the Colorize files go to 1-3 levels (psd-tools huesaturation_colorize_rgb 120 -> 3). CPU and GPU paths. Co-Authored-By: Claude Opus 5.5 * fix(adjust): a range's negative Lightness darkens towards the darkest channel Measured in Photoshop 27.11 (Blues -50 / -100, Reds -50): (102, 128, 204) at Blues -50 becomes (102, 115, 154), towards the pixel's darkest channel, not towards black. Mirrors the positive rule (towards the brightest). Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/compose/src/adjust.rs | 85 ++++++++++++++++++++++++++++++------ crates/gpu/src/compose.wgsl | 34 ++++++++++----- 2 files changed, 94 insertions(+), 25 deletions(-) diff --git a/crates/compose/src/adjust.rs b/crates/compose/src/adjust.rs index f4e6bede26..a39f3307f9 100644 --- a/crates/compose/src/adjust.rs +++ b/crates/compose/src/adjust.rs @@ -163,7 +163,8 @@ pub fn apply_depth(adj: &Adjustment, buf: &mut Buffer, transfer: Transfer, depth } None => (0.0, 0.0, 0.0), }; - hue_saturation(c, *hue + dh, (*saturation / 100.0 + ds).clamp(-1.0, 1.0), (*lightness / 100.0 + dl).clamp(-1.0, 1.0), *colorize) + let out = hue_saturation(c, *hue + dh, (*saturation / 100.0 + ds).clamp(-1.0, 1.0), (*lightness / 100.0).clamp(-1.0, 1.0), *colorize); + range_lightness(out, dl) }) } Adjustment::Vibrance { vibrance, saturation } => { @@ -428,21 +429,32 @@ pub fn hue_range_tables(ranges: &[HueRange; 6]) -> [Vec; 3] { /// Colorize sets the hue and saturation instead of shifting them; at 0% it leaves only the /// lightness, as in Photoshop (#2326). Ticking Colorize in the dialog starts saturation at 25%. pub fn hue_saturation(c: [f32; 3], hue: f32, s: f32, l: f32, colorize: bool) -> [f32; 3] { - let (mut hh, mut ss, ll) = rgb_to_hsl(c); + let lighten = |v: f32| if l > 0.0 { v + (1.0 - v) * l } else { v * (1.0 + l) }; if colorize { - hh = hue.rem_euclid(360.0) / 360.0; - ss = s.abs().min(1.0); - } else { - hh = (hh + hue / 360.0).rem_euclid(1.0); - ss = (ss * (1.0 + s)).clamp(0.0, 1.0); + // Colorize builds the colour at the lightened (or darkened) lightness, so black with + // Lightness +30 becomes a 30 % lightness colour, not grey (measured in Photoshop 27.11). + let (_, _, ll) = rgb_to_hsl(c); + return hsl_to_rgb(hue.rem_euclid(360.0) / 360.0, s.abs().min(1.0), lighten(ll)); } - let mut rgb = hsl_to_rgb(hh, ss, ll); - if l > 0.0 { - rgb = rgb.map(|v| v + (1.0 - v) * l); - } else if l < 0.0 { - rgb = rgb.map(|v| v * (1.0 + l)); - } - rgb + // Photoshop applies Lightness first, then rotates the hue and scales the saturation of the + // result: Hue +40, Saturation +25, Lightness -10 turns (240, 160, 30) into (173, 243, 0), not + // (168, 230, 14) (Photoshop 27.11 corpus file adjustments/rgb8/hue-saturation). + let (hh, ss, ll) = rgb_to_hsl(c.map(lighten)); + let hh = (hh + hue / 360.0).rem_euclid(1.0); + // Raising saturation divides by 1 - s, lowering it multiplies by 1 + s: +50 % doubles it + // (measured in Photoshop 27.11); +100 % saturates any colour that has some. + let ss = if s > 0.0 { ss / (1.0 - s).max(1.0 / 512.0) } else { ss * (1.0 + s) }.clamp(0.0, 1.0); + hsl_to_rgb(hh, ss, ll) +} + +/// A colour range's Lightness, applied after the master edits. It moves each channel towards the +/// pixel's brightest channel when raised and towards its darkest when lowered, not towards white +/// or black: Blues +50 turns (0, 29, 115) into (57, 71, 115), Blues -50 turns (102, 128, 204) into +/// (102, 115, 153) (measured in Photoshop 27.11). +pub fn range_lightness(c: [f32; 3], l: f32) -> [f32; 3] { + let l = l.clamp(-1.0, 1.0); + let target = if l > 0.0 { c[0].max(c[1]).max(c[2]) } else { c[0].min(c[1]).min(c[2]) }; + c.map(|v| v + (target - v) * l.abs()) } /// Black & White grey value. Each colour is the sum of a grey part (its smallest channel), a @@ -1285,6 +1297,51 @@ mod tone_tests { } } + /// Photoshop 27.11, measured: Hue/Saturation raising saturation, and Colorize with Lightness. + #[test] + fn hue_saturation_matches_photoshop() { + // (input, hue, saturation, lightness, colorize, Photoshop's output) + type Case = ([u8; 3], f32, f32, f32, bool, [u8; 3]); + let measured: [Case; 8] = [ + ([204, 102, 102], 0.0, 50.0, 0.0, false, [254, 51, 51]), + ([204, 159, 102], 0.0, 50.0, 0.0, false, [254, 164, 51]), + ([204, 102, 102], 0.0, -50.0, 0.0, false, [178, 127, 127]), + ([0, 0, 0], 120.0, 100.0, 30.0, true, [0, 152, 0]), + ([28, 28, 28], 120.0, 100.0, 30.0, true, [0, 192, 0]), + ([160, 160, 160], 30.0, 25.0, -40.0, true, [120, 96, 73]), + ([252, 252, 252], 30.0, 25.0, -40.0, true, [177, 151, 126]), + ([255, 143, 0], 30.0, 25.0, -40.0, true, [95, 76, 58]), + ]; + for (input, hue, saturation, lightness, colorize, want) in measured { + let a = Adjustment::HueSaturation { hue, saturation, lightness, colorize, ranges: HueRange::defaults() }; + let c = input.map(|v| v as f32 / 255.0); + let mut b = Buffer { rect: Rect::new(0, 0, 1, 1), px: vec![[c[0], c[1], c[2], 1.0]] }; + apply(&a, &mut b); + for (i, w) in want.iter().enumerate() { + let got = b.px[0][i] * 255.0; + assert!((got - *w as f32).abs() <= 2.0, "{input:?} h{hue} s{saturation} l{lightness} colorize {colorize}, channel {i}: {got} vs {w}"); + } + } + } + + /// Photoshop 27.11, measured: a range's Lightness (Blues ±50) moves towards the brightest or darkest channel. + #[test] + fn range_lightness_matches_photoshop() { + let measured = [ + ([0u8, 29, 115], 0.5, [57u8, 71, 115]), + ([0, 64, 255], 0.5, [125, 157, 255]), + ([102, 128, 204], 0.5, [152, 165, 204]), + ([102, 128, 204], -0.5, [102, 115, 154]), + ([0, 18, 115], -0.5, [0, 9, 58]), + ]; + for (input, l, want) in measured { + let got = range_lightness(input.map(|v| v as f32 / 255.0), l); + for i in 0..3 { + assert!((got[i] * 255.0 - want[i] as f32).abs() <= 2.5, "{input:?} channel {i}: {} vs {}", got[i] * 255.0, want[i]); + } + } + } + #[test] fn black_white_weights() { let d = [40.0, 60.0, 40.0, 60.0, 20.0, 80.0]; diff --git a/crates/gpu/src/compose.wgsl b/crates/gpu/src/compose.wgsl index 790b217552..bf535b08f0 100644 --- a/crates/gpu/src/compose.wgsl +++ b/crates/gpu/src/compose.wgsl @@ -633,19 +633,31 @@ fn adjust(c: vec3) -> vec3 { dl = lut(2, hsl.x) * chroma; } let sat = clamp(p0.y + ds, -1.0, 1.0); - let light = clamp(p0.z + dl, -1.0, 1.0); + let light = clamp(p0.z, -1.0, 1.0); if (p0.w > 0.5) { - hh = rem_euclid(p0.x, 360.0) / 360.0; - ss = min(abs(sat), 1.0); - } else { - hh = rem_euclid(hsl.x + (p0.x + dh) / 360.0, 1.0); - ss = clamp(hsl.y * (1.0 + sat), 0.0, 1.0); + // compose::adjust::hue_saturation: Colorize at the lightened / darkened lightness. + var ll = hsl.z * (1.0 + light); + if (light > 0.0) { ll = hsl.z + (1.0 - hsl.z) * light; } + return hsl_to_rgb(rem_euclid(p0.x, 360.0) / 360.0, min(abs(sat), 1.0), ll); } - var rgb = hsl_to_rgb(hh, ss, hsl.z); - if (light > 0.0) { - rgb = rgb + (1.0 - rgb) * light; - } else if (light < 0.0) { - rgb = rgb * (1.0 + light); + // Lightness first, then hue and saturation of the result. + var lc = c * (1.0 + light); + if (light > 0.0) { lc = c + (1.0 - c) * light; } + let lh = rgb_to_hsl(lc); + hh = rem_euclid(lh.x + (p0.x + dh) / 360.0, 1.0); + // Raising saturation divides by 1 - s; lowering it multiplies by 1 + s. + if (sat > 0.0) { + ss = clamp(lh.y / max(1.0 - sat, 1.0 / 512.0), 0.0, 1.0); + } else { + ss = clamp(lh.y * (1.0 + sat), 0.0, 1.0); + } + var rgb = hsl_to_rgb(hh, ss, lh.z); + // compose::adjust::range_lightness: towards the brightest channel when raised, the darkest when lowered. + let rl = clamp(dl, -1.0, 1.0); + if (rl > 0.0) { + rgb = rgb + (vec3(max(rgb.r, max(rgb.g, rgb.b))) - rgb) * rl; + } else if (rl < 0.0) { + rgb = rgb + (vec3(min(rgb.r, min(rgb.g, rgb.b))) - rgb) * -rl; } return rgb; } From 2aa1f8d2c6a5cdf421b07409be1ac7518de34d2d Mon Sep 17 00:00:00 2001 From: Scott C Hughes <1591011+dottedt@users.noreply.github.com> Date: Mon, 12 Oct 2026 06:49:26 -0500 Subject: [PATCH 24/24] feat(engine): add history.undo and history.redo aliases (#3675) (#3786) A `history.*` namespace exists (history.deleteState, history.newDocument) but not history.undo, so a client or agent guessing `history.undo` gets a hard `unknown command`. Register history.undo and history.redo as aliases of edit.undo and edit.redo, with no menu entry and no shortcut; the Edit menu items keep Cmd+Z / Cmd+Shift+Z. Tests: cargo test -p photocraft-engine --lib history_cmds; cargo test -p photocraft-engine --test panic_hunt -- --ignored; cargo xtask parity. --- crates/engine/src/history_cmds.rs | 41 +++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/crates/engine/src/history_cmds.rs b/crates/engine/src/history_cmds.rs index bb9cb34391..cc18df581e 100644 --- a/crates/engine/src/history_cmds.rs +++ b/crates/engine/src/history_cmds.rs @@ -199,8 +199,39 @@ fn has_doc(s: &Session) -> std::result::Result<(), String> { s.active().map(|_| ()).ok_or_else(|| "no document open".into()) } +/// `history.undo` / `history.redo` enable predicates, matching `edit.undo` / `edit.redo`. +fn can_undo(s: &Session) -> std::result::Result<(), String> { + s.active().filter(|d| d.history.can_undo()).map(|_| ()).ok_or_else(|| "nothing to undo".into()) +} + +fn can_redo(s: &Session) -> std::result::Result<(), String> { + s.active().filter(|d| d.history.can_redo()).map(|_| ()).ok_or_else(|| "nothing to redo".into()) +} + pub fn specs() -> Vec { vec![ + // `history.*` aliases of Edit › Undo / Redo, so a client reaching for the History namespace + // finds them (`edit.undo` / `edit.redo` remain the menu items and own the shortcuts, #3675). + CommandSpec { + id: "history.undo", + label: "Undo", + menu: &[], + shortcut: None, + params: "{} (the same action as `edit.undo`)", + enabled: can_undo, + run: |s, _| Ok(json!(s.undo())), + journal: false, + }, + CommandSpec { + id: "history.redo", + label: "Redo", + menu: &[], + shortcut: None, + params: "{} (the same action as `edit.redo`)", + enabled: can_redo, + run: |s, _| Ok(json!(s.redo())), + journal: false, + }, CommandSpec { id: "history.deleteState", label: "Delete State", @@ -282,6 +313,16 @@ mod tests { s.active().unwrap().history.entries() } + #[test] + fn history_undo_and_redo_alias_edit_undo_and_redo() { + let mut s = session(); + let n = s.active().unwrap().history.past_len(); + s.execute("history.undo", json!({})).unwrap(); + assert_eq!(s.active().unwrap().history.past_len(), n - 1, "history.undo steps back like edit.undo"); + s.execute("history.redo", json!({})).unwrap(); + assert_eq!(s.active().unwrap().history.past_len(), n, "history.redo steps forward like edit.redo"); + } + #[test] fn delete_current_state_steps_back_and_drops_it() { let mut s = session();