From 64dd48d801df4746891e26ab6b8371b4a25fced8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 02:52:41 -0800 Subject: [PATCH 1/9] PSD import: apply Invert, Threshold and Posterize adjustment layers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit File › Open with a PSD or PSB file's layers as objects now reads the nvrt, thrs and post blocks of the PSD file format specification and merges each such adjustment layer with the visible layers below it in its group, changing their colors. Clipped to a layer, it changes only that layer and the layers clipped to it. In a pass-through group with nothing below it in the group, it changes what is below the group when the group is merged. Each channel is taken as an 8-bit sRGB value: Invert turns v into 255 - v, Threshold compares the Rec. 709 luminance with its level, and Posterize maps each channel to the nearest of its evenly spaced levels. The adjusted color is composited in the layer's blend mode at its opacity and fill opacity, through its layer mask. A hidden one is left out. One that layers are clipped to, one clipped to another adjustment layer, one whose data can't be read and one whose merge needs more memory than allowed are not applied and are counted in the existing adjustment-layer warning. Other adjustment kinds are still not applied. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/fileio/psdlayers.rs | 428 ++++++++++++++++-- .../engine/src/cmd/fileio/tests_psdlayers.rs | 347 ++++++++++++++ crates/engine/tests/import_fuzz.rs | 3 +- docs/mcp.md | 24 +- docs/target-app-parity.md | 3 +- 5 files changed, 747 insertions(+), 58 deletions(-) diff --git a/crates/engine/src/cmd/fileio/psdlayers.rs b/crates/engine/src/cmd/fileio/psdlayers.rs index 17e6c3f814..5f3c0a6b01 100644 --- a/crates/engine/src/cmd/fileio/psdlayers.rs +++ b/crates/engine/src/cmd/fileio/psdlayers.rs @@ -32,12 +32,30 @@ //! memory than allowed, the layer comes in alone: in the Normal mode, unclipped, or without its //! knockout. Hidden layers are left out unless `hidden` asks for them. A hidden layer that would need //! a merge (one in a mode VectorCraft lacks, one with a knockout in a group that changes the layers -//! below it, one that layers are clipped to, one clipped to another, or one below a merged layer) is -//! always left out, with the layers clipped to it. Adjustment layers, fill layers that store no -//! pixels and whose fill isn't read or whose shape is a vector mask, layer effects that are switched -//! on, vector masks, and the knockouts of top-level layers, of clipped layers, of layers that others -//! are clipped to and of layers in a pass-through group with a layer in another mode, and other -//! Knockout values, aren't applied; the warnings count them and the hidden layers left out. +//! below it, one that layers are clipped to, one clipped to another, an Invert, Threshold or +//! Posterize adjustment layer, or one below a merged layer) is always left out, with the layers +//! clipped to it. +//! +//! An Invert, Threshold or Posterize adjustment layer, as the import option describes for +//! adjustment layers, is merged with the visible layers below it in its group, which it changes; +//! clipped to a layer, it changes only the layers merged into that one. The rules are VectorCraft's +//! own: each color channel is taken as an 8-bit value of the sRGB color the layers are drawn in, +//! Invert turns `v` into `255 − v`, Threshold makes a pixel white when the luminance of its color +//! (Rec. 709 weights on linear sRGB, encoded back to 0..255) is above the level and black +//! otherwise, and Posterize maps each channel to the nearest of its evenly spaced levels, the higher +//! one on a tie. The adjusted color is composited over the color below in the layer's blend mode, +//! at its opacity times its fill opacity, through its layer mask; transparency stays as it was. One +//! with nothing visible below it in its group changes nothing; in a pass-through group it changes +//! what is below the group when the group is merged, and otherwise isn't applied. One that layers +//! are clipped to, and one clipped to another adjustment layer, isn't applied. +//! +//! Other adjustment layers, Invert, Threshold and Posterize data that can't be read (a level out of +//! range, too short, or a second adjustment block on the layer), fill layers that store no pixels and +//! whose fill isn't read or whose shape is a vector mask, layer effects that are switched on, vector +//! masks, and the knockouts of top-level layers, of clipped layers, of layers that others are clipped +//! to and of layers in a pass-through group with a layer in another mode, and other Knockout values, +//! and adjustments whose merge needs more memory than allowed aren't applied; the warnings count them +//! and the hidden layers left out. //! //! The file is untrusted: every count, length and size is checked before anything is allocated, //! groups nest at most [`MAX_DEPTH`] deep (layers deeper than a document may nest merge into the @@ -193,8 +211,9 @@ enum Content { Pixels, /// A type layer: its pixels come in. Type, - /// An adjustment layer: not applied. - Adjustment, + /// An adjustment layer: the adjustment applied (`None` for another kind, or data that can't be + /// read, which isn't applied). + Adjustment(Option), /// A solid color fill layer: its stored pixels, or its color over the whole canvas when it /// stores none (nothing when the color can't be read, or when its shape is a vector mask). Solid(Option), @@ -202,6 +221,58 @@ enum Content { Fill, } +/// An adjustment the import applies. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Adjust { + /// `nvrt`: each color channel's value `v` (0..255) becomes `255 − v`. + Invert, + /// `thrs`: pixels whose luminance is above the level (1..255) become white, the others black. + Threshold(u8), + /// `post`: each color channel takes the nearest of this many (2..255) evenly spaced levels. + Posterize(u8), +} + +impl Adjust { + /// The adjustment of key `key` whose data is `data`; `None` when the data can't be read or its + /// value is out of range. Invert has no data; Threshold's level and Posterize's count of levels + /// are a 16-bit number followed by 2 bytes of padding, as psd-tools (MIT) reads them + /// (, `psd/adjustments.py`); data shorter than the 4 + /// bytes can't be read. + fn read(key: &[u8; 4], data: &[u8]) -> Option { + let value = || data.get(..4).map(|v| u16::from_be_bytes([v[0], v[1]])); + match key { + b"nvrt" => Some(Adjust::Invert), + b"thrs" => u8::try_from(value()?).ok().filter(|&l| l >= 1).map(Adjust::Threshold), + b"post" => u8::try_from(value()?).ok().filter(|&n| n >= 2).map(Adjust::Posterize), + _ => None, + } + } + + /// Straight RGB, 0..1, adjusted. Each channel is taken as an 8-bit value. Threshold measures + /// the sRGB relative luminance (Rec. 709 weights on the linear values), encoded back to 0..255: + /// above the level is white, at or below it black. Posterize maps a value to the nearest of + /// its levels `k × 255 / (n − 1)`, the higher one on a tie. + fn apply(self, rgb: [f32; 3]) -> [f32; 3] { + use vectorcraft_color::cms::lab::{linear_to_srgb, srgb_to_linear}; + let v = rgb.map(byte); + match self { + Adjust::Invert => v.map(|v| f32::from(255 - v) / 255.0), + Adjust::Threshold(level) => { + let lin = v.map(|v| srgb_to_linear(f32::from(v) / 255.0)); + let y = byte(linear_to_srgb(0.2126 * lin[0] + 0.7152 * lin[1] + 0.0722 * lin[2])); + [if y > level { 1.0 } else { 0.0 }; 3] + } + Adjust::Posterize(n) => { + let steps = u32::from(n) - 1; + v.map(|v| { + let k = (2 * u32::from(v) * steps + 255) / 510; + ((2 * k * 255 + steps) / (2 * steps)) as f32 / 255.0 + }) + } + } + } +} + /// A solid color fill layer's color. #[derive(Clone, Copy, Debug, PartialEq)] enum Paint { @@ -333,6 +404,8 @@ impl Record<'_> { // Effects in a descriptor (`lfx2`, `lmfx`) say whether they are switched on; the older // `lrFX` block is counted whenever it is there. let (mut effects, mut old_effects) = (None, false); + // Whether an adjustment block has been read. + let mut adjusted = false; while e.rest().len() >= 12 { let (Ok(signature), Ok(key)) = (e.array::<4>(), e.array::<4>()) else { break }; if !matches!(&signature, b"8BIM" | b"8B64") { @@ -363,7 +436,12 @@ impl Record<'_> { b"lrFX" => old_effects = true, b"vmsk" | b"vsms" => self.vector_mask = true, b"knko" => self.knockout = data.first().copied().unwrap_or(0), - k if ADJUSTMENTS.contains(&k) => self.content = Content::Adjustment, + // A second adjustment block, with other blocks between them or not, makes the + // layer's adjustment unreadable. + k if ADJUSTMENTS.contains(&k) => { + let again = std::mem::replace(&mut adjusted, true); + self.content = Content::Adjustment(Adjust::read(k, data).filter(|_| !again)); + } _ => {} } // Some writers pad blocks further: skip to the next signature. @@ -390,12 +468,20 @@ impl Record<'_> { matches!(self.content, Content::Solid(Some(_))) && self.stores_nothing() && !self.vector_mask } + /// The adjustment the layer applies, if it is an adjustment layer of a kind the import applies. + fn adjust(&self) -> Option { + match self.content { + Content::Adjustment(a) => a, + _ => None, + } + } + /// Does the layer cover the whole canvas without drawing (an adjustment layer, or a fill that /// stores no pixels, has no vector mask and isn't drawn from its color)? Layers clipped to it /// show over the whole canvas. fn covers_without_drawing(&self) -> bool { match self.content { - Content::Adjustment => true, + Content::Adjustment(_) => true, Content::Solid(None) | Content::Fill => self.stores_nothing() && !self.vector_mask, _ => false, } @@ -701,6 +787,9 @@ enum Drawn { struct Notes { types: usize, adjustments: usize, + /// Adjustment layers of a kind the import applies that it couldn't apply (warned of with + /// `adjustments`). + unadjusted: usize, fills: usize, effects: usize, vector_masks: usize, @@ -730,6 +819,8 @@ struct Counts { clipped_out: usize, /// The groups found to read no pixels. blank: usize, + /// The adjustment layers counted as not applied (see [`Builder::unadjust`]). + unadjusted: usize, } /// Adds the warning for `n` things to `out`: `one` when `n` is 1, `many` with the count in place @@ -778,7 +869,7 @@ impl Notes { let [types, adjustments, fills, effects, masks, knockouts, hidden, clipped_out, unmerged, unclipped] = LAYER_WARNINGS; let mut out = vec![]; note(&mut out, self.types, types); - note(&mut out, self.adjustments, adjustments); + note(&mut out, self.adjustments + self.unadjusted, adjustments); note(&mut out, self.fills, fills); note(&mut out, self.effects, effects); note(&mut out, self.vector_masks, masks); @@ -793,7 +884,7 @@ impl Notes { out } - fn counts(&self, spent: u64, skipped: usize, unknocked: usize, blank: usize) -> Counts { + fn counts(&self, spent: u64, skipped: usize, unknocked: usize, blank: usize, unadjusted: usize) -> Counts { Counts { spent, skipped, @@ -803,6 +894,7 @@ impl Notes { unclipped: self.unclipped, clipped_out: self.clipped_out, blank, + unadjusted, } } } @@ -842,6 +934,10 @@ struct Builder<'a, F> { unclipped: Vec, /// Those records, in the order they were counted. unclip_log: Vec, + /// The records counted as adjustment layers the import applies that weren't applied. + unadjusted: Vec, + /// Those records, in the order they were counted. + unadjust_log: Vec, /// The records that came in as layers of the document (hidden ones too, with `hidden`): not left /// out, though a drawing for a merge that wasn't made counted them. kept: Vec, @@ -922,7 +1018,7 @@ impl [f32; 3]> Builder<'_, F> { let h = self.h; let max_side = if h.psb { 300_000 } else { 30_000 }; let (w, rows) = match rec.content { - Content::Adjustment => return Ok(None), + Content::Adjustment(_) => return Ok(None), // A fill layer that stores no pixels (a shape layer stores its shape's; one that // doesn't, with only its vector mask, isn't drawn). Content::Solid(Some(paint)) if rec.color_over_canvas() => { @@ -1058,8 +1154,14 @@ impl [f32; 3]> Builder<'_, F> { } self.refund(spent)?; // The merge doesn't fit: this layer and the next ones clipped to the same - // base come in as layers of their own. + // base come in as layers of their own; an adjustment layer, which would + // change more than its base, isn't applied. unclipped = true; + if self.adjustment(&body)?.is_some() { + self.squeezed += 1; + self.unadjust(i); + continue; + } self.unclip(i); out.push(Unit { name, visible: true, opacity, blend, mask_of: Some(i), record: i, body, clip: None, base: false }); } @@ -1089,25 +1191,37 @@ impl [f32; 3]> Builder<'_, F> { #[allow(clippy::too_many_arguments)] fn clip(&mut self, out: &mut [Unit<'_>], b: usize, body: &Body<'_>, i: usize, name: &str, blend: Blend, opacity: f32) -> Result { let Some(u) = out.get(b) else { return Ok(true) }; - let (whole, undrawn, fill, base_opacity) = { + let (whole, undrawn, fill, base_opacity, base_adjusts, base_adjustment) = { let r = self.record(u.record)?; let layer = matches!(u.body, Body::Layer(_)); - (layer && r.covers_without_drawing(), layer && r.undrawn_shape(), r.fill, r.opacity) + // The base as a layer, or as the canvas of the layers already clipped to it. + let adjustment = (layer || u.clip.is_some()) && matches!(r.content, Content::Adjustment(_)); + (layer && r.covers_without_drawing(), layer && r.undrawn_shape(), r.fill, r.opacity, layer && r.adjust().is_some(), adjustment) }; // A fill whose shape is a vector mask isn't drawn, and nothing clipped to it is either. if undrawn && u.clip.is_none() { self.clip_out(i); return Ok(true); } - let layer = match self.draw_body(body, Some(i))? { - Drawn::Nothing => return Ok(true), - Drawn::TooLarge => return Ok(false), - Drawn::Canvas(c) => c, + // A clipped adjustment layer changes the merged canvas in place, through its layer mask. + let adjust = self.adjustment(body)?; + let layer = match adjust { + Some(_) => Canvas::default(), + None => match self.draw_body(body, Some(i))? { + Drawn::Nothing => return Ok(true), + Drawn::TooLarge => return Ok(false), + Drawn::Canvas(c) => c, + }, }; let room = self.room(); let layer_bytes = 16 * layer.px.len() as u64; let Some(u) = out.get_mut(b) else { return Ok(true) }; if u.clip.is_none() { + // An adjustment layer that others are clipped to isn't applied. + if base_adjusts { + let record = u.record; + self.unadjust(record); + } let (canvas, clip) = if whole { (Canvas::default(), Clip::Whole) } else { @@ -1134,6 +1248,18 @@ impl [f32; 3]> Builder<'_, F> { u.opacity = base_opacity; } let Body::Merged(c) = &mut u.body else { return Ok(true) }; + if let Some(a) = adjust { + // Clipped to an adjustment layer, it would change the layers below that one: not applied. + if base_adjustment { + self.unadjust(i); + return Ok(true); + } + let mask = self.mask(i, false)?; + adjust_onto(c, a, blend, opacity, mask.as_ref(), i); + u.name.push_str(" + "); + u.name.push_str(name); + return Ok(true); + } match &u.clip { Some(Clip::Shape(_)) => { if (20 * c.px.len() as u64).saturating_add(layer_bytes) > room { @@ -1191,7 +1317,8 @@ impl [f32; 3]> Builder<'_, F> { }; match content { Content::Type => self.notes.types += 1, - Content::Adjustment => self.notes.adjustments += 1, + // One the import applies is counted only where it isn't (see `unadjust`). + Content::Adjustment(None) => self.notes.adjustments += 1, // A fill drawn from neither its pixels nor its color. Content::Fill | Content::Solid(None) if empty => self.notes.fills += 1, Content::Solid(Some(_)) if empty && vector_mask => self.notes.fills += 1, @@ -1286,6 +1413,82 @@ impl [f32; 3]> Builder<'_, F> { } } + /// Count record `i` as an adjustment layer the import applies that wasn't applied (once). + fn unadjust(&mut self, i: usize) { + if let Some(s) = self.unadjusted.get_mut(i) + && !*s + { + *s = true; + self.notes.unadjusted += 1; + self.unadjust_log.push(i); + } + } + + /// The adjustment `body` applies: a layer record that is an adjustment layer the import applies. + fn adjustment(&self, body: &Body<'_>) -> Result, String> { + match body { + Body::Layer(i) => Ok(self.record(*i)?.adjust()), + _ => Ok(None), + } + } + + /// The records of the adjustment layers kept in `out` at `level` (in a pass-through group, to + /// change what is below the group), those kept in the pass-through groups of `out` included. + fn pending(&self, out: &[Unit<'_>], level: Level) -> Result, String> { + let mut records = vec![]; + if level != Level::Pass { + return Ok(records); + } + for u in out { + if self.adjustment(&u.body)?.is_some() { + records.push(u.record); + } else if let (Body::Group(_, items), Blend::Pass) = (&u.body, u.blend) { + records.extend(self.leading(items)?.0); + } + } + Ok(records) + } + + /// The adjustment layers the import applies that a pass-through group with the layers `items` + /// keeps to change what is below it: from the first one with nothing that draws below it in the + /// group (hidden and clipped layers, other adjustment layers and fills that draw nothing aren't + /// counted), it and every one above it, in the pass-through groups inside it too. Also whether + /// anything in `items` draws. + fn leading(&self, items: &[Item]) -> Result<(Vec, bool), String> { + let (mut records, mut draws) = (vec![], false); + for item in items { + match item { + Item::Layer(i) => { + let r = self.record(*i)?; + if r.hidden || r.clipped { + continue; + } + if r.adjust().is_some() { + if !draws || !records.is_empty() { + records.push(*i); + } + } else if !r.covers_without_drawing() { + draws = true; + } + } + Item::Group(g, children) => { + let r = self.record(*g)?; + if r.hidden { + continue; + } + if r.blend == Blend::Pass && (!draws || !records.is_empty()) { + let (inner, inner_draws) = self.leading(children)?; + records.extend(inner); + draws |= inner_draws; + } else { + draws = true; + } + } + } + } + Ok((records, draws)) + } + /// `items`' units, at `level`, with the layers in blend modes VectorCraft lacks, and in a group /// the layers with a shallow knockout, merged with those below. fn merged<'i>(&mut self, items: &'i [Item], keep_hidden: bool, level: Level) -> Result>, String> { @@ -1322,6 +1525,10 @@ impl [f32; 3]> Builder<'_, F> { continue; } Knocked::Merged(canvas) => { + // Adjustment layers kept below it in the group are merged with nothing to change. + for r in self.pending(&out, level)? { + self.unadjust(r); + } self.take_merge(&mut out, &u, canvas); if let Blend::Other(other) = u.blend && !self.notes.merged.contains(&other.label()) @@ -1350,42 +1557,25 @@ impl [f32; 3]> Builder<'_, F> { } } } + if self.adjustment(&u.body)?.is_some() { + self.adjust_below(&mut out, u, level)?; + continue; + } let Blend::Other(other) = u.blend else { out.push(u); continue; }; // A merge that can't be made counts nothing its groups would have counted. let saved = self.saved(); + let pending = self.pending(&out, level)?; let outer = self.try_from_here(); - let made = match out.as_mut_slice() { - // Onto the previous merge alone: composited onto its canvas, in place. - [prev] if prev.is_merge() => { - let mut acc = match &mut prev.body { - Body::Merged(c) => Some(std::mem::take(c)), - _ => None, - }; - let made = self.composite(&mut acc, &u); - if let Body::Merged(c) = &mut prev.body { - *c = acc.unwrap_or_default(); - } - if made? { - prev.name.push_str(" + "); - prev.name.push_str(&u.name); - true - } else { - false - } - } - _ => match self.merge(&out, &u)? { - Some(canvas) => { - self.take_merge(&mut out, &u, canvas); - true - } - None => false, - }, - }; + let made = self.merge_into(&mut out, &u)?; self.tried(outer, made)?; if made { + // Adjustment layers kept below it in the group are merged with nothing to change. + for r in pending { + self.unadjust(r); + } if !self.notes.merged.contains(&other.label()) { self.notes.merged.push(other.label()); } @@ -1400,9 +1590,96 @@ impl [f32; 3]> Builder<'_, F> { Ok(out) } + /// `out` replaced by one layer, the merge of its visible units with `top` (see + /// [`Self::take_merge`]). `false` when the canvas would need more memory than allowed. + fn merge_into<'i>(&mut self, out: &mut Vec>, top: &Unit<'_>) -> Result { + match out.as_mut_slice() { + // Onto the previous merge alone: composited onto its canvas, in place. + [prev] if prev.is_merge() => { + let mut acc = match &mut prev.body { + Body::Merged(c) => Some(std::mem::take(c)), + _ => None, + }; + let made = self.composite(&mut acc, top); + if let Body::Merged(c) = &mut prev.body { + *c = acc.unwrap_or_default(); + } + if made? { + prev.name.push_str(" + "); + prev.name.push_str(&top.name); + Ok(true) + } else { + Ok(false) + } + } + _ => match self.merge(out, top)? { + Some(canvas) => { + self.take_merge(out, top, canvas); + Ok(true) + } + None => Ok(false), + }, + } + } + + /// Adjustment layer `u` (one the import applies), at `level`, merged with the visible units + /// `out` below it in its list: they become one layer, adjusted. A hidden one would need the + /// merge and is left out. With nothing visible below it that draws (other adjustment layers and + /// fills that draw nothing don't count), or at 0 opacity, it changes nothing + /// and comes in as nothing, except in a pass-through group, where it is kept to change what is + /// below the group when the group is drawn onto it; there, once one is kept (in the group or in + /// a pass-through group in it), the ones above it are kept too, in order. One that layers are clipped to, and one whose merge needs more memory + /// than allowed, isn't applied, and is counted. + fn adjust_below<'i>(&mut self, out: &mut Vec>, u: Unit<'i>, level: Level) -> Result<(), String> { + if !u.visible { + self.skip(u.record); + return Ok(()); + } + // One that layers are clipped to, kept as a layer because they drew nothing or their merge + // didn't fit, isn't applied. + if u.base { + self.unadjust(u.record); + return Ok(()); + } + if u.opacity <= 0.0 { + return Ok(()); + } + let mut below = false; + for b in out.iter() { + match &b.body { + // An adjustment layer, or a fill that draws nothing, has nothing to change. + Body::Layer(i) if self.record(*i)?.covers_without_drawing() => {} + _ => below |= b.visible, + } + } + // Kept below it in the group, or in a pass-through group below it there. + let pending = !self.pending(out, level)?.is_empty(); + if level == Level::Pass && (pending || !below) { + out.push(u); + return Ok(()); + } + if !below { + return Ok(()); + } + let saved = self.saved(); + let outer = self.try_from_here(); + let made = self.merge_into(out, &u)?; + self.tried(outer, made)?; + if !made { + self.restore(saved)?; + self.squeezed += 1; + self.unadjust(u.record); + } else if let Blend::Other(other) = u.blend + && !self.notes.merged.contains(&other.label()) + { + self.notes.merged.push(other.label()); + } + Ok(()) + } + /// The counts as they are, for [`Self::restore`]. fn saved(&self) -> Counts { - self.notes.counts(self.spent.get(), self.skip_log.len(), self.unknock_log.len(), self.blank_log.len()) + self.notes.counts(self.spent.get(), self.skip_log.len(), self.unknock_log.len(), self.blank_log.len(), self.unadjust_log.len()) } /// The counts as they were before a merge that couldn't be made, the bytes it spent counted as @@ -1442,6 +1719,12 @@ impl [f32; 3]> Builder<'_, F> { self.notes.clipped_out = self.notes.clipped_out.saturating_sub(1); } } + for i in self.unadjust_log.split_off(c.unadjusted) { + if let Some(s) = self.unadjusted.get_mut(i) { + *s = false; + self.notes.unadjusted = self.notes.unadjusted.saturating_sub(1); + } + } self.notes.merged.truncate(c.merged); self.notes.unmerged = c.unmerged; Ok(()) @@ -1563,7 +1846,7 @@ impl [f32; 3]> Builder<'_, F> { Body::Layer(i) => { let rec = self.record(*i)?; match rec.content { - Content::Adjustment => continue, + Content::Adjustment(_) => continue, Content::Solid(Some(_)) if rec.color_over_canvas() => [0, 0, i64::from(self.h.width), i64::from(self.h.height)], _ => { let (w, h) = rec.bounds.size(); @@ -1643,6 +1926,17 @@ impl [f32; 3]> Builder<'_, F> { } return Ok(true); } + // An adjustment layer changes `acc` where it is, through its layer mask. + if let Some(a) = self.adjustment(&u.body)? { + if let Some(c) = acc.as_mut() { + let mask = match u.mask_of { + Some(i) => self.mask(i, false)?, + None => None, + }; + adjust_onto(c, a, u.blend, u.opacity, mask.as_ref(), u.record); + } + return Ok(true); + } let c = match self.draw_body(&u.body, u.mask_of)? { Drawn::Nothing => return Ok(true), Drawn::Canvas(c) => c, @@ -1760,6 +2054,12 @@ impl [f32; 3]> Builder<'_, F> { if let Some(k) = self.kept.get_mut(u.record) { *k = true; } + // An adjustment layer kept in a pass-through group with nothing below it in the group: the + // layers below the group aren't changed by it. + if self.adjustment(&u.body)?.is_some() { + self.unadjust(u.record); + return Ok(None); + } let children = match &u.body { Body::Layer(i) => match self.image(*i)? { Some((left, top, img)) => vec![Arc::new(self.image_node(&u.name, left, top, img)?)], @@ -1870,6 +2170,32 @@ fn fade(after: &mut Canvas, before: Option<&Canvas>, opacity: f32, mask: Option< } } +/// `c` changed by adjustment `a` (of record `record`): at each pixel, the adjusted color is +/// composited over the color as it was in `blend`, at `opacity` times the value of `mask` (as +/// [`fade`] takes it) there. The transparency of each pixel stays as it was. +fn adjust_onto(c: &mut Canvas, a: Adjust, blend: Blend, opacity: f32, mask: Option<&(i64, i64, image::GrayImage, u8)>, record: usize) { + let width = c.width.max(1); + let opacity = opacity.clamp(0.0, 1.0); + for (k, p) in c.px.iter_mut().enumerate() { + if p[3] <= 0.0 { + continue; + } + let (x, y) = (c.left + (k % width) as i64, c.top + (k / width) as i64); + let m = mask.map_or(255, |(left, top, m, default)| { + let inside = (*left..*left + i64::from(m.width())).contains(&x) && (*top..*top + i64::from(m.height())).contains(&y); + if inside { m.get_pixel((x - left) as u32, (y - top) as u32).0[0] } else { *default } + }); + let t = coverage(blend, opacity * f32::from(m) / 255.0, x, y, record); + if t <= 0.0 { + continue; + } + let rgb = [p[0], p[1], p[2]]; + let [r, g, b] = a.apply(rgb); + let mixed = over(blend, [rgb[0], rgb[1], rgb[2], 1.0], [r, g, b, t]); + *p = [mixed[0], mixed[1], mixed[2], p[3]]; + } +} + /// `src` (of record `record`) at `opacity` composited onto `acc` (nothing when `None`) in `blend`, /// on a canvas covering both (`acc` itself when it covers `src`; a larger one is counted with /// `spend`). `false`, with `acc` as it was, when the canvases held, `acc` and `src` and a larger @@ -2027,6 +2353,8 @@ pub(super) fn import( clipped_out_log: vec![], unclipped: vec![false; records.len()], unclip_log: vec![], + unadjusted: vec![false; records.len()], + unadjust_log: vec![], kept: vec![false; records.len()], spent: Cell::new(0), wasted: Cell::new(0), diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs index d5dccfd662..80d9fba25f 100644 --- a/crates/engine/src/cmd/fileio/tests_psdlayers.rs +++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs @@ -1201,6 +1201,353 @@ fn layers_clipped_to_an_adjustment_layer_show_over_the_canvas() { assert!(r["warnings"].to_string().contains("1 adjustment layer was not applied"), "{r}"); } +/// An adjustment layer of key `key` with `data`, storing no pixels. +fn adjustment(name: &'static str, key: &[u8; 4], data: &[u8]) -> L { + L { blocks: vec![(*key, data.to_vec())], ..layer(name, [0, 0, 0, 0], [0; 4]) } +} + +/// The colors of a 1-pixel-high layer's image, left to right. +fn row_of(s: &Session, l: &Node) -> Vec<[u8; 4]> { + let px = image_of(s, l).1; + (0..px.width()).map(|x| px.get_pixel(x, 0).0).collect() +} + +/// Invert, Threshold and Posterize adjustment layers merge with the visible layers below them, which +/// they change; the layers above stay apart. Invert turns each value `v` into `255 − v`; Threshold +/// at 128 makes a pixel white when its luminance is above 128 and black at or below it; Posterize at +/// 4 levels maps each channel to the nearest of 0, 85, 170 and 255. +#[test] +fn invert_threshold_and_posterize_merge_with_the_layers_below() { + let top = layer("Top", [0, 0, 1, 1], [1, 2, 3, 255]); + for (depth, psb) in [(8, false), (16, false), (8, true), (16, true)] { + let layers = [ + layer("Dark", [0, 0, 1, 1], [10, 20, 30, 255]), + layer("Light", [0, 1, 1, 2], [200, 150, 100, 128]), + adjustment("Invert", b"nvrt", &[]), + top.clone(), + ]; + let (s, r) = open(&file(2, 1, &layers, depth, false, psb), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Dark + Light + Invert", "Top"], "{depth} {psb}: {r}"); + assert_eq!(r["warnings"], json!([]), "{depth} {psb}"); + assert_eq!(row_of(&s, &d.layers[0]), [[245, 235, 225, 255], [55, 105, 155, 128]], "{depth} {psb}: transparency stays"); + assert_eq!(row_of(&s, &d.layers[1]), [[1, 2, 3, 255]], "{depth} {psb}: the layer above isn't changed"); + } + let grays = [ + layer("128", [0, 0, 1, 1], [128, 128, 128, 255]), + layer("129", [0, 1, 1, 2], [129, 129, 129, 255]), + layer("Light", [0, 2, 1, 3], [200, 150, 100, 255]), + layer("Dark", [0, 3, 1, 4], [10, 20, 30, 255]), + ]; + let layers = [&grays[..], &[adjustment("Threshold", b"thrs", &[0, 128, 0, 0])][..]].concat(); + let (s, r) = open(&file(4, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["128 + 129 + Light + Dark + Threshold"], "{r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[0, 0, 0, 255], [255, 255, 255, 255], [255, 255, 255, 255], [0, 0, 0, 255]]); + let layers = + [layer("A", [0, 0, 1, 1], [42, 43, 128, 255]), layer("B", [0, 1, 1, 2], [212, 213, 0, 255]), adjustment("Posterize", b"post", &[0, 4, 0, 0])]; + let (s, r) = open(&file(2, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["A + B + Posterize"], "{r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[0, 85, 170, 255], [170, 255, 0, 255]]); +} + +/// An adjustment layer's opacity, layer mask and blend mode decide how much of the adjusted color +/// replaces the color below. +#[test] +fn an_adjustment_layer_takes_its_opacity_mask_and_blend_mode() { + let black = || layer("Black", [0, 0, 1, 2], [0, 0, 0, 255]); + let half = L { opacity: 128, ..adjustment("Invert", b"nvrt", &[]) }; + let (s, r) = open(&file(2, 1, &[black(), half], 8, false, false), json!({})); + assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[128, 128, 128, 255]; 2], "{r}"); + // Black in the mask leaves the first pixel as it was; outside, the mask's default (white) applies it. + let masked = L { mask: Some(([0, 0, 1, 1], 255, 0, vec![0])), ..adjustment("Invert", b"nvrt", &[]) }; + let (s, r) = open(&file(2, 1, &[black(), masked], 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(row_of(&s, &d.layers[0]), [[0, 0, 0, 255], [255, 255, 255, 255]], "{r}"); + assert!(d.layers[0].extras().mask.is_none(), "the mask is spent on the merge"); + // A disabled mask applies it everywhere. + let off = L { mask: Some(([0, 0, 1, 1], 255, 2, vec![0])), ..adjustment("Invert", b"nvrt", &[]) }; + let (s, _) = open(&file(2, 1, &[black(), off], 8, false, false), json!({})); + assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[255, 255, 255, 255]; 2]); + // Multiply: the inverted color (55, 155, 205) multiplies the color below. + let multiply = L { blend: b"mul ", ..adjustment("Invert", b"nvrt", &[]) }; + let (s, _) = open(&file(1, 1, &[layer("Under", [0, 0, 1, 1], [200, 100, 50, 255]), multiply], 8, false, false), json!({})); + assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[43, 61, 40, 255]]); + // In a mode VectorCraft lacks, the warnings name the mode, as for other layers merged for it. + let dodge = L { blend: b"lddg", ..adjustment("Invert", b"nvrt", &[]) }; + let (s, r) = open(&file(1, 1, &[layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), dodge], 8, false, false), json!({})); + assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[255, 255, 255, 255]], "{r}"); + let merged = "layers in blend modes VectorCraft doesn't have (Linear Dodge) were merged with the layers below them"; + assert_eq!(r["warnings"], json!([merged])); +} + +/// Clipped to a layer, an adjustment layer changes only that layer and the layers clipped to it. +#[test] +fn a_clipped_adjustment_layer_changes_only_its_base() { + let layers = [ + layer("Other", [0, 1, 1, 2], [10, 10, 10, 255]), + layer("Base", [0, 0, 1, 1], [200, 0, 0, 255]), + L { clipped: true, ..adjustment("Invert", b"nvrt", &[]) }, + ]; + let (s, r) = open(&file(2, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Other", "Base + Invert"], "{r}"); + assert_eq!(r["warnings"], json!([])); + assert_eq!((row_of(&s, &d.layers[0]), row_of(&s, &d.layers[1])), (vec![[10, 10, 10, 255]], vec![[55, 255, 255, 255]])); + // Over a layer clipped to the same base, and only inside the base's shape. + let layers = [ + layer("Base", [0, 0, 1, 1], [200, 0, 0, 255]), + L { clipped: true, ..layer("Photo", [0, 0, 1, 2], [0, 0, 255, 255]) }, + L { clipped: true, ..adjustment("Invert", b"nvrt", &[]) }, + ]; + let (s, r) = open(&file(2, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Base + Photo + Invert"], "{r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[255, 255, 0, 255]]); + // Clipped to another adjustment layer, it isn't applied: the layers keep their colors. + let layers = [ + layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), + adjustment("Curves", b"curv", &[0; 4]), + L { clipped: true, ..layer("Photo", [0, 0, 1, 1], [0, 0, 255, 255]) }, + L { clipped: true, ..adjustment("Invert", b"nvrt", &[]) }, + ]; + let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Under", "Curves + Photo"], "{r}"); + assert_eq!((row_of(&s, &d.layers[0]), row_of(&s, &d.layers[1])), (vec![[10, 20, 30, 255]], vec![[0, 0, 255, 255]])); + assert_eq!(r["warnings"], json!(["2 adjustment layers were not applied"])); + // Its layer mask isn't read then: one too large to read doesn't stop the file opening. + let mut masked = layers; + masked[3].mask = Some(([0, 0, 1, 40_000], 0, 0, vec![200])); + let (s, r) = open(&file(1, 1, &masked, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Under", "Curves + Photo"], "{r}"); + assert_eq!(r["warnings"], json!(["2 adjustment layers were not applied"])); + // An Invert layer that a layer drawing nothing is clipped to isn't applied either. + let layers = [ + layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), + adjustment("Invert", b"nvrt", &[]), + L { clipped: true, ..layer("Empty", [0, 0, 0, 0], [0; 4]) }, + ]; + let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Under"], "{r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[10, 20, 30, 255]]); + assert_eq!(r["warnings"], json!(["1 adjustment layer was not applied"])); +} + +/// A hidden adjustment layer changes nothing and is left out, with or without the hidden layers; one +/// with nothing below it, or in an isolated group with nothing below it there, changes nothing. +#[test] +fn hidden_and_lone_adjustment_layers_change_nothing() { + for hidden in [false, true] { + let layers = [layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), L { hidden: true, ..adjustment("Invert", b"nvrt", &[]) }]; + let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({"hiddenLayers": hidden})); + let d = &s.doc().unwrap().doc; + assert_eq!((d.layers.iter().map(|l| name(l)).collect::>(), &r["warnings"]), (vec!["Under"], &json!([HIDDEN_1])), "{hidden}"); + assert_eq!(row_of(&s, &d.layers[0]), [[10, 20, 30, 255]]); + } + let (s, r) = open(&file(1, 1, &[adjustment("Invert", b"nvrt", &[]), layer("Top", [0, 0, 1, 1], [10, 20, 30, 255])], 8, false, false), json!({})); + assert_eq!((s.doc().unwrap().doc.layers.iter().map(|l| name(l)).collect::>(), &r["warnings"]), (vec!["Top"], &json!([]))); + let layers = [layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), group_end(), adjustment("Invert", b"nvrt", &[]), group("Isolated", b"norm")]; + let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!((d.layers.iter().map(|l| name(l)).collect::>(), &r["warnings"]), (vec!["Under", "Isolated"], &json!([]))); + assert_eq!(row_of(&s, &d.layers[0]), [[10, 20, 30, 255]]); +} + +/// In a pass-through group with nothing below it in the group, an adjustment layer changes what is +/// below the group when the group is merged; when the group comes in as layers, it isn't applied. +#[test] +fn an_adjustment_layer_in_a_pass_through_group_changes_what_is_below_the_group() { + let layers = |dodge: bool| { + let mut l = vec![layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), group_end(), adjustment("Invert", b"nvrt", &[]), group("Folder", b"pass")]; + if dodge { + l.push(L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }); + } + l + }; + let (s, r) = open(&file(1, 1, &layers(true), 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Under + Folder + Dodge"], "{r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[245, 235, 225, 255]]); + let (s, r) = open(&file(1, 1, &layers(false), 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Under", "Folder"], "{r}"); + assert_eq!(r["warnings"], json!(["1 adjustment layer was not applied"])); + // Two at the bottom of the group both change what is below it, in order: inverted, then + // posterized to 4 levels (without the Invert the color would posterize to black). + let stacked = [ + layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), + group_end(), + adjustment("Invert", b"nvrt", &[]), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Folder", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + ]; + let (s, r) = open(&file(1, 1, &stacked, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Under + Folder + Dodge"], "{r}"); + assert_eq!((row_of(&s, &d.layers[0]), r["warnings"].to_string().contains("adjustment")), (vec![[255, 255, 255, 255]], false), "{r}"); + // One above a layer of the group, with one kept below that layer, is kept too: the group draws + // them in order over what is below it. + let between = [ + layer("Under", [0, 0, 1, 2], [10, 20, 30, 255]), + group_end(), + adjustment("Invert", b"nvrt", &[]), + layer("Top", [0, 1, 1, 2], [100, 100, 100, 255]), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Folder", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + ]; + let (s, r) = open(&file(2, 1, &between, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Under + Folder + Dodge"], "{r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[255, 255, 255, 255], [85, 85, 85, 255]], "{r}"); + // Another adjustment layer below it in the group draws nothing, so it still changes what is + // below the group. + let over_curves = [ + layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), + group_end(), + adjustment("Curves", b"curv", &[0; 4]), + adjustment("Invert", b"nvrt", &[]), + group("Folder", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + ]; + let (s, r) = open(&file(1, 1, &over_curves, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Under + Folder + Dodge"], "{r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[245, 235, 225, 255]], "{r}"); + // One kept in a pass-through group inside the group keeps the ones above it too: inverted, then + // posterized to 4 levels. + let nested = [ + layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), + group_end(), + group_end(), + adjustment("Invert", b"nvrt", &[]), + group("Inner", b"pass"), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Folder", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + ]; + let (s, r) = open(&file(1, 1, &nested, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Under + Folder + Dodge"], "{r}"); + assert_eq!((row_of(&s, &d.layers[0]), r["warnings"].to_string().contains("adjustment")), (vec![[255, 255, 255, 255]], false), "{r}"); + // Without the merge, the group comes in as layers and both are counted as not applied. + let (s, r) = open(&file(1, 1, &nested[..7], 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Under", "Folder"], "{r}"); + assert_eq!(r["warnings"], json!(["2 adjustment layers were not applied"])); + // Merged in the group with a layer in a mode VectorCraft lacks, it has nothing to change. + let inside = [ + layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), + group_end(), + adjustment("Invert", b"nvrt", &[]), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + group("Folder", b"pass"), + ]; + let (s, r) = open(&file(1, 1, &inside, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + let names: Vec<&str> = d.layers.iter().map(|l| name(l)).collect(); + let merged = "layers in blend modes VectorCraft doesn't have (Linear Dodge) were merged with the layers below them"; + assert_eq!((names, &r["warnings"]), (vec!["Under", "Folder"], &json!(["1 adjustment layer was not applied", merged])), "{r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[10, 20, 30, 255]]); +} + +/// Invert, Threshold and Posterize data that can't be read is not applied, with a warning: a level +/// out of range, data too short, or a second adjustment block on the layer. +#[test] +fn adjustment_data_that_cant_be_read_isnt_applied() { + let mut twice = adjustment("Twice", b"nvrt", &[]); + twice.blocks.push((*b"post", vec![0, 4, 0, 0])); + let mut apart = adjustment("Apart", b"nvrt", &[]); + apart.blocks.extend([(*b"SoCo", vec![]), (*b"post", vec![0, 4, 0, 0])]); + let cases = [ + adjustment("Level 0", b"thrs", &[0, 0, 0, 0]), + adjustment("Level 256", b"thrs", &[1, 0, 0, 0]), + adjustment("No level", b"thrs", &[]), + adjustment("No padding", b"thrs", &[0, 128]), + adjustment("No padding", b"post", &[0, 4]), + adjustment("1 level", b"post", &[0, 1, 0, 0]), + adjustment("256 levels", b"post", &[1, 0, 0, 0]), + twice, + apart, + ]; + for bad in cases { + let what = bad.name; + let (s, r) = open(&file(1, 1, &[layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), bad], 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Under"], "{what}: {r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[10, 20, 30, 255]], "{what}"); + assert_eq!(r["warnings"], json!(["1 adjustment layer was not applied"]), "{what}"); + } + // The highest level and count are read. + let under = |c: u8| layer("Under", [0, 0, 1, 1], [c, c, c, 255]); + let (s, r) = open(&file(1, 1, &[under(254), adjustment("Max", b"thrs", &[0, 255, 0, 0])], 8, false, false), json!({})); + assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[0, 0, 0, 255]], "{r}"); + let (s, r) = open(&file(1, 1, &[under(7), adjustment("Max", b"post", &[0, 255, 0, 0])], 8, false, false), json!({})); + assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[7, 7, 7, 255]], "{r}"); +} + +/// An adjustment layer whose merge needs more memory than allowed isn't applied: the layers below +/// it stay as they are, with a warning. +#[test] +fn an_adjustment_merge_past_the_memory_allowed_isnt_applied() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let layers = [layer("Under", [0, 0, 2, 2], [10, 20, 30, 255]), layer("Beside", [2, 2, 4, 4], [1, 2, 3, 255]), adjustment("Invert", b"nvrt", &[])]; + let f = file(4, 4, &layers, 8, false, false); + // Each 2 × 2 layer fits 128 bytes; the 4 × 4 canvas of both doesn't. + let (doc, warnings) = psdlayers::import(&f, false, 128, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::>(), ["Under", "Beside"]); + assert_eq!(warnings, ["1 adjustment layer was not applied"]); + let (doc, warnings) = psdlayers::import(&f, false, 1 << 20, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::>(), ["Under + Beside + Invert"]); + assert!(warnings.is_empty(), "{warnings:?}"); + // Clipped: the base's canvas with its shape doesn't fit 300 bytes, so the adjustment is left + // out rather than applied to everything below. + let layers = [layer("Base", [0, 0, 4, 4], [10, 20, 30, 255]), L { clipped: true, ..adjustment("Invert", b"nvrt", &[]) }]; + let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 300, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::>(), ["Base"]); + assert_eq!(warnings, ["1 adjustment layer was not applied"]); + // A layer clipped to an Invert layer whose merge doesn't fit comes in unclipped, and the Invert + // layer isn't applied to the layers below it. + let layers = [ + layer("Under", [0, 0, 2, 2], [10, 20, 30, 255]), + adjustment("Invert", b"nvrt", &[]), + L { clipped: true, ..layer("Photo", [0, 0, 4, 4], [1, 2, 3, 255]) }, + ]; + let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 128, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::>(), ["Under", "Photo"], "{warnings:?}"); + assert!(warnings.iter().any(|w| w == "1 adjustment layer was not applied"), "{warnings:?}"); +} + +/// Damaged Invert, Threshold and Posterize layers, masked and clipped, open without a panic. +#[test] +fn damaged_adjustment_layers_never_panic() { + let layers = [ + layer("A", [0, 0, 2, 2], [255, 0, 0, 255]), + L { mask: Some(([0, 0, 1, 1], 0, 0, vec![200])), ..adjustment("Invert", b"nvrt", &[]) }, + L { clipped: true, ..adjustment("Threshold", b"thrs", &[0, 128, 0, 0]) }, + adjustment("Posterize", b"post", &[0, 3, 0, 0]), + ]; + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let good = file(2, 2, &layers, 8, false, false); + assert!(psdlayers::import(&good, true, 1 << 30, cms).unwrap().is_some()); + for i in 0..good.len() { + for v in [0, 1, 0x7f, 0x80, 0xff] { + let mut f = good.clone(); + f[i] = v; + let _ = psdlayers::import(&f, true, 1 << 30, cms); + let _ = psdlayers::import(&f, false, 64, cms); + } + } + for n in 0..good.len() { + let _ = psdlayers::import(&good[..n], true, 1 << 30, cms); + } +} + /// Each blend mode VectorCraft lacks merges with the layer below by its formula, from the public /// descriptions: /// (Vivid Light, Pin Light, Hard Mix, Darker and Lighter Color) and diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 9c83f697da..b655ed0eb5 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -2095,7 +2095,8 @@ proptest! { /// Mutated copies of the PSD and PSB samples never crash opening them with their layers, hidden /// ones too: the PSD's layer records, channel lengths and data, and the PSB's layer count. - /// (Masks, clipping and groups are covered by `tests_psdlayers::damaged_layers_never_panic`.) + /// (Masks, clipping and groups are covered by `tests_psdlayers::damaged_layers_never_panic`, and + /// Invert, Threshold and Posterize layers by `tests_psdlayers::damaged_adjustment_layers_never_panic`.) /// Neither does `document.psdInfo`, nor placing them with their layers as objects. #[test] fn mutated_layered_psds_open_without_panics(which in 6usize..8, cut in 0usize..1_000_000, edits in prop::collection::vec((0usize..1_000_000, any::()), 0..12)) { diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..5e4b1ddf55 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10872,8 +10872,8 @@ clipping mask into one layer and discards hidden layers that require merging; th imports one image, and Import Hidden Layers brings hidden layers in. `document.open` does the same, with `layers: false` for the single image and `hiddenLayers: true` for the hidden layers. The page also merges adjustment layers, layers with a knockout option, and layers that hold transparent pixels in some blend modes with -the layers below them. `document.open` does not apply adjustments, applies only shallow knockouts inside groups, and -otherwise merges a layer by its blend mode alone, as the rules below say. +the layers below them. `document.open` applies only Invert, Threshold and Posterize adjustments, applies only +shallow knockouts inside groups, and otherwise merges a layer by its blend mode alone, as the rules below say. The rest are VectorCraft's own rules: @@ -10909,10 +10909,22 @@ The rest are VectorCraft's own rules: stores. A solid color fill layer that stores no pixels and has no vector mask comes in as an image of its color (RGB, CMYK, Grayscale, Lab or HSB) over the canvas. One whose shape is a vector mask isn't drawn, and the layers clipped to it are left out. -- Adjustment layers, fill layers that store no pixels and whose fill isn't read, layer effects that are switched on, - the other knockouts (top-level layers, clipped layers, layers that others are clipped to, Pass Through groups with - layers in other modes, other Knockout values, and merges that need more memory than allowed) and vector masks are - not applied; the `warnings` count them. +- An Invert, Threshold or Posterize adjustment layer (`nvrt`, `thrs` and `post` in the PSD file format + specification) is merged with the visible layers below it in its group, which it changes. Clipped to a layer, it + changes only that layer and the layers clipped to it. Each color channel is taken as an 8-bit sRGB value: Invert + turns `v` into `255 − v`; Threshold makes a pixel white when its luminance (Rec. 709 weights on linear sRGB, + encoded back to 0..255) is above the level (1 to 255) and black otherwise; Posterize maps each channel to the + nearest of its 2 to 255 evenly spaced levels, the higher one on a tie. The adjusted color is composited over the + color below in the layer's blend mode, at its opacity times its fill opacity, through its layer mask, and + transparency is kept. A hidden one is left out. One with nothing visible below it in its group changes nothing; in + a Pass Through group it changes what is below the group only when the group is merged, and is otherwise not + applied. +- Other adjustment layers, Invert, Threshold and Posterize layers that others are clipped to, that are clipped to + another adjustment layer, whose data can't be read (a level out of range, too short, or two adjustment blocks on + one layer) or whose merge needs more memory than allowed, fill layers that store no pixels and whose fill isn't + read, layer effects that are switched on, the other knockouts (top-level layers, clipped layers, layers that others + are clipped to, Pass Through groups with layers in other modes, other Knockout values, and merges that need more + memory than allowed) and vector masks are not applied; the `warnings` count them. - Layer channels may be raw, PackBits or zipped (with or without prediction) at 8, 16 and 32 bits. - A file without layers opens as its merged image. A file whose layers can't be read opens as its merged image with a warning, and when the merged image can't be read either, the file is refused with an error. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..2f1aee44ba 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2323,7 +2323,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur EPS export and EPS Save make each file's PNG thumbnail from its TIFF preview, averaging the preview's pixels down to the thumbnail's size on white, instead of drawing the document a second time; a file without a preview still draws its thumbnail (`crates/engine/src/cmd/fileio/tests_eps.rs`). - Targa files (`.tga`, `.vda`, `.icb`, `.vst`) open, place linked or embedded, relink and update at their pixel size: color-mapped, true-color and black-and-white, raw or run-length encoded, in any of the four row orders. The image descriptor's attribute bits and the extension area's Attributes Type decide the transparency: a file with no attribute bits, or with attribute data the Attributes Type calls undefined, opens opaque; with one bit, a 16-bit true-color pixel takes that bit as its alpha, and a color-mapped pixel takes the bit of the 16-bit color map entry it indexes; premultiplied colors are divided by their alpha. Open and Place recognize a Targa file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a Targa file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/tests/links.rs`). - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). - - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the visible layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the visible layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill where it covers none of their painted pixels, isn't merged for the knockout), and adjustment layers, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). + - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the visible layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the visible layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill where it covers none of their painted pixels, isn't merged for the knockout), and adjustment layers other than Invert, Threshold and Posterize, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). + - File › Open with a PSD or PSB file's layers as objects applies Invert, Threshold and Posterize adjustment layers (the `nvrt`, `thrs` and `post` blocks of the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/)): each is merged with the visible layers below it in its group, which it changes, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for adjustment layers; clipped to a layer, it changes only that layer and the layers clipped to it. Each adjustment works on the colors as [the help page](https://helpx.adobe.com/photoshop/desktop/adjust-color/color-effects-techniques/apply-special-color-effects-to-images.html) describes them. VectorCraft's own rules: each channel is taken as an 8-bit sRGB value; Invert turns `v` into `255 − v`; Threshold compares the Rec. 709 luminance of linear sRGB, encoded back to 0..255, with its level (1 to 255), white above it and black at or below it; Posterize maps each channel to the nearest of its 2 to 255 evenly spaced levels, the higher one on a tie; the adjusted color is composited over the color below in the layer's blend mode at its opacity and fill opacity, through its layer mask, and transparency is kept. A hidden one is left out; one with nothing visible below it in its group changes nothing, and in a pass-through group it changes what is below the group only when the group is merged; one that layers are clipped to, one clipped to another adjustment layer, one whose data can't be read (a level out of range, too short, or two adjustment blocks on one layer), and one whose merge needs more memory than allowed aren't applied and are counted in the warnings (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none; `links.update` leaves a distorted image's clipping as it is. When Placement Options do not clip the image, a clip group whose clipping path was changed in the document (an anchor or handle moved by a thousandth of a point or more, anchors added or removed, a subpath opened or closed, or its fill rule changed) and a clipping mask made in the document are kept: a new file that names no clipping path leaves the mask clipping the image, and the clip group of a new file that names one goes inside the mask. Files that name no clipping path come in as before. `links.unembed` keeps the clip group, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/dcs.rs`). - Import Slices: File › Open of a PSD or PSB file with slices, and File › Place of one without Link, bring its slices in as user slices, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded; PSD Import Options offers Import Slices for such a file. `document.open` and `file.place` take `importSlices`, and `document.psdInfo` counts the slices. The slices are read from image resource 1050 in version 6 and in the descriptor of versions 7 and 8, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it. VectorCraft's own rules: Import Slices applies to Convert Layers to Objects and to Flatten Layers to a Single Image alike, and makes the dialog ask for a file with fewer than two layers; placed slices move and scale with the art in the same undo step; each slice keeps its name, type, link, target, message, alternative text, cell text and background color; slices the file generated automatically, and slices wholly outside the canvas, are left out; slices that can't be read are left out with a warning while the art comes in; with Show Import Options off, a PSD file is placed with the PSD Import Options chosen last, and on, each PSD file of the place cursor asks for them (`crates/engine/src/cmd/fileio/tests_psdslices.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). From aecf4b12846a6eff063a479add90abc6fdb15be2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 04:03:36 -0800 Subject: [PATCH 2/9] PSD import: keep adjustment layers pending over layers that draw nothing - A hidden pass-through group, kept with the hidden layers, and an adjustment layer at 0 opacity or 0 fill no longer hold back the adjustment layers above them in a pass-through group. - Layers that draw nothing (no pixels stored, 0 opacity, or 0 fill with nothing clipped to them) and groups of only such layers don't count as content below an adjustment layer, so in a pass-through group it still changes what is below the group. Layers clipped to a layer at 0 fill or to an adjustment layer count as content. - An adjustment layer whose layer mask is too large for the memory allowed is counted as not applied, merged or clipped, instead of stopping the layered import. --- crates/engine/src/cmd/fileio/psdlayers.rs | 168 ++++++++++++---- .../engine/src/cmd/fileio/tests_psdlayers.rs | 184 ++++++++++++++++++ docs/mcp.md | 7 +- docs/target-app-parity.md | 2 +- 4 files changed, 318 insertions(+), 43 deletions(-) diff --git a/crates/engine/src/cmd/fileio/psdlayers.rs b/crates/engine/src/cmd/fileio/psdlayers.rs index 5f3c0a6b01..5fc6916c5e 100644 --- a/crates/engine/src/cmd/fileio/psdlayers.rs +++ b/crates/engine/src/cmd/fileio/psdlayers.rs @@ -45,7 +45,9 @@ //! otherwise, and Posterize maps each channel to the nearest of its evenly spaced levels, the higher //! one on a tie. The adjusted color is composited over the color below in the layer's blend mode, //! at its opacity times its fill opacity, through its layer mask; transparency stays as it was. One -//! with nothing visible below it in its group changes nothing; in a pass-through group it changes +//! with nothing visible below it in its group that draws (a layer that stores no pixels or is at 0 +//! opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such layers) +//! changes nothing; in a pass-through group it changes //! what is below the group when the group is merged, and otherwise isn't applied. One that layers //! are clipped to, and one clipped to another adjustment layer, isn't applied. //! @@ -54,7 +56,7 @@ //! whose fill isn't read or whose shape is a vector mask, layer effects that are switched on, vector //! masks, and the knockouts of top-level layers, of clipped layers, of layers that others are clipped //! to and of layers in a pass-through group with a layer in another mode, and other Knockout values, -//! and adjustments whose merge needs more memory than allowed aren't applied; the warnings count them +//! and adjustments whose merge, their layer mask included, needs more memory than allowed aren't applied; the warnings count them //! and the hidden layers left out. //! //! The file is untrusted: every count, length and size is checked before anything is allocated, @@ -487,6 +489,12 @@ impl Record<'_> { } } + /// Does the layer draw nothing (an adjustment layer, or one that stores no pixels and isn't a + /// fill drawn from its color over the canvas; see [`Builder::image`])? + fn draws_nothing(&self) -> bool { + self.covers_without_drawing() || (self.stores_nothing() && !self.color_over_canvas()) + } + /// Is the layer a fill that stores no pixels and whose shape is a vector mask, so that it /// isn't drawn? fn undrawn_shape(&self) -> bool { @@ -1089,6 +1097,22 @@ impl [f32; 3]> Builder<'_, F> { Ok(Some((i64::from(m.bounds.left), i64::from(m.bounds.top), img, read(m.default)))) } + /// Does record `i`'s layer mask, switched on, fit the memory allowed for reading it with + /// [`Self::mask`]? `true` when it has none, and when its size is damaged (reading it says so). + fn mask_fits(&self, i: usize) -> Result { + let rec = self.record(i)?; + let Some(m) = rec.mask.filter(|m| !m.disabled) else { return Ok(true) }; + if !rec.channels.iter().any(|(c, _)| *c == -2) { + return Ok(true); + } + let (w, rows) = m.bounds.size(); + let max_side = if self.h.psb { 300_000 } else { 30_000 }; + if w > max_side || rows > max_side { + return Ok(true); + } + Ok(self.fits((row_bytes(w, self.h.depth) as u64 + w as u64).saturating_mul(rows as u64)).is_ok()) + } + /// Multiply `c`'s transparency by record `i`'s layer mask. fn apply_mask(&self, c: &mut Canvas, i: usize) -> Result<(), String> { let Some((left, top, m, default)) = self.mask(i, false)? else { return Ok(()) }; @@ -1205,6 +1229,10 @@ impl [f32; 3]> Builder<'_, F> { } // A clipped adjustment layer changes the merged canvas in place, through its layer mask. let adjust = self.adjustment(body)?; + // Its layer mask too large to read needs more memory than allowed. + if adjust.is_some() && !base_adjustment && !self.mask_fits(i)? { + return Ok(false); + } let layer = match adjust { Some(_) => Canvas::default(), None => match self.draw_body(body, Some(i))? { @@ -1433,13 +1461,15 @@ impl [f32; 3]> Builder<'_, F> { } /// The records of the adjustment layers kept in `out` at `level` (in a pass-through group, to - /// change what is below the group), those kept in the pass-through groups of `out` included. + /// change what is below the group), those kept in the visible pass-through groups of `out` + /// included. fn pending(&self, out: &[Unit<'_>], level: Level) -> Result, String> { let mut records = vec![]; if level != Level::Pass { return Ok(records); } - for u in out { + // A hidden unit, kept with the hidden layers, or one at 0 opacity, changes nothing. + for u in out.iter().filter(|u| u.visible && u.opacity > 0.0) { if self.adjustment(&u.body)?.is_some() { records.push(u.record); } else if let (Body::Group(_, items), Blend::Pass) = (&u.body, u.blend) { @@ -1451,44 +1481,98 @@ impl [f32; 3]> Builder<'_, F> { /// The adjustment layers the import applies that a pass-through group with the layers `items` /// keeps to change what is below it: from the first one with nothing that draws below it in the - /// group (hidden and clipped layers, other adjustment layers and fills that draw nothing aren't - /// counted), it and every one above it, in the pass-through groups inside it too. Also whether - /// anything in `items` draws. + /// group (hidden and clipped layers, other adjustment layers, layers and groups at 0 opacity, and + /// layers and groups that draw nothing aren't counted), it and every one above it, in the + /// pass-through groups inside it too; one at 0 opacity isn't kept. Also whether anything in + /// `items` draws. fn leading(&self, items: &[Item]) -> Result<(Vec, bool), String> { let (mut records, mut draws) = (vec![], false); - for item in items { - match item { - Item::Layer(i) => { - let r = self.record(*i)?; - if r.hidden || r.clipped { - continue; - } - if r.adjust().is_some() { - if !draws || !records.is_empty() { - records.push(*i); - } - } else if !r.covers_without_drawing() { - draws = true; + for (k, item) in items.iter().enumerate() { + let (i, r, children) = match item { + Item::Layer(i) => (*i, self.record(*i)?, None), + Item::Group(g, children) => (*g, self.record(*g)?, Some(children)), + }; + // A clipped one draws as part of the one it is clipped to. + if r.hidden || r.clipped { + continue; + } + let (clips, drawn) = self.base_draws(items, k)?; + // One that layers are clipped to isn't kept, and a pass-through group they are clipped to + // is drawn alone (see `clip`). One at 0 opacity changes nothing (see `adjust_below`). + let keeps = !clips && r.opacity * r.fill > 0.0 && (!draws || !records.is_empty()); + match children { + None if r.adjust().is_some() && !clips => { + if keeps { + records.push(i); } } - Item::Group(g, children) => { - let r = self.record(*g)?; - if r.hidden { - continue; - } - if r.blend == Blend::Pass && (!draws || !records.is_empty()) { - let (inner, inner_draws) = self.leading(children)?; - records.extend(inner); - draws |= inner_draws; - } else { - draws = true; - } + Some(children) if r.blend == Blend::Pass && keeps => { + let (inner, inner_draws) = self.leading(children)?; + records.extend(inner); + draws |= inner_draws; } + _ => draws |= drawn, } } Ok((records, draws)) } + /// Does anything in `items` draw: a visible layer or group that isn't clipped and draws (see + /// [`Self::base_draws`])? + fn draws(&self, items: &[Item]) -> Result { + for (k, item) in items.iter().enumerate() { + let r = match item { + Item::Layer(i) => self.record(*i)?, + Item::Group(g, _) => self.record(*g)?, + }; + if !r.hidden && !r.clipped && self.base_draws(items, k)?.1 { + return Ok(true); + } + } + Ok(false) + } + + /// For item `k` of `items`, visible and not clipped: whether visible layers are clipped to it, + /// and whether it draws, above 0 opacity: by its own pixels (a group's, those of its layers) + /// above 0 fill, or by those of the layers clipped to it that draw, which show in its pixels at + /// any fill, or over the canvas when it is a layer that covers it without drawing. + fn base_draws(&self, items: &[Item], k: usize) -> Result<(bool, bool), String> { + let Some(item) = items.get(k) else { return Ok((false, false)) }; + let (r, own) = self.pixels(item)?; + let covers = matches!(item, Item::Layer(_)) && r.covers_without_drawing(); + let (mut clips, mut clips_draw) = (false, false); + for above in items.get(k + 1..).unwrap_or_default() { + let c = match above { + Item::Layer(i) => self.record(*i)?, + Item::Group(g, _) => self.record(*g)?, + }; + if !c.clipped { + break; + } + if c.hidden { + continue; + } + clips = true; + if !clips_draw && c.opacity * c.fill > 0.0 { + clips_draw = self.pixels(above)?.1; + } + } + let drawn = (r.fill > 0.0 && own) || (clips_draw && (covers || own)); + Ok((clips, r.opacity > 0.0 && drawn)) + } + + /// `item`'s record, and whether it has pixels of its own: a layer that draws, or a group with + /// something in it that draws (see [`Self::draws`]). + fn pixels(&self, item: &Item) -> Result<(&Record<'_>, bool), String> { + Ok(match item { + Item::Layer(i) => { + let r = self.record(*i)?; + (r, !r.draws_nothing()) + } + Item::Group(g, children) => (self.record(*g)?, self.draws(children)?), + }) + } + /// `items`' units, at `level`, with the layers in blend modes VectorCraft lacks, and in a group /// the layers with a shallow knockout, merged with those below. fn merged<'i>(&mut self, items: &'i [Item], keep_hidden: bool, level: Level) -> Result>, String> { @@ -1625,7 +1709,8 @@ impl [f32; 3]> Builder<'_, F> { /// Adjustment layer `u` (one the import applies), at `level`, merged with the visible units /// `out` below it in its list: they become one layer, adjusted. A hidden one would need the /// merge and is left out. With nothing visible below it that draws (other adjustment layers and - /// fills that draw nothing don't count), or at 0 opacity, it changes nothing + /// layers and groups that draw nothing or are at 0 opacity don't count), or at 0 opacity, it + /// changes nothing /// and comes in as nothing, except in a pass-through group, where it is kept to change what is /// below the group when the group is drawn onto it; there, once one is kept (in the group or in /// a pass-through group in it), the ones above it are kept too, in order. One that layers are clipped to, and one whose merge needs more memory @@ -1645,12 +1730,15 @@ impl [f32; 3]> Builder<'_, F> { return Ok(()); } let mut below = false; - for b in out.iter() { - match &b.body { - // An adjustment layer, or a fill that draws nothing, has nothing to change. - Body::Layer(i) if self.record(*i)?.covers_without_drawing() => {} - _ => below |= b.visible, - } + for b in out.iter().filter(|b| b.visible && b.opacity > 0.0) { + below |= match &b.body { + // An adjustment layer, a layer that draws nothing, or a group of such layers, has + // nothing to change. + Body::Layer(i) => !self.record(*i)?.draws_nothing(), + Body::Group(_, items) => self.draws(items)?, + // Clipped layers merged with a base that has no pixels have none either. + Body::Merged(c) => c.px.iter().any(|p| p[3] > 0.0), + }; } // Kept below it in the group, or in a pass-through group below it there. let pending = !self.pending(out, level)?.is_empty(); @@ -1930,6 +2018,8 @@ impl [f32; 3]> Builder<'_, F> { if let Some(a) = self.adjustment(&u.body)? { if let Some(c) = acc.as_mut() { let mask = match u.mask_of { + // A layer mask too large to read needs more memory than allowed. + Some(i) if !self.mask_fits(i)? => return Ok(false), Some(i) => self.mask(i, false)?, None => None, }; diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs index 80d9fba25f..8ebc3a9f24 100644 --- a/crates/engine/src/cmd/fileio/tests_psdlayers.rs +++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs @@ -1456,6 +1456,171 @@ fn an_adjustment_layer_in_a_pass_through_group_changes_what_is_below_the_group() assert_eq!(row_of(&s, &d.layers[0]), [[10, 20, 30, 255]]); } +/// The layer of a pass-through group's sublayers whose name ends with `end`. +fn sublayer<'d>(folder: &'d Node, end: &str) -> &'d Node { + let children = folder.children().map(Vec::as_slice).unwrap_or_default(); + let names: Vec<&str> = children.iter().map(|c| name(c)).collect(); + children.iter().find(|c| name(c).ends_with(end)).unwrap_or_else(|| panic!("no sublayer ending with {end} in {names:?}")) +} + +/// An adjustment layer that changes nothing, in a hidden pass-through group or at 0 opacity or 0 +/// fill, keeps no adjustment layer above it in the group from merging with the layers below it: +/// the gray 100 posterizes to 85. +#[test] +fn adjustment_layers_that_change_nothing_hold_none_back() { + let invert = |opacity: u8, fill: u8| { + let mut l = L { opacity, ..adjustment("Invert", b"nvrt", &[]) }; + l.blocks.push((*b"iOpa", vec![fill])); + l + }; + let cases = [("hidden group", true, invert(255, 255)), ("0 opacity", false, invert(0, 255)), ("0 fill", false, invert(255, 0))]; + for (what, hidden, invert) in cases { + let layers = [ + group_end(), + group_end(), + invert, + L { hidden, ..group("Inner", b"pass") }, + layer("Photo", [0, 0, 1, 1], [100, 100, 100, 255]), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Folder", b"pass"), + ]; + let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({"hiddenLayers": hidden})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Folder"], "{what}: {r}"); + assert_eq!(row_of(&s, sublayer(&d.layers[0], "Photo + Posterize")), [[85, 85, 85, 255]], "{what}: {r}"); + } +} + +/// A layer that stores no pixels draws nothing: an adjustment layer above it in a pass-through group, +/// directly or in a pass-through group inside it, still changes what is below the group. +#[test] +fn an_adjustment_layer_over_layers_that_draw_nothing_changes_what_is_below_the_group() { + let empty = || layer("Empty", [0, 0, 0, 0], [0; 4]); + let direct = [ + layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), + group_end(), + empty(), + adjustment("Invert", b"nvrt", &[]), + group("Folder", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + ]; + let (s, r) = open(&file(1, 1, &direct, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Under + Folder + Dodge"], "{r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[245, 235, 225, 255]], "{r}"); + assert!(!r["warnings"].to_string().contains("adjustment"), "{r}"); + // Inverted in the inner group, then posterized to 4 levels. + let nested = [ + layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), + group_end(), + group_end(), + empty(), + adjustment("Invert", b"nvrt", &[]), + group("Inner", b"pass"), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Folder", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + ]; + let (s, r) = open(&file(1, 1, &nested, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers.iter().map(|l| name(l)).collect::>(), ["Under + Folder + Dodge"], "{r}"); + assert_eq!(row_of(&s, &d.layers[0]), [[255, 255, 255, 255]], "{r}"); + assert!(!r["warnings"].to_string().contains("adjustment"), "{r}"); + // Nor does a group of such layers, in any mode, or a layer at 0 opacity: below them, directly + // or in the inner group, Invert and Posterize still change what is below the outer group. + let mut no_fill = layer("Clear", [0, 0, 1, 1], [0, 0, 0, 255]); + no_fill.blocks.push((*b"iOpa", vec![0])); + let photo = || layer("Photo", [0, 0, 1, 1], [0, 0, 255, 255]); + let below: [(&str, Vec); 5] = [ + ("empty group", vec![group_end(), empty(), group("Empty", b"norm")]), + ("empty pass-through group", vec![group_end(), empty(), group("Empty", b"pass")]), + ("0 opacity", vec![L { opacity: 0, ..layer("Clear", [0, 0, 1, 1], [0, 0, 0, 255]) }]), + ("0 fill in a group", vec![group_end(), no_fill, group("Empty", b"norm")]), + ("group clipped to an empty layer", vec![empty(), group_end(), photo(), L { clipped: true, ..group("Clipped", b"norm") }]), + ]; + for (what, nothing) in below { + let direct = [ + &[layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), group_end()][..], + ¬hing, + &[adjustment("Invert", b"nvrt", &[]), group("Folder", b"pass"), L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }], + ] + .concat(); + let (s, r) = open(&file(1, 1, &direct, 8, false, false), json!({})); + assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[245, 235, 225, 255]], "{what}: {r}"); + let nested = [ + &[layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), group_end(), group_end()][..], + ¬hing, + &[ + adjustment("Invert", b"nvrt", &[]), + group("Inner", b"pass"), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Folder", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + ], + ] + .concat(); + let (s, r) = open(&file(1, 1, &nested, 8, false, false), json!({})); + assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[255, 255, 255, 255]], "{what}: {r}"); + } +} + +/// Layers clipped to a layer at 0 fill, or to an adjustment layer, draw: an adjustment layer above +/// them in a pass-through group merges with them and is applied. +#[test] +fn an_adjustment_layer_over_clipped_layers_merges_with_them() { + let mut clear = layer("Base", [0, 0, 1, 1], [0, 0, 0, 255]); + clear.blocks.push((*b"iOpa", vec![0])); + let photo = || L { clipped: true, ..layer("Photo", [0, 0, 1, 1], [0, 0, 255, 255]) }; + let layers = [ + group_end(), + group_end(), + clear, + photo(), + adjustment("Invert", b"nvrt", &[]), + group("Folder", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + group("Outer", b"pass"), + ]; + let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + let merged = "layers in blend modes VectorCraft doesn't have (Linear Dodge) were merged with the layers below them"; + assert_eq!(r["warnings"], json!([merged]), "{r}"); + assert_eq!(row_of(&s, sublayer(&d.layers[0], "Dodge")), [[255, 255, 0, 255]], "{r}"); + // The same with a group at 0 fill as the base. + let mut clear_group = group("Base", b"norm"); + clear_group.blocks.push((*b"iOpa", vec![0])); + let layers = [ + group_end(), + group_end(), + group_end(), + layer("Black", [0, 0, 1, 1], [0, 0, 0, 255]), + clear_group, + photo(), + adjustment("Invert", b"nvrt", &[]), + group("Folder", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }, + group("Outer", b"pass"), + ]; + let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(r["warnings"], json!([merged]), "{r}"); + assert_eq!(row_of(&s, sublayer(&d.layers[0], "Dodge")), [[255, 255, 0, 255]], "{r}"); + // Clipped to an Invert layer, which isn't applied then, the photo shows over the canvas, and + // Posterize merges with it: the gray 100 posterizes to 85. + let layers = [ + group_end(), + group_end(), + adjustment("Invert", b"nvrt", &[]), + L { clipped: true, ..layer("Photo", [0, 0, 1, 1], [100, 100, 100, 255]) }, + group("Folder", b"pass"), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Outer", b"pass"), + ]; + let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(row_of(&s, sublayer(&d.layers[0], "Posterize")), [[85, 85, 85, 255]], "{r}"); +} + /// Invert, Threshold and Posterize data that can't be read is not applied, with a warning: a level /// out of range, data too short, or a second adjustment block on the layer. #[test] @@ -1523,6 +1688,25 @@ fn an_adjustment_merge_past_the_memory_allowed_isnt_applied() { assert!(warnings.iter().any(|w| w == "1 adjustment layer was not applied"), "{warnings:?}"); } +/// An adjustment layer whose layer mask is too large for the memory allowed isn't applied, merged +/// with the layers below it or clipped to one, and the file still opens with its layers. +#[test] +fn an_adjustment_mask_past_the_memory_allowed_isnt_applied() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + // The 100 × 100 mask takes more than 128 bytes; the 1-pixel layer below it doesn't. + let masked = |clipped: bool| L { clipped, mask: Some(([0, 0, 100, 100], 255, 0, vec![0; 10_000])), ..adjustment("Invert", b"nvrt", &[]) }; + for clipped in [false, true] { + let f = file(1, 1, &[layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), masked(clipped)], 8, false, false); + let (doc, warnings) = psdlayers::import(&f, false, 128, cms).unwrap_or_else(|e| panic!("{clipped}: {e}")).unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::>(), ["Under"], "{clipped}: {warnings:?}"); + assert_eq!(warnings, ["1 adjustment layer was not applied"], "{clipped}"); + // With the memory for it, the mask's black leaves the layer as it was. + let (doc, warnings) = psdlayers::import(&f, false, 1 << 20, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::>(), ["Under + Invert"], "{clipped}: {warnings:?}"); + assert!(warnings.is_empty(), "{clipped}: {warnings:?}"); + } +} + /// Damaged Invert, Threshold and Posterize layers, masked and clipped, open without a panic. #[test] fn damaged_adjustment_layers_never_panic() { diff --git a/docs/mcp.md b/docs/mcp.md index 5e4b1ddf55..2194a45351 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10916,12 +10916,13 @@ The rest are VectorCraft's own rules: encoded back to 0..255) is above the level (1 to 255) and black otherwise; Posterize maps each channel to the nearest of its 2 to 255 evenly spaced levels, the higher one on a tie. The adjusted color is composited over the color below in the layer's blend mode, at its opacity times its fill opacity, through its layer mask, and - transparency is kept. A hidden one is left out. One with nothing visible below it in its group changes nothing; in - a Pass Through group it changes what is below the group only when the group is merged, and is otherwise not + transparency is kept. A hidden one is left out. One with nothing visible below it in its group that draws (a layer + that stores no pixels or is at 0 opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such + layers) changes nothing, and so does one at 0 opacity or 0 fill; in a Pass Through group it changes what is below the group only when the group is merged, and is otherwise not applied. - Other adjustment layers, Invert, Threshold and Posterize layers that others are clipped to, that are clipped to another adjustment layer, whose data can't be read (a level out of range, too short, or two adjustment blocks on - one layer) or whose merge needs more memory than allowed, fill layers that store no pixels and whose fill isn't + one layer) or whose merge, its layer mask included, needs more memory than allowed, fill layers that store no pixels and whose fill isn't read, layer effects that are switched on, the other knockouts (top-level layers, clipped layers, layers that others are clipped to, Pass Through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) and vector masks are not applied; the `warnings` count them. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2f1aee44ba..b42ce17573 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2324,7 +2324,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Targa files (`.tga`, `.vda`, `.icb`, `.vst`) open, place linked or embedded, relink and update at their pixel size: color-mapped, true-color and black-and-white, raw or run-length encoded, in any of the four row orders. The image descriptor's attribute bits and the extension area's Attributes Type decide the transparency: a file with no attribute bits, or with attribute data the Attributes Type calls undefined, opens opaque; with one bit, a 16-bit true-color pixel takes that bit as its alpha, and a color-mapped pixel takes the bit of the 16-bit color map entry it indexes; premultiplied colors are divided by their alpha. Open and Place recognize a Targa file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a Targa file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/tests/links.rs`). - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the visible layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the visible layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill where it covers none of their painted pixels, isn't merged for the knockout), and adjustment layers other than Invert, Threshold and Posterize, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - - File › Open with a PSD or PSB file's layers as objects applies Invert, Threshold and Posterize adjustment layers (the `nvrt`, `thrs` and `post` blocks of the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/)): each is merged with the visible layers below it in its group, which it changes, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for adjustment layers; clipped to a layer, it changes only that layer and the layers clipped to it. Each adjustment works on the colors as [the help page](https://helpx.adobe.com/photoshop/desktop/adjust-color/color-effects-techniques/apply-special-color-effects-to-images.html) describes them. VectorCraft's own rules: each channel is taken as an 8-bit sRGB value; Invert turns `v` into `255 − v`; Threshold compares the Rec. 709 luminance of linear sRGB, encoded back to 0..255, with its level (1 to 255), white above it and black at or below it; Posterize maps each channel to the nearest of its 2 to 255 evenly spaced levels, the higher one on a tie; the adjusted color is composited over the color below in the layer's blend mode at its opacity and fill opacity, through its layer mask, and transparency is kept. A hidden one is left out; one with nothing visible below it in its group changes nothing, and in a pass-through group it changes what is below the group only when the group is merged; one that layers are clipped to, one clipped to another adjustment layer, one whose data can't be read (a level out of range, too short, or two adjustment blocks on one layer), and one whose merge needs more memory than allowed aren't applied and are counted in the warnings (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). + - File › Open with a PSD or PSB file's layers as objects applies Invert, Threshold and Posterize adjustment layers (the `nvrt`, `thrs` and `post` blocks of the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/)): each is merged with the visible layers below it in its group, which it changes, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for adjustment layers; clipped to a layer, it changes only that layer and the layers clipped to it. Each adjustment works on the colors as [the help page](https://helpx.adobe.com/photoshop/desktop/adjust-color/color-effects-techniques/apply-special-color-effects-to-images.html) describes them. VectorCraft's own rules: each channel is taken as an 8-bit sRGB value; Invert turns `v` into `255 − v`; Threshold compares the Rec. 709 luminance of linear sRGB, encoded back to 0..255, with its level (1 to 255), white above it and black at or below it; Posterize maps each channel to the nearest of its 2 to 255 evenly spaced levels, the higher one on a tie; the adjusted color is composited over the color below in the layer's blend mode at its opacity and fill opacity, through its layer mask, and transparency is kept. A hidden one is left out; one with nothing visible below it in its group that draws (a layer that stores no pixels or is at 0 opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such layers) changes nothing, and so does one at 0 opacity or 0 fill; in a pass-through group it changes what is below the group only when the group is merged; one that layers are clipped to, one clipped to another adjustment layer, one whose data can't be read (a level out of range, too short, or two adjustment blocks on one layer), and one whose merge, its layer mask included, needs more memory than allowed aren't applied and are counted in the warnings (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none; `links.update` leaves a distorted image's clipping as it is. When Placement Options do not clip the image, a clip group whose clipping path was changed in the document (an anchor or handle moved by a thousandth of a point or more, anchors added or removed, a subpath opened or closed, or its fill rule changed) and a clipping mask made in the document are kept: a new file that names no clipping path leaves the mask clipping the image, and the clip group of a new file that names one goes inside the mask. Files that name no clipping path come in as before. `links.unembed` keeps the clip group, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/dcs.rs`). - Import Slices: File › Open of a PSD or PSB file with slices, and File › Place of one without Link, bring its slices in as user slices, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded; PSD Import Options offers Import Slices for such a file. `document.open` and `file.place` take `importSlices`, and `document.psdInfo` counts the slices. The slices are read from image resource 1050 in version 6 and in the descriptor of versions 7 and 8, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it. VectorCraft's own rules: Import Slices applies to Convert Layers to Objects and to Flatten Layers to a Single Image alike, and makes the dialog ask for a file with fewer than two layers; placed slices move and scale with the art in the same undo step; each slice keeps its name, type, link, target, message, alternative text, cell text and background color; slices the file generated automatically, and slices wholly outside the canvas, are left out; slices that can't be read are left out with a warning while the art comes in; with Show Import Options off, a PSD file is placed with the PSD Import Options chosen last, and on, each PSD file of the place cursor asks for them (`crates/engine/src/cmd/fileio/tests_psdslices.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). From 0d272049445a08835527e63b364d553ba4b10b2b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 06:11:57 -0800 Subject: [PATCH 3/9] PSD import: keep clips and merges around adjustments that aren't applied - An adjustment layer's mask is checked against the memory allowed beside the canvases held while it is read (the merged canvas, the base's shape and the copies kept for pass-through groups). - A clipped adjustment layer whose mask is too large to read is left out without unclipping the layers clipped above it to the same base. - An adjustment layer in a pass-through group whose mask is too large to read is left out without stopping the merge of the layer above the group; its own merge with the layers below it still isn't made. - A layer whose stored pixels are all transparent draws nothing, so an adjustment layer above it in a pass-through group stays kept to change what is below the group. - A layer merged in a pass-through group for its blend mode or its knockout takes the adjustment layers kept below it with it, so an adjustment layer above that group in an outer pass-through group merges with it instead of being dropped. --- crates/engine/src/cmd/fileio/psdlayers.rs | 136 ++++++++++++++++-- .../engine/src/cmd/fileio/tests_psdlayers.rs | 101 +++++++++++++ docs/mcp.md | 6 +- docs/target-app-parity.md | 2 +- 4 files changed, 227 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cmd/fileio/psdlayers.rs b/crates/engine/src/cmd/fileio/psdlayers.rs index 5fc6916c5e..dae505e247 100644 --- a/crates/engine/src/cmd/fileio/psdlayers.rs +++ b/crates/engine/src/cmd/fileio/psdlayers.rs @@ -45,11 +45,14 @@ //! otherwise, and Posterize maps each channel to the nearest of its evenly spaced levels, the higher //! one on a tie. The adjusted color is composited over the color below in the layer's blend mode, //! at its opacity times its fill opacity, through its layer mask; transparency stays as it was. One -//! with nothing visible below it in its group that draws (a layer that stores no pixels or is at 0 +//! with nothing visible below it in its group that draws (a layer that stores no pixels, other than +//! a solid color fill drawn over the canvas, a layer whose pixels are all transparent, or one at 0 //! opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such layers) //! changes nothing; in a pass-through group it changes //! what is below the group when the group is merged, and otherwise isn't applied. One that layers -//! are clipped to, and one clipped to another adjustment layer, isn't applied. +//! are clipped to, and one clipped to another adjustment layer, isn't applied. One whose layer mask +//! needs more memory than allowed beside the canvases it would change isn't applied, and a clip, or +//! a merge for another layer, that it is part of goes on without it. //! //! Other adjustment layers, Invert, Threshold and Posterize data that can't be read (a level out of //! range, too short, or a second adjustment block on the layer), fill layers that store no pixels and @@ -969,6 +972,12 @@ struct Builder<'a, F> { blank_log: Vec, /// How many times a merge was counted as not made because it needed more memory than allowed. squeezed: usize, + /// The adjustment layer whose own merge with the layers below it is being made: a layer mask of + /// its too large to read stops that merge, where one of another adjustment layer drawn in it + /// leaves that one out. + adjusting: Option, + /// Whether each record's stored transparency is 0 everywhere, once [`Self::clear`] has read it. + clear: Vec>>, } impl [f32; 3]> Builder<'_, F> { @@ -1098,8 +1107,10 @@ impl [f32; 3]> Builder<'_, F> { } /// Does record `i`'s layer mask, switched on, fit the memory allowed for reading it with - /// [`Self::mask`]? `true` when it has none, and when its size is damaged (reading it says so). - fn mask_fits(&self, i: usize) -> Result { + /// [`Self::mask`] beside `live` bytes of canvases held while it is read, and the copies of what + /// is below the pass-through groups being merged? `true` when it has none, and when its size is + /// damaged (reading it says so). + fn mask_fits(&self, i: usize, live: u64) -> Result { let rec = self.record(i)?; let Some(m) = rec.mask.filter(|m| !m.disabled) else { return Ok(true) }; if !rec.channels.iter().any(|(c, _)| *c == -2) { @@ -1110,7 +1121,42 @@ impl [f32; 3]> Builder<'_, F> { if w > max_side || rows > max_side { return Ok(true); } - Ok(self.fits((row_bytes(w, self.h.depth) as u64 + w as u64).saturating_mul(rows as u64)).is_ok()) + let bytes = (row_bytes(w, self.h.depth) as u64 + w as u64).saturating_mul(rows as u64); + Ok(bytes.saturating_add(live) <= self.room()) + } + + /// Does record `i` store pixels that are all fully transparent, so that it paints nothing? + /// Its transparency is read once. `false` when it stores none, or has no transparency, or its + /// transparency can't be read within the memory allowed or is damaged (drawing it says so). + fn clear(&self, i: usize) -> Result { + if let Some(clear) = self.clear.get(i).and_then(Cell::get) { + return Ok(clear); + } + let rec = self.record(i)?; + let (w, rows) = rec.bounds.size(); + let max_side = if self.h.psb { 300_000 } else { 30_000 }; + let alpha = rec.channels.iter().find(|(c, _)| *c == -1).map(|(_, data)| data); + let clear = match alpha { + Some(data) if !rec.draws_nothing() && !rec.color_over_canvas() && w <= max_side && rows <= max_side => { + let (depth, row) = (self.h.depth, row_bytes(w, self.h.depth)); + let bytes = (row as u64).saturating_mul(rows as u64); + if bytes > self.room() { + false + } else { + self.spend(bytes)?; + match layer_channel(data, rows, row, self.h.psb, depth) { + Ok(plane) => (0..rows) + .all(|y| plane.get(y * row..(y + 1) * row).is_some_and(|r| (0..w).all(|x| byte(sample(r, x, depth, false)) == 0))), + Err(_) => false, + } + } + } + _ => false, + }; + if let Some(c) = self.clear.get(i) { + c.set(Some(clear)); + } + Ok(clear) } /// Multiply `c`'s transparency by record `i`'s layer mask. @@ -1229,9 +1275,12 @@ impl [f32; 3]> Builder<'_, F> { } // A clipped adjustment layer changes the merged canvas in place, through its layer mask. let adjust = self.adjustment(body)?; - // Its layer mask too large to read needs more memory than allowed. - if adjust.is_some() && !base_adjustment && !self.mask_fits(i)? { - return Ok(false); + // Its layer mask too large to read needs more memory than allowed: it isn't applied, and the + // layers clipped above it still clip to the base. + if adjust.is_some() && !base_adjustment && !self.mask_fits(i, 0)? { + self.squeezed += 1; + self.unadjust(i); + return Ok(true); } let layer = match adjust { Some(_) => Canvas::default(), @@ -1282,6 +1331,16 @@ impl [f32; 3]> Builder<'_, F> { self.unadjust(i); return Ok(true); } + // The mask is read beside the merged canvas and the base's shape. + let shape = match &u.clip { + Some(Clip::Shape(s)) => 4 * s.len() as u64, + _ => 0, + }; + if !self.mask_fits(i, (16 * c.px.len() as u64).saturating_add(shape))? { + self.squeezed += 1; + self.unadjust(i); + return Ok(true); + } let mask = self.mask(i, false)?; adjust_onto(c, a, blend, opacity, mask.as_ref(), i); u.name.push_str(" + "); @@ -1497,6 +1556,12 @@ impl [f32; 3]> Builder<'_, F> { continue; } let (clips, drawn) = self.base_draws(items, k)?; + // One in a mode VectorCraft lacks (an adjustment layer aside), or with a shallow knockout + // that cuts what is below it, is merged with the layers below it in the group, which + // takes the ones kept so far with them (see `merged`). + if (matches!(r.blend, Blend::Other(_)) && (children.is_some() || r.adjust().is_none())) || self.cuts(items, k, clips, drawn && draws)? { + records.clear(); + } // One that layers are clipped to isn't kept, and a pass-through group they are clipped to // is drawn alone (see `clip`). One at 0 opacity changes nothing (see `adjust_below`). let keeps = !clips && r.opacity * r.fill > 0.0 && (!draws || !records.is_empty()); @@ -1517,6 +1582,33 @@ impl [f32; 3]> Builder<'_, F> { Ok((records, draws)) } + /// Does item `k` of `items`, a pass-through group's layers, take a shallow knockout that is merged + /// with the layers below it (see [`Self::knocks`])? Only one that `clips` nothing, is in the + /// Normal mode over visible layers in the Normal mode back to the last one merged for its mode, + /// and where it and something below it draw (`draws`). + fn cuts(&self, items: &[Item], k: usize, clips: bool, draws: bool) -> Result { + let record = |item: &Item| match item { + Item::Layer(i) | Item::Group(i, _) => self.record(*i), + }; + let Some(r) = items.get(k).map(record).transpose()? else { return Ok(false) }; + let normal = Blend::Mode(BlendMode::Normal); + if r.knockout != 1 || clips || !draws || r.blend != normal { + return Ok(false); + } + for below in items.get(..k).unwrap_or_default().iter().rev() { + let b = record(below)?; + if b.hidden || b.clipped { + continue; + } + match b.blend { + Blend::Other(_) if matches!(below, Item::Group(..)) || b.adjust().is_none() => break, + blend if blend != normal => return Ok(false), + _ => {} + } + } + Ok(true) + } + /// Does anything in `items` draw: a visible layer or group that isn't clipped and draws (see /// [`Self::base_draws`])? fn draws(&self, items: &[Item]) -> Result { @@ -1567,7 +1659,7 @@ impl [f32; 3]> Builder<'_, F> { Ok(match item { Item::Layer(i) => { let r = self.record(*i)?; - (r, !r.draws_nothing()) + (r, !r.draws_nothing() && !self.clear(*i)?) } Item::Group(g, children) => (self.record(*g)?, self.draws(children)?), }) @@ -1732,9 +1824,9 @@ impl [f32; 3]> Builder<'_, F> { let mut below = false; for b in out.iter().filter(|b| b.visible && b.opacity > 0.0) { below |= match &b.body { - // An adjustment layer, a layer that draws nothing, or a group of such layers, has - // nothing to change. - Body::Layer(i) => !self.record(*i)?.draws_nothing(), + // An adjustment layer, a layer that draws nothing or whose pixels are all + // transparent, or a group of such layers, has nothing to change. + Body::Layer(i) => !self.record(*i)?.draws_nothing() && !self.clear(*i)?, Body::Group(_, items) => self.draws(items)?, // Clipped layers merged with a base that has no pixels have none either. Body::Merged(c) => c.px.iter().any(|p| p[3] > 0.0), @@ -1751,7 +1843,10 @@ impl [f32; 3]> Builder<'_, F> { } let saved = self.saved(); let outer = self.try_from_here(); - let made = self.merge_into(out, &u)?; + let adjusting = self.adjusting.replace(u.record); + let made = self.merge_into(out, &u); + self.adjusting = adjusting; + let made = made?; self.tried(outer, made)?; if !made { self.restore(saved)?; @@ -2018,8 +2113,17 @@ impl [f32; 3]> Builder<'_, F> { if let Some(a) = self.adjustment(&u.body)? { if let Some(c) = acc.as_mut() { let mask = match u.mask_of { - // A layer mask too large to read needs more memory than allowed. - Some(i) if !self.mask_fits(i)? => return Ok(false), + // A layer mask too large to read beside the canvas needs more memory than + // allowed: the adjustment isn't applied, and the rest of the merge goes on. + Some(i) if !self.mask_fits(i, 16 * c.px.len() as u64)? => { + // The adjustment's own merge isn't made then. + if self.adjusting == Some(u.record) { + return Ok(false); + } + self.squeezed += 1; + self.unadjust(u.record); + return Ok(true); + } Some(i) => self.mask(i, false)?, None => None, }; @@ -2454,6 +2558,8 @@ pub(super) fn import( laid_blank: vec![false; records.len()], blank_log: vec![], squeezed: 0, + adjusting: None, + clear: vec![Cell::new(None); records.len()], }; let layers = b.list(&items, Level::Top)?; // A drawing for a knockout or a clip leaves hidden layers out; those that came in anyway aren't. diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs index 8ebc3a9f24..cda458d2aa 100644 --- a/crates/engine/src/cmd/fileio/tests_psdlayers.rs +++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs @@ -1707,6 +1707,107 @@ fn an_adjustment_mask_past_the_memory_allowed_isnt_applied() { } } +/// An adjustment layer's mask is read beside the canvases it changes: a 100 × 1 mask fits 256 bytes +/// alone, but not beside a 6 × 1 canvas, so the layer isn't applied. With the memory for both, it is. +#[test] +fn an_adjustment_mask_counts_the_canvas_it_changes() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let masked = |clipped: bool| L { clipped, mask: Some(([0, 0, 1, 100], 255, 0, vec![255; 100])), ..adjustment("Invert", b"nvrt", &[]) }; + for clipped in [false, true] { + let f = file(6, 1, &[layer("Under", [0, 0, 1, 6], [10, 20, 30, 255]), masked(clipped)], 8, false, false); + let (doc, warnings) = psdlayers::import(&f, false, 256, cms).unwrap_or_else(|e| panic!("{clipped}: {e}")).unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::>(), ["Under"], "{clipped}: {warnings:?}"); + assert_eq!(warnings, ["1 adjustment layer was not applied"], "{clipped}"); + let (doc, warnings) = psdlayers::import(&f, false, 1 << 20, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::>(), ["Under + Invert"], "{clipped}: {warnings:?}"); + assert!(warnings.is_empty(), "{clipped}: {warnings:?}"); + } +} + +/// An adjustment layer whose mask is too large to read is left out without stopping the clip or the +/// merge around it: a layer clipped above it still clips to the base, and a layer in a mode +/// VectorCraft lacks above a pass-through group holding it still merges in its mode. +#[test] +fn an_adjustment_mask_too_large_leaves_the_clip_and_merge_around_it() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let masked = |clipped: bool| L { clipped, mask: Some(([0, 0, 100, 100], 255, 0, vec![255; 10_000])), ..adjustment("Invert", b"nvrt", &[]) }; + let layers = [layer("Base", [0, 0, 1, 1], [200, 0, 0, 255]), masked(true), L { clipped: true, ..layer("Photo", [0, 0, 1, 2], [0, 0, 255, 255]) }]; + let (doc, warnings) = psdlayers::import(&file(2, 1, &layers, 8, false, false), false, 128, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::>(), ["Base + Photo"], "{warnings:?}"); + assert_eq!(warnings, ["1 adjustment layer was not applied"]); + // Gray 100 under Linear Dodge's gray 20 gives gray 120. + let layers = [ + layer("Under", [0, 0, 1, 1], [100, 100, 100, 255]), + group_end(), + masked(false), + group("Folder", b"pass"), + L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [20, 20, 20, 255]) }, + ]; + let (doc, warnings) = psdlayers::import(&file(1, 1, &layers, 8, false, false), false, 128, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::>(), ["Under + Folder + Dodge"], "{warnings:?}"); + let merged = "layers in blend modes VectorCraft doesn't have (Linear Dodge) were merged with the layers below them"; + assert_eq!(warnings, ["1 adjustment layer was not applied", merged]); + let Some([c]) = doc.layers[0].children().map(Vec::as_slice) else { panic!("the merged layer holds one image") }; + let NodeKind::Image(img) = &c.kind else { panic!("the merged layer holds an image") }; + let px = craft_image_codecs::decode(&doc.images[&img.key].bytes).unwrap().to_rgba8(); + assert_eq!(px, [120, 120, 120, 255]); +} + +/// A layer merged in a pass-through group for its mode or its knockout takes the adjustment layers +/// kept below it with it: an adjustment layer above that group in an outer pass-through group then +/// merges with it, and the gray 100 posterizes to 85. +#[test] +fn an_adjustment_layer_above_a_group_whose_kept_ones_merged_is_applied() { + let tops = [ + ("Linear Dodge", vec![L { blend: b"lddg", ..layer("Top", [0, 0, 1, 1], [100, 100, 100, 255]) }]), + ("knockout", vec![layer("Photo", [0, 0, 1, 1], [50, 50, 50, 255]), knockout(layer("Top", [0, 0, 1, 1], [100, 100, 100, 255]), 1, 255)]), + ]; + for (what, top) in tops { + let layers = [ + &[group_end(), group_end(), adjustment("Invert", b"nvrt", &[])][..], + &top, + &[group("Inner", b"pass"), adjustment("Posterize", b"post", &[0, 4, 0, 0]), group("Folder", b"pass")], + ] + .concat(); + let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(row_of(&s, sublayer(&d.layers[0], "Posterize")), [[85, 85, 85, 255]], "{what}: {r}"); + assert!(r["warnings"].to_string().contains("1 adjustment layer was not applied"), "{what}: {r}"); + } +} + +/// A layer whose pixels are all transparent draws nothing: an adjustment layer above it in a +/// pass-through group, directly or in a pass-through group inside it, still changes what is below +/// the group. +#[test] +fn an_adjustment_layer_over_transparent_pixels_changes_what_is_below_the_group() { + let clear = || layer("Clear", [0, 0, 1, 1], [50, 50, 50, 0]); + let dodge = || L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 1], [0, 0, 0, 255]) }; + let direct = [ + layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), + group_end(), + clear(), + adjustment("Invert", b"nvrt", &[]), + group("Folder", b"pass"), + dodge(), + ]; + let (s, r) = open(&file(1, 1, &direct, 8, false, false), json!({})); + assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[245, 235, 225, 255]], "{r}"); + let nested = [ + layer("Under", [0, 0, 1, 1], [10, 20, 30, 255]), + group_end(), + group_end(), + clear(), + adjustment("Invert", b"nvrt", &[]), + group("Inner", b"pass"), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Folder", b"pass"), + dodge(), + ]; + let (s, r) = open(&file(1, 1, &nested, 8, false, false), json!({})); + assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[255, 255, 255, 255]], "{r}"); +} + /// Damaged Invert, Threshold and Posterize layers, masked and clipped, open without a panic. #[test] fn damaged_adjustment_layers_never_panic() { diff --git a/docs/mcp.md b/docs/mcp.md index 2194a45351..04ce0fe200 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10917,9 +10917,11 @@ The rest are VectorCraft's own rules: nearest of its 2 to 255 evenly spaced levels, the higher one on a tie. The adjusted color is composited over the color below in the layer's blend mode, at its opacity times its fill opacity, through its layer mask, and transparency is kept. A hidden one is left out. One with nothing visible below it in its group that draws (a layer - that stores no pixels or is at 0 opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such + that stores no pixels, other than a solid color fill drawn over the canvas, a layer whose pixels are all + transparent, or one at 0 opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such layers) changes nothing, and so does one at 0 opacity or 0 fill; in a Pass Through group it changes what is below the group only when the group is merged, and is otherwise not - applied. + applied. One whose layer mask needs more memory than allowed beside the canvases it would change is not applied, + and a clip, or a merge for another layer, that it is part of goes on without it. - Other adjustment layers, Invert, Threshold and Posterize layers that others are clipped to, that are clipped to another adjustment layer, whose data can't be read (a level out of range, too short, or two adjustment blocks on one layer) or whose merge, its layer mask included, needs more memory than allowed, fill layers that store no pixels and whose fill isn't diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b42ce17573..0046922018 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2324,7 +2324,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Targa files (`.tga`, `.vda`, `.icb`, `.vst`) open, place linked or embedded, relink and update at their pixel size: color-mapped, true-color and black-and-white, raw or run-length encoded, in any of the four row orders. The image descriptor's attribute bits and the extension area's Attributes Type decide the transparency: a file with no attribute bits, or with attribute data the Attributes Type calls undefined, opens opaque; with one bit, a 16-bit true-color pixel takes that bit as its alpha, and a color-mapped pixel takes the bit of the 16-bit color map entry it indexes; premultiplied colors are divided by their alpha. Open and Place recognize a Targa file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a Targa file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/tests/links.rs`). - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the visible layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the visible layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill where it covers none of their painted pixels, isn't merged for the knockout), and adjustment layers other than Invert, Threshold and Posterize, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - - File › Open with a PSD or PSB file's layers as objects applies Invert, Threshold and Posterize adjustment layers (the `nvrt`, `thrs` and `post` blocks of the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/)): each is merged with the visible layers below it in its group, which it changes, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for adjustment layers; clipped to a layer, it changes only that layer and the layers clipped to it. Each adjustment works on the colors as [the help page](https://helpx.adobe.com/photoshop/desktop/adjust-color/color-effects-techniques/apply-special-color-effects-to-images.html) describes them. VectorCraft's own rules: each channel is taken as an 8-bit sRGB value; Invert turns `v` into `255 − v`; Threshold compares the Rec. 709 luminance of linear sRGB, encoded back to 0..255, with its level (1 to 255), white above it and black at or below it; Posterize maps each channel to the nearest of its 2 to 255 evenly spaced levels, the higher one on a tie; the adjusted color is composited over the color below in the layer's blend mode at its opacity and fill opacity, through its layer mask, and transparency is kept. A hidden one is left out; one with nothing visible below it in its group that draws (a layer that stores no pixels or is at 0 opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such layers) changes nothing, and so does one at 0 opacity or 0 fill; in a pass-through group it changes what is below the group only when the group is merged; one that layers are clipped to, one clipped to another adjustment layer, one whose data can't be read (a level out of range, too short, or two adjustment blocks on one layer), and one whose merge, its layer mask included, needs more memory than allowed aren't applied and are counted in the warnings (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). + - File › Open with a PSD or PSB file's layers as objects applies Invert, Threshold and Posterize adjustment layers (the `nvrt`, `thrs` and `post` blocks of the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/)): each is merged with the visible layers below it in its group, which it changes, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for adjustment layers; clipped to a layer, it changes only that layer and the layers clipped to it. Each adjustment works on the colors as [the help page](https://helpx.adobe.com/photoshop/desktop/adjust-color/color-effects-techniques/apply-special-color-effects-to-images.html) describes them. VectorCraft's own rules: each channel is taken as an 8-bit sRGB value; Invert turns `v` into `255 − v`; Threshold compares the Rec. 709 luminance of linear sRGB, encoded back to 0..255, with its level (1 to 255), white above it and black at or below it; Posterize maps each channel to the nearest of its 2 to 255 evenly spaced levels, the higher one on a tie; the adjusted color is composited over the color below in the layer's blend mode at its opacity and fill opacity, through its layer mask, and transparency is kept. A hidden one is left out; one with nothing visible below it in its group that draws (a layer that stores no pixels, other than a solid color fill drawn over the canvas, a layer whose pixels are all transparent, or one at 0 opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such layers) changes nothing, and so does one at 0 opacity or 0 fill; in a pass-through group it changes what is below the group only when the group is merged; one that layers are clipped to, one clipped to another adjustment layer, one whose data can't be read (a level out of range, too short, or two adjustment blocks on one layer), and one whose merge, its layer mask included, needs more memory than allowed aren't applied and are counted in the warnings; a clip, or a merge for another layer, that one with a layer mask too large to read is part of goes on without it (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none; `links.update` leaves a distorted image's clipping as it is. When Placement Options do not clip the image, a clip group whose clipping path was changed in the document (an anchor or handle moved by a thousandth of a point or more, anchors added or removed, a subpath opened or closed, or its fill rule changed) and a clipping mask made in the document are kept: a new file that names no clipping path leaves the mask clipping the image, and the clip group of a new file that names one goes inside the mask. Files that name no clipping path come in as before. `links.unembed` keeps the clip group, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/dcs.rs`). - Import Slices: File › Open of a PSD or PSB file with slices, and File › Place of one without Link, bring its slices in as user slices, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded; PSD Import Options offers Import Slices for such a file. `document.open` and `file.place` take `importSlices`, and `document.psdInfo` counts the slices. The slices are read from image resource 1050 in version 6 and in the descriptor of versions 7 and 8, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it. VectorCraft's own rules: Import Slices applies to Convert Layers to Objects and to Flatten Layers to a Single Image alike, and makes the dialog ask for a file with fewer than two layers; placed slices move and scale with the art in the same undo step; each slice keeps its name, type, link, target, message, alternative text, cell text and background color; slices the file generated automatically, and slices wholly outside the canvas, are left out; slices that can't be read are left out with a warning while the art comes in; with Show Import Options off, a PSD file is placed with the PSD Import Options chosen last, and on, each PSD file of the place cursor asks for them (`crates/engine/src/cmd/fileio/tests_psdslices.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). From 9b6519382c7e1e1098bbbe9d57580943556a314f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 09:12:19 -0800 Subject: [PATCH 4/9] PSD import: layers their masks hide draw nothing A layer or group whose layer mask, switched on, hides all of it now counts as drawing nothing when the import decides what an adjustment layer changes. A layer with stored pixels is hidden when its mask is 0 over all of them. A group, an adjustment layer and a layer that stores no pixels are hidden only when the mask is 0 everywhere, the value outside it included. - An adjustment layer above such a layer or group in a pass-through group is kept to change what is below the group, instead of merging with pixels that never show. - A shallow knockout hidden by its mask merges nothing, so the adjustment layers kept below it in a pass-through group stay in the group's kept set: an adjustment layer above that group in an outer pass-through group is kept after them, and both change what is below. - A clipping base hidden by its mask draws nothing, its clipped layers included. Each mask is read once for this, only when it can hide all of the layer, and the read is not counted against the import's memory allowance, since the mask is read and counted again where it is drawn. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/fileio/psdlayers.rs | 68 +++++++++++++++++-- .../engine/src/cmd/fileio/tests_psdlayers.rs | 52 ++++++++++++++ docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 4 files changed, 116 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/fileio/psdlayers.rs b/crates/engine/src/cmd/fileio/psdlayers.rs index dae505e247..d6719d45ea 100644 --- a/crates/engine/src/cmd/fileio/psdlayers.rs +++ b/crates/engine/src/cmd/fileio/psdlayers.rs @@ -978,6 +978,8 @@ struct Builder<'a, F> { adjusting: Option, /// Whether each record's stored transparency is 0 everywhere, once [`Self::clear`] has read it. clear: Vec>>, + /// Whether each record's layer mask hides all of it, once [`Self::masked_out`] has read it. + masked_out: Vec>>, } impl [f32; 3]> Builder<'_, F> { @@ -1159,6 +1161,47 @@ impl [f32; 3]> Builder<'_, F> { Ok(clear) } + /// Does record `i` have a layer mask, switched on, that hides all of it? For a layer with stored + /// pixels, other than an adjustment layer, the mask is 0 over all of them; for a group, an + /// adjustment layer and a layer that stores no pixels, which can change pixels anywhere below + /// them, it is 0 everywhere, the value outside it included. A mask is read only when it can hide + /// all of it, once. `false` when it has none, or it can't be read within the memory allowed or + /// is damaged (drawing it says so). `group` says the record opens a group. + fn masked_out(&self, i: usize, group: bool) -> Result { + if let Some(out) = self.masked_out.get(i).and_then(Cell::get) { + return Ok(out); + } + let rec = self.record(i)?; + // Where it draws: a layer's stored pixels. + let area = (!group && !rec.stores_nothing() && !matches!(rec.content, Content::Adjustment(_))).then_some(rec.bounds); + let inside = + |b: Bounds, x: i64, y: i64| (i64::from(b.left)..i64::from(b.right)).contains(&x) && (i64::from(b.top)..i64::from(b.bottom)).contains(&y); + // With a value outside it other than 0, it hides all of it only when it covers all of `area`. + let can_hide = rec.mask.is_some_and(|m| { + let outside = if m.inverted { 255 - m.default } else { m.default }; + outside == 0 + || area.is_some_and(|a| m.bounds.left <= a.left && m.bounds.top <= a.top && a.right <= m.bounds.right && a.bottom <= m.bounds.bottom) + }); + let out = can_hide && self.has_mask(Some(i))? && self.mask_fits(i, 0)? && { + // This read isn't counted against the import's allowance: the mask is read again, and + // counted, where the layer is drawn or its opacity mask is made. + let spent = self.spent.get(); + let read = self.mask(i, false); + self.spent.set(spent); + match read { + // Its values outside `area` hide nothing of it. + Ok(Some((left, top, m, _))) => { + m.enumerate_pixels().all(|(x, y, p)| p.0[0] == 0 || area.is_some_and(|a| !inside(a, left + i64::from(x), top + i64::from(y)))) + } + _ => false, + } + }; + if let Some(c) = self.masked_out.get(i) { + c.set(Some(out)); + } + Ok(out) + } + /// Multiply `c`'s transparency by record `i`'s layer mask. fn apply_mask(&self, c: &mut Canvas, i: usize) -> Result<(), String> { let Some((left, top, m, default)) = self.mask(i, false)? else { return Ok(()) }; @@ -1627,11 +1670,15 @@ impl [f32; 3]> Builder<'_, F> { /// For item `k` of `items`, visible and not clipped: whether visible layers are clipped to it, /// and whether it draws, above 0 opacity: by its own pixels (a group's, those of its layers) /// above 0 fill, or by those of the layers clipped to it that draw, which show in its pixels at - /// any fill, or over the canvas when it is a layer that covers it without drawing. + /// any fill, or over the canvas when it is a layer that covers it without drawing and that its + /// layer mask doesn't hide all of. fn base_draws(&self, items: &[Item], k: usize) -> Result<(bool, bool), String> { let Some(item) = items.get(k) else { return Ok((false, false)) }; let (r, own) = self.pixels(item)?; - let covers = matches!(item, Item::Layer(_)) && r.covers_without_drawing(); + let covers = match item { + Item::Layer(i) => r.covers_without_drawing() && !self.masked_out(*i, false)?, + Item::Group(..) => false, + }; let (mut clips, mut clips_draw) = (false, false); for above in items.get(k + 1..).unwrap_or_default() { let c = match above { @@ -1654,14 +1701,14 @@ impl [f32; 3]> Builder<'_, F> { } /// `item`'s record, and whether it has pixels of its own: a layer that draws, or a group with - /// something in it that draws (see [`Self::draws`]). + /// something in it that draws (see [`Self::draws`]), that its layer mask doesn't hide all of. fn pixels(&self, item: &Item) -> Result<(&Record<'_>, bool), String> { Ok(match item { Item::Layer(i) => { let r = self.record(*i)?; - (r, !r.draws_nothing() && !self.clear(*i)?) + (r, !r.draws_nothing() && !self.clear(*i)? && !self.masked_out(*i, false)?) } - Item::Group(g, children) => (self.record(*g)?, self.draws(children)?), + Item::Group(g, children) => (self.record(*g)?, self.draws(children)? && !self.masked_out(*g, true)?), }) } @@ -1823,7 +1870,7 @@ impl [f32; 3]> Builder<'_, F> { } let mut below = false; for b in out.iter().filter(|b| b.visible && b.opacity > 0.0) { - below |= match &b.body { + let draws = match &b.body { // An adjustment layer, a layer that draws nothing or whose pixels are all // transparent, or a group of such layers, has nothing to change. Body::Layer(i) => !self.record(*i)?.draws_nothing() && !self.clear(*i)?, @@ -1831,6 +1878,14 @@ impl [f32; 3]> Builder<'_, F> { // Clipped layers merged with a base that has no pixels have none either. Body::Merged(c) => c.px.iter().any(|p| p[3] > 0.0), }; + // One whose layer mask hides all of it has nothing to change either. A base merged with + // the layers clipped to it isn't checked: its canvas may reach past the base's own pixels. + let hidden = |m: usize| match &b.body { + Body::Layer(_) => self.masked_out(m, false), + Body::Group(..) => self.masked_out(m, true), + Body::Merged(_) => Ok(false), + }; + below = below || (draws && !b.mask_of.map(hidden).transpose()?.unwrap_or(false)); } // Kept below it in the group, or in a pass-through group below it there. let pending = !self.pending(out, level)?.is_empty(); @@ -2560,6 +2615,7 @@ pub(super) fn import( squeezed: 0, adjusting: None, clear: vec![Cell::new(None); records.len()], + masked_out: vec![Cell::new(None); records.len()], }; let layers = b.list(&items, Level::Top)?; // A drawing for a knockout or a clip leaves hidden layers out; those that came in anyway aren't. diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs index cda458d2aa..bc66cb717c 100644 --- a/crates/engine/src/cmd/fileio/tests_psdlayers.rs +++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs @@ -1808,6 +1808,58 @@ fn an_adjustment_layer_over_transparent_pixels_changes_what_is_below_the_group() assert_eq!(row_of(&s, &s.doc().unwrap().doc.layers[0]), [[255, 255, 255, 255]], "{r}"); } +/// A layer or group whose layer mask hides all of it draws nothing: an adjustment layer above it in +/// a pass-through group still changes what is below the group, and a shallow knockout hidden that +/// way merges nothing, so the adjustment layers below it stay kept. +#[test] +fn an_adjustment_layer_over_layers_their_masks_hide_changes_what_is_below_the_group() { + let black = |l: L| L { mask: Some(([0, 0, 1, 2], 0, 0, vec![0, 0])), ..l }; + let under = || layer("Under", [0, 0, 1, 2], [10, 20, 30, 255]); + let dodge = || L { blend: b"lddg", ..layer("Dodge", [0, 0, 1, 2], [0, 0, 0, 255]) }; + let photo = || layer("Photo", [0, 0, 1, 2], [100, 100, 100, 255]); + let inverted = [[245, 235, 225, 255], [245, 235, 225, 255]]; + let masked_layer = [under(), group_end(), black(photo()), adjustment("Invert", b"nvrt", &[]), group("Folder", b"pass"), dodge()]; + // A mask over all of the layer's pixels hides it whatever its value outside them. + let white_outside = L { mask: Some(([0, 0, 1, 2], 255, 0, vec![0, 0])), ..photo() }; + let covered_layer = [under(), group_end(), white_outside, adjustment("Invert", b"nvrt", &[]), group("Folder", b"pass"), dodge()]; + let masked_group = [ + under(), + group_end(), + group_end(), + photo(), + black(group("Inner", b"norm")), + adjustment("Invert", b"nvrt", &[]), + group("Folder", b"pass"), + dodge(), + ]; + let knockout_cut = knockout(black(layer("Cut", [0, 0, 1, 1], [0, 0, 255, 255])), 1, 255); + let masked_knockout = [ + under(), + group_end(), + group_end(), + adjustment("Invert", b"nvrt", &[]), + layer("Photo", [0, 0, 1, 1], [100, 100, 100, 255]), + knockout_cut, + group("Inner", b"pass"), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Folder", b"pass"), + dodge(), + ]; + let cases = [ + ("layer", &masked_layer[..], inverted), + ("covered layer", &covered_layer[..], inverted), + ("group", &masked_group[..], inverted), + ("knockout", &masked_knockout[..], [[85, 85, 85, 255], [255, 255, 255, 255]]), + ]; + let rows = |layers: &[L]| { + let (s, _) = open(&file(2, 1, layers, 8, false, false), json!({})); + row_of(&s, &s.doc().unwrap().doc.layers[0]) + }; + let got: Vec<_> = cases.iter().map(|(what, layers, _)| (*what, rows(layers))).collect(); + let want: Vec<_> = cases.iter().map(|(what, _, want)| (*what, want.to_vec())).collect(); + assert_eq!(got, want); +} + /// Damaged Invert, Threshold and Posterize layers, masked and clipped, open without a panic. #[test] fn damaged_adjustment_layers_never_panic() { diff --git a/docs/mcp.md b/docs/mcp.md index 04ce0fe200..d1e8f49dd7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10919,7 +10919,7 @@ The rest are VectorCraft's own rules: transparency is kept. A hidden one is left out. One with nothing visible below it in its group that draws (a layer that stores no pixels, other than a solid color fill drawn over the canvas, a layer whose pixels are all transparent, or one at 0 opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such - layers) changes nothing, and so does one at 0 opacity or 0 fill; in a Pass Through group it changes what is below the group only when the group is merged, and is otherwise not + layers, nor a layer or group whose layer mask hides all of it) changes nothing, and so does one at 0 opacity or 0 fill; in a Pass Through group it changes what is below the group only when the group is merged, and is otherwise not applied. One whose layer mask needs more memory than allowed beside the canvases it would change is not applied, and a clip, or a merge for another layer, that it is part of goes on without it. - Other adjustment layers, Invert, Threshold and Posterize layers that others are clipped to, that are clipped to diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0046922018..ef92436720 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2324,7 +2324,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Targa files (`.tga`, `.vda`, `.icb`, `.vst`) open, place linked or embedded, relink and update at their pixel size: color-mapped, true-color and black-and-white, raw or run-length encoded, in any of the four row orders. The image descriptor's attribute bits and the extension area's Attributes Type decide the transparency: a file with no attribute bits, or with attribute data the Attributes Type calls undefined, opens opaque; with one bit, a 16-bit true-color pixel takes that bit as its alpha, and a color-mapped pixel takes the bit of the 16-bit color map entry it indexes; premultiplied colors are divided by their alpha. Open and Place recognize a Targa file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a Targa file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/tests/links.rs`). - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the visible layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the visible layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill where it covers none of their painted pixels, isn't merged for the knockout), and adjustment layers other than Invert, Threshold and Posterize, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - - File › Open with a PSD or PSB file's layers as objects applies Invert, Threshold and Posterize adjustment layers (the `nvrt`, `thrs` and `post` blocks of the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/)): each is merged with the visible layers below it in its group, which it changes, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for adjustment layers; clipped to a layer, it changes only that layer and the layers clipped to it. Each adjustment works on the colors as [the help page](https://helpx.adobe.com/photoshop/desktop/adjust-color/color-effects-techniques/apply-special-color-effects-to-images.html) describes them. VectorCraft's own rules: each channel is taken as an 8-bit sRGB value; Invert turns `v` into `255 − v`; Threshold compares the Rec. 709 luminance of linear sRGB, encoded back to 0..255, with its level (1 to 255), white above it and black at or below it; Posterize maps each channel to the nearest of its 2 to 255 evenly spaced levels, the higher one on a tie; the adjusted color is composited over the color below in the layer's blend mode at its opacity and fill opacity, through its layer mask, and transparency is kept. A hidden one is left out; one with nothing visible below it in its group that draws (a layer that stores no pixels, other than a solid color fill drawn over the canvas, a layer whose pixels are all transparent, or one at 0 opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such layers) changes nothing, and so does one at 0 opacity or 0 fill; in a pass-through group it changes what is below the group only when the group is merged; one that layers are clipped to, one clipped to another adjustment layer, one whose data can't be read (a level out of range, too short, or two adjustment blocks on one layer), and one whose merge, its layer mask included, needs more memory than allowed aren't applied and are counted in the warnings; a clip, or a merge for another layer, that one with a layer mask too large to read is part of goes on without it (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). + - File › Open with a PSD or PSB file's layers as objects applies Invert, Threshold and Posterize adjustment layers (the `nvrt`, `thrs` and `post` blocks of the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/)): each is merged with the visible layers below it in its group, which it changes, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for adjustment layers; clipped to a layer, it changes only that layer and the layers clipped to it. Each adjustment works on the colors as [the help page](https://helpx.adobe.com/photoshop/desktop/adjust-color/color-effects-techniques/apply-special-color-effects-to-images.html) describes them. VectorCraft's own rules: each channel is taken as an 8-bit sRGB value; Invert turns `v` into `255 − v`; Threshold compares the Rec. 709 luminance of linear sRGB, encoded back to 0..255, with its level (1 to 255), white above it and black at or below it; Posterize maps each channel to the nearest of its 2 to 255 evenly spaced levels, the higher one on a tie; the adjusted color is composited over the color below in the layer's blend mode at its opacity and fill opacity, through its layer mask, and transparency is kept. A hidden one is left out; one with nothing visible below it in its group that draws (a layer that stores no pixels, other than a solid color fill drawn over the canvas, a layer whose pixels are all transparent, or one at 0 opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such layers, nor a layer or group whose layer mask hides all of it) changes nothing, and so does one at 0 opacity or 0 fill; in a pass-through group it changes what is below the group only when the group is merged; one that layers are clipped to, one clipped to another adjustment layer, one whose data can't be read (a level out of range, too short, or two adjustment blocks on one layer), and one whose merge, its layer mask included, needs more memory than allowed aren't applied and are counted in the warnings; a clip, or a merge for another layer, that one with a layer mask too large to read is part of goes on without it (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none; `links.update` leaves a distorted image's clipping as it is. When Placement Options do not clip the image, a clip group whose clipping path was changed in the document (an anchor or handle moved by a thousandth of a point or more, anchors added or removed, a subpath opened or closed, or its fill rule changed) and a clipping mask made in the document are kept: a new file that names no clipping path leaves the mask clipping the image, and the clip group of a new file that names one goes inside the mask. Files that name no clipping path come in as before. `links.unembed` keeps the clip group, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/dcs.rs`). - Import Slices: File › Open of a PSD or PSB file with slices, and File › Place of one without Link, bring its slices in as user slices, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded; PSD Import Options offers Import Slices for such a file. `document.open` and `file.place` take `importSlices`, and `document.psdInfo` counts the slices. The slices are read from image resource 1050 in version 6 and in the descriptor of versions 7 and 8, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it. VectorCraft's own rules: Import Slices applies to Convert Layers to Objects and to Flatten Layers to a Single Image alike, and makes the dialog ask for a file with fewer than two layers; placed slices move and scale with the art in the same undo step; each slice keeps its name, type, link, target, message, alternative text, cell text and background color; slices the file generated automatically, and slices wholly outside the canvas, are left out; slices that can't be read are left out with a warning while the art comes in; with Show Import Options off, a PSD file is placed with the PSD Import Options chosen last, and on, each PSD file of the place cursor asks for them (`crates/engine/src/cmd/fileio/tests_psdslices.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). From 540711e1a5a82f7852c7b4a0629bd948061bf304 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 10:23:48 -0800 Subject: [PATCH 5/9] PSD import: masks that hide a layer's drawn pixels or a pass-through group hide all of it A layer's mask now hides all of it when it is 0 over every pixel that isn't fully transparent, so a shallow knockout whose mask and transparency leave nothing drawn no longer drops the adjustment layers kept below it. A pass-through group whose mask hides all of it no longer counts its layers as drawing, or its adjustment layers as kept, when deciding which adjustment layers above it change what is below the group. --- crates/engine/src/cmd/fileio/psdlayers.rs | 59 ++++++++++++++----- .../engine/src/cmd/fileio/tests_psdlayers.rs | 49 ++++++++++++++- 2 files changed, 93 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/fileio/psdlayers.rs b/crates/engine/src/cmd/fileio/psdlayers.rs index d6719d45ea..59ead541d6 100644 --- a/crates/engine/src/cmd/fileio/psdlayers.rs +++ b/crates/engine/src/cmd/fileio/psdlayers.rs @@ -1162,11 +1162,13 @@ impl [f32; 3]> Builder<'_, F> { } /// Does record `i` have a layer mask, switched on, that hides all of it? For a layer with stored - /// pixels, other than an adjustment layer, the mask is 0 over all of them; for a group, an - /// adjustment layer and a layer that stores no pixels, which can change pixels anywhere below - /// them, it is 0 everywhere, the value outside it included. A mask is read only when it can hide - /// all of it, once. `false` when it has none, or it can't be read within the memory allowed or - /// is damaged (drawing it says so). `group` says the record opens a group. + /// pixels, other than an adjustment layer, the mask is 0 over all of them that aren't fully + /// transparent (over all of them when their transparency can't be read within the memory + /// allowed); for a group, an adjustment layer and a layer that stores no pixels, which can + /// change pixels anywhere below them, it is 0 everywhere, the value outside it included. A mask + /// is read only when it can hide all of it, once. `false` when it has none, or it can't be read + /// within the memory allowed or is damaged (drawing it says so). `group` says the record opens + /// a group. fn masked_out(&self, i: usize, group: bool) -> Result { if let Some(out) = self.masked_out.get(i).and_then(Cell::get) { return Ok(out); @@ -1183,16 +1185,42 @@ impl [f32; 3]> Builder<'_, F> { || area.is_some_and(|a| m.bounds.left <= a.left && m.bounds.top <= a.top && a.right <= m.bounds.right && a.bottom <= m.bounds.bottom) }); let out = can_hide && self.has_mask(Some(i))? && self.mask_fits(i, 0)? && { - // This read isn't counted against the import's allowance: the mask is read again, and - // counted, where the layer is drawn or its opacity mask is made. + // Its transparency, when it stores one that can be read beside the mask. + let max_side = if self.h.psb { 300_000 } else { 30_000 }; + let (w, rows) = rec.bounds.size(); + let row = row_bytes(w, self.h.depth); + let alpha = match rec.channels.iter().find(|(c, _)| *c == -1) { + Some((_, data)) + if area.is_some() + && !rec.draws_nothing() + && !rec.color_over_canvas() + && w <= max_side + && rows <= max_side + && self.mask_fits(i, (row as u64).saturating_mul(rows as u64))? => + { + layer_channel(data, rows, row, self.h.psb, self.h.depth).ok() + } + _ => None, + }; + // Is its pixel at `x`, `y`, inside `area`, fully transparent? + let transparent = |x: i64, y: i64| { + alpha.as_ref().is_some_and(|plane| { + let (dx, dy) = ((x - i64::from(rec.bounds.left)) as usize, (y - i64::from(rec.bounds.top)) as usize); + plane.get(dy * row..(dy + 1) * row).is_some_and(|r| byte(sample(r, dx, self.h.depth, false)) == 0) + }) + }; + // These reads aren't counted against the import's allowance: the mask and the + // transparency are read again, and counted, where the layer is drawn or its opacity + // mask is made. let spent = self.spent.get(); let read = self.mask(i, false); self.spent.set(spent); match read { - // Its values outside `area` hide nothing of it. - Ok(Some((left, top, m, _))) => { - m.enumerate_pixels().all(|(x, y, p)| p.0[0] == 0 || area.is_some_and(|a| !inside(a, left + i64::from(x), top + i64::from(y)))) - } + // Its values outside `area`, and over its fully transparent pixels, hide nothing of it. + Ok(Some((left, top, m, _))) => m.enumerate_pixels().all(|(x, y, p)| { + let (x, y) = (left + i64::from(x), top + i64::from(y)); + p.0[0] == 0 || area.is_some_and(|a| !inside(a, x, y)) || transparent(x, y) + }), _ => false, } }; @@ -1564,7 +1592,7 @@ impl [f32; 3]> Builder<'_, F> { /// The records of the adjustment layers kept in `out` at `level` (in a pass-through group, to /// change what is below the group), those kept in the visible pass-through groups of `out` - /// included. + /// included, except groups whose layer mask hides all of them. fn pending(&self, out: &[Unit<'_>], level: Level) -> Result, String> { let mut records = vec![]; if level != Level::Pass { @@ -1574,7 +1602,9 @@ impl [f32; 3]> Builder<'_, F> { for u in out.iter().filter(|u| u.visible && u.opacity > 0.0) { if self.adjustment(&u.body)?.is_some() { records.push(u.record); - } else if let (Body::Group(_, items), Blend::Pass) = (&u.body, u.blend) { + } else if let (Body::Group(_, items), Blend::Pass) = (&u.body, u.blend) + && !u.mask_of.map(|g| self.masked_out(g, true)).transpose()?.unwrap_or(false) + { records.extend(self.leading(items)?.0); } } @@ -1614,7 +1644,8 @@ impl [f32; 3]> Builder<'_, F> { records.push(i); } } - Some(children) if r.blend == Blend::Pass && keeps => { + // A pass-through group whose layer mask hides all of it draws and changes nothing. + Some(children) if r.blend == Blend::Pass && keeps && !self.masked_out(i, true)? => { let (inner, inner_draws) = self.leading(children)?; records.extend(inner); draws |= inner_draws; diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs index bc66cb717c..4f1777c323 100644 --- a/crates/engine/src/cmd/fileio/tests_psdlayers.rs +++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs @@ -18,6 +18,8 @@ struct L { rect: [i32; 4], /// Red, green, blue and alpha, the same for every pixel. rgba: [u8; 4], + /// The alpha of each pixel, in place of `rgba`'s, stored raw. + alpha: Option>, blend: &'static [u8; 4], opacity: u8, clipped: bool, @@ -40,6 +42,7 @@ fn layer(name: &'static str, rect: [i32; 4], rgba: [u8; 4]) -> L { name, rect, rgba, + alpha: None, blend: b"norm", opacity: 255, clipped: false, @@ -151,6 +154,12 @@ fn layer_info(layers: &[L], depth: u16, rle: bool, psb: bool) -> Vec { .filter(|_| !l.bare) .map(|&(id, v)| (id, channel(v, w * h, w, depth, rle, psb, l.zip))) .collect(); + if let (Some(pixels), Some((_, d))) = (&l.alpha, channels.first_mut()) { + *d = vec![0, 0]; + for &p in pixels { + d.extend(std::iter::repeat_n(p, usize::from(depth / 8))); + } + } let mut mask = vec![]; if let Some(([mt, ml, mb, mr], default, flags, pixels)) = &l.mask { let mut d = vec![0, 0]; @@ -1810,7 +1819,9 @@ fn an_adjustment_layer_over_transparent_pixels_changes_what_is_below_the_group() /// A layer or group whose layer mask hides all of it draws nothing: an adjustment layer above it in /// a pass-through group still changes what is below the group, and a shallow knockout hidden that -/// way merges nothing, so the adjustment layers below it stay kept. +/// way merges nothing, so the adjustment layers below it stay kept. A layer's mask hides all of it +/// when it hides each pixel that isn't fully transparent. The layers in a pass-through group hidden +/// that way don't count as drawing below an adjustment layer above the group. #[test] fn an_adjustment_layer_over_layers_their_masks_hide_changes_what_is_below_the_group() { let black = |l: L| L { mask: Some(([0, 0, 1, 2], 0, 0, vec![0, 0])), ..l }; @@ -1845,11 +1856,47 @@ fn an_adjustment_layer_over_layers_their_masks_hide_changes_what_is_below_the_gr group("Folder", b"pass"), dodge(), ]; + // A knockout whose mask hides each pixel it doesn't leave transparent. + let half = L { alpha: Some(vec![255, 0]), mask: Some(([0, 0, 1, 2], 0, 0, vec![0, 255])), ..layer("Cut", [0, 0, 1, 2], [0, 0, 255, 255]) }; + let mut transparent_knockout = masked_knockout.clone(); + transparent_knockout[5] = knockout(half, 1, 255); + // A pass-through group its mask hides, below Invert in a pass-through group, with a layer drawn + // above that group, under Posterize. + let masked_pass = [ + under(), + group_end(), + group_end(), + group_end(), + photo(), + black(group("Hidden", b"pass")), + adjustment("Invert", b"nvrt", &[]), + group("Inner", b"pass"), + layer("Blue", [0, 0, 1, 1], [0, 0, 255, 255]), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Folder", b"pass"), + dodge(), + ]; + // Invert in a pass-through group its mask hides keeps nothing above that group: Posterize + // merges with the layer below it, as with no such group. + let masked_invert = [ + under(), + group_end(), + group_end(), + adjustment("Invert", b"nvrt", &[]), + black(group("Hidden", b"pass")), + layer("Blue", [0, 0, 1, 1], [0, 0, 255, 255]), + adjustment("Posterize", b"post", &[0, 4, 0, 0]), + group("Folder", b"pass"), + dodge(), + ]; let cases = [ ("layer", &masked_layer[..], inverted), ("covered layer", &covered_layer[..], inverted), ("group", &masked_group[..], inverted), ("knockout", &masked_knockout[..], [[85, 85, 85, 255], [255, 255, 255, 255]]), + ("transparent knockout", &transparent_knockout[..], [[85, 85, 85, 255], [255, 255, 255, 255]]), + ("pass-through group", &masked_pass[..], [[0, 0, 255, 255], [255, 255, 255, 255]]), + ("adjustment in a pass-through group", &masked_invert[..], [[0, 0, 255, 255], [10, 20, 30, 255]]), ]; let rows = |layers: &[L]| { let (s, _) = open(&file(2, 1, layers, 8, false, false), json!({})); From 3b7c10acc4fab5bfa037193479f1f02e83a9a33c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 10:56:48 -0800 Subject: [PATCH 6/9] PSD import: an adjustment layer in a nested group over drawn layers merges applied A pass-through group's adjustment layers count as kept to change what is below the outer pass-through group only when nothing below that group in the outer one draws, as for adjustment layers directly in the outer group. Before, a layer merged above them for its blend mode merged them applied but the import counted them as not applied. docs/mcp.md now says when a layer's mask hides all of it. --- crates/engine/src/cmd/fileio/psdlayers.rs | 53 ++++++++++++------- .../engine/src/cmd/fileio/tests_psdlayers.rs | 21 ++++++++ docs/mcp.md | 3 +- 3 files changed, 56 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/fileio/psdlayers.rs b/crates/engine/src/cmd/fileio/psdlayers.rs index 59ead541d6..75c303cc36 100644 --- a/crates/engine/src/cmd/fileio/psdlayers.rs +++ b/crates/engine/src/cmd/fileio/psdlayers.rs @@ -1592,9 +1592,10 @@ impl [f32; 3]> Builder<'_, F> { /// The records of the adjustment layers kept in `out` at `level` (in a pass-through group, to /// change what is below the group), those kept in the visible pass-through groups of `out` - /// included, except groups whose layer mask hides all of them. + /// included: from the first one with nothing that draws below it in `out`, as [`Self::leading`] + /// keeps them. A group whose layer mask hides all of it keeps none. fn pending(&self, out: &[Unit<'_>], level: Level) -> Result, String> { - let mut records = vec![]; + let (mut records, mut draws) = (vec![], false); if level != Level::Pass { return Ok(records); } @@ -1602,15 +1603,41 @@ impl [f32; 3]> Builder<'_, F> { for u in out.iter().filter(|u| u.visible && u.opacity > 0.0) { if self.adjustment(&u.body)?.is_some() { records.push(u.record); - } else if let (Body::Group(_, items), Blend::Pass) = (&u.body, u.blend) + continue; + } + if let (Body::Group(_, items), Blend::Pass) = (&u.body, u.blend) + && (!draws || !records.is_empty()) && !u.mask_of.map(|g| self.masked_out(g, true)).transpose()?.unwrap_or(false) { - records.extend(self.leading(items)?.0); + let (inner, inner_draws) = self.leading(items)?; + records.extend(inner); + draws |= inner_draws; + continue; } + draws = draws || self.unit_draws(u)?; } Ok(records) } + /// Does unit `u` draw? An adjustment layer, a layer that draws nothing or whose pixels are all + /// transparent, a group of such layers, and a unit whose layer mask hides all of it, don't. + fn unit_draws(&self, u: &Unit<'_>) -> Result { + let draws = match &u.body { + Body::Layer(i) => !self.record(*i)?.draws_nothing() && !self.clear(*i)?, + Body::Group(_, items) => self.draws(items)?, + // Clipped layers merged with a base that has no pixels have none either. + Body::Merged(c) => c.px.iter().any(|p| p[3] > 0.0), + }; + // A base merged with the layers clipped to it isn't checked: its canvas may reach past the + // base's own pixels. + let hidden = |m: usize| match &u.body { + Body::Layer(_) => self.masked_out(m, false), + Body::Group(..) => self.masked_out(m, true), + Body::Merged(_) => Ok(false), + }; + Ok(draws && !u.mask_of.map(hidden).transpose()?.unwrap_or(false)) + } + /// The adjustment layers the import applies that a pass-through group with the layers `items` /// keeps to change what is below it: from the first one with nothing that draws below it in the /// group (hidden and clipped layers, other adjustment layers, layers and groups at 0 opacity, and @@ -1899,24 +1926,10 @@ impl [f32; 3]> Builder<'_, F> { if u.opacity <= 0.0 { return Ok(()); } + // A unit that draws nothing has nothing to change. let mut below = false; for b in out.iter().filter(|b| b.visible && b.opacity > 0.0) { - let draws = match &b.body { - // An adjustment layer, a layer that draws nothing or whose pixels are all - // transparent, or a group of such layers, has nothing to change. - Body::Layer(i) => !self.record(*i)?.draws_nothing() && !self.clear(*i)?, - Body::Group(_, items) => self.draws(items)?, - // Clipped layers merged with a base that has no pixels have none either. - Body::Merged(c) => c.px.iter().any(|p| p[3] > 0.0), - }; - // One whose layer mask hides all of it has nothing to change either. A base merged with - // the layers clipped to it isn't checked: its canvas may reach past the base's own pixels. - let hidden = |m: usize| match &b.body { - Body::Layer(_) => self.masked_out(m, false), - Body::Group(..) => self.masked_out(m, true), - Body::Merged(_) => Ok(false), - }; - below = below || (draws && !b.mask_of.map(hidden).transpose()?.unwrap_or(false)); + below = below || self.unit_draws(b)?; } // Kept below it in the group, or in a pass-through group below it there. let pending = !self.pending(out, level)?.is_empty(); diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs index 4f1777c323..56322787da 100644 --- a/crates/engine/src/cmd/fileio/tests_psdlayers.rs +++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs @@ -1785,6 +1785,27 @@ fn an_adjustment_layer_above_a_group_whose_kept_ones_merged_is_applied() { } } +/// An adjustment layer in a pass-through group, over a layer drawn below that group in an outer +/// pass-through group, isn't kept to change what is below the outer group: a layer merged above +/// them for its mode merges it applied, and the import doesn't count it as not applied. The gray +/// 100 inverts to 155. +#[test] +fn an_adjustment_layer_in_a_group_over_a_drawn_layer_merges_applied() { + let layers = [ + group_end(), + layer("Photo", [0, 0, 1, 1], [100, 100, 100, 255]), + group_end(), + adjustment("Invert", b"nvrt", &[]), + group("Inner", b"pass"), + L { blend: b"lddg", ..layer("Top", [0, 0, 1, 1], [0, 0, 0, 255]) }, + group("Folder", b"pass"), + ]; + let (s, r) = open(&file(1, 1, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(row_of(&s, sublayer(&d.layers[0], "Top")), [[155, 155, 155, 255]], "{r}"); + assert!(!r["warnings"].to_string().contains("adjustment"), "{r}"); +} + /// A layer whose pixels are all transparent draws nothing: an adjustment layer above it in a /// pass-through group, directly or in a pass-through group inside it, still changes what is below /// the group. diff --git a/docs/mcp.md b/docs/mcp.md index d1e8f49dd7..504eab27ae 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10919,7 +10919,8 @@ The rest are VectorCraft's own rules: transparency is kept. A hidden one is left out. One with nothing visible below it in its group that draws (a layer that stores no pixels, other than a solid color fill drawn over the canvas, a layer whose pixels are all transparent, or one at 0 opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such - layers, nor a layer or group whose layer mask hides all of it) changes nothing, and so does one at 0 opacity or 0 fill; in a Pass Through group it changes what is below the group only when the group is merged, and is otherwise not + layers, nor a layer or group whose layer mask hides all of it, for a layer a mask of 0 over each of its pixels that + isn't fully transparent) changes nothing, and so does one at 0 opacity or 0 fill; in a Pass Through group it changes what is below the group only when the group is merged, and is otherwise not applied. One whose layer mask needs more memory than allowed beside the canvases it would change is not applied, and a clip, or a merge for another layer, that it is part of goes on without it. - Other adjustment layers, Invert, Threshold and Posterize layers that others are clipped to, that are clipped to From 365823add69ec4da79543861fd002d9f09977f77 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 11:52:13 -0800 Subject: [PATCH 7/9] PSD import: masks hide layers and groups by the pixels they draw A layer mask white outside its rectangle now hides a layer when the mask is 0 over every pixel the layer draws, even where the rectangle leaves fully transparent pixels out. A group's mask is checked the same way against the pixels of the group's layers, unless the group holds an adjustment layer or a fill that stores no pixels. A base merged with the layers clipped to it counts as drawing nothing when its mask hides the base. A check that was skipped for lack of memory is made again later instead of being kept. --- crates/engine/src/cmd/fileio/psdlayers.rs | 208 +++++++++++++----- .../engine/src/cmd/fileio/tests_psdlayers.rs | 68 +++++- 2 files changed, 208 insertions(+), 68 deletions(-) diff --git a/crates/engine/src/cmd/fileio/psdlayers.rs b/crates/engine/src/cmd/fileio/psdlayers.rs index 75c303cc36..75aadb1c01 100644 --- a/crates/engine/src/cmd/fileio/psdlayers.rs +++ b/crates/engine/src/cmd/fileio/psdlayers.rs @@ -585,6 +585,15 @@ enum Item { Group(usize, Vec), } +/// The layers of the group of record `g`, looked for in `items` and the groups inside them. +fn find_group(items: &[Item], g: usize) -> Option<&[Item]> { + items.iter().find_map(|item| match item { + Item::Group(i, children) if *i == g => Some(children.as_slice()), + Item::Group(_, children) => find_group(children, g), + Item::Layer(_) => None, + }) +} + fn tree(records: &[Record<'_>]) -> Result, String> { let mut stack: Vec> = vec![vec![]]; for (i, rec) in records.iter().enumerate() { @@ -913,6 +922,8 @@ impl Notes { struct Builder<'a, F> { h: &'a Header<'a>, records: &'a [Record<'a>], + /// The records as layers and groups (see [`tree`]). + tree: &'a [Item], /// Hidden layers come in, hidden. hidden: bool, max_alloc: u64, @@ -1129,7 +1140,8 @@ impl [f32; 3]> Builder<'_, F> { /// Does record `i` store pixels that are all fully transparent, so that it paints nothing? /// Its transparency is read once. `false` when it stores none, or has no transparency, or its - /// transparency can't be read within the memory allowed or is damaged (drawing it says so). + /// transparency can't be read within the memory allowed or is damaged (drawing it says so); one + /// that didn't fit the memory allowed is read again the next time. fn clear(&self, i: usize) -> Result { if let Some(clear) = self.clear.get(i).and_then(Cell::get) { return Ok(clear); @@ -1143,7 +1155,7 @@ impl [f32; 3]> Builder<'_, F> { let (depth, row) = (self.h.depth, row_bytes(w, self.h.depth)); let bytes = (row as u64).saturating_mul(rows as u64); if bytes > self.room() { - false + return Ok(false); } else { self.spend(bytes)?; match layer_channel(data, rows, row, self.h.psb, depth) { @@ -1161,75 +1173,155 @@ impl [f32; 3]> Builder<'_, F> { Ok(clear) } - /// Does record `i` have a layer mask, switched on, that hides all of it? For a layer with stored - /// pixels, other than an adjustment layer, the mask is 0 over all of them that aren't fully - /// transparent (over all of them when their transparency can't be read within the memory - /// allowed); for a group, an adjustment layer and a layer that stores no pixels, which can - /// change pixels anywhere below them, it is 0 everywhere, the value outside it included. A mask - /// is read only when it can hide all of it, once. `false` when it has none, or it can't be read - /// within the memory allowed or is damaged (drawing it says so). `group` says the record opens - /// a group. + /// Does record `i` have a layer mask, switched on, that hides all of it? The mask is 0 over every + /// pixel that isn't fully transparent of the layers whose stored pixels show where it draws: a + /// layer's own, and a group's those of its layers, in the groups inside it too (every pixel of a + /// layer whose transparency can't be read). For an adjustment layer, a layer that stores no + /// pixels and a group with one of those in it, which can change pixels anywhere below them, it + /// is 0 everywhere, the value outside it included. The mask is read once. `false` when it has + /// none, or it can't be read within the memory allowed or is damaged (drawing it says so); a + /// `false` that a read skipped for lack of memory decided is worked out again the next time. + /// `group` says the record opens a group. fn masked_out(&self, i: usize, group: bool) -> Result { if let Some(out) = self.masked_out.get(i).and_then(Cell::get) { return Ok(out); } let rec = self.record(i)?; - // Where it draws: a layer's stored pixels. - let area = (!group && !rec.stores_nothing() && !matches!(rec.content, Content::Adjustment(_))).then_some(rec.bounds); - let inside = - |b: Bounds, x: i64, y: i64| (i64::from(b.left)..i64::from(b.right)).contains(&x) && (i64::from(b.top)..i64::from(b.bottom)).contains(&y); - // With a value outside it other than 0, it hides all of it only when it covers all of `area`. - let can_hide = rec.mask.is_some_and(|m| { - let outside = if m.inverted { 255 - m.default } else { m.default }; - outside == 0 - || area.is_some_and(|a| m.bounds.left <= a.left && m.bounds.top <= a.top && a.right <= m.bounds.right && a.bottom <= m.bounds.bottom) - }); - let out = can_hide && self.has_mask(Some(i))? && self.mask_fits(i, 0)? && { - // Its transparency, when it stores one that can be read beside the mask. - let max_side = if self.h.psb { 300_000 } else { 30_000 }; - let (w, rows) = rec.bounds.size(); - let row = row_bytes(w, self.h.depth); - let alpha = match rec.channels.iter().find(|(c, _)| *c == -1) { - Some((_, data)) - if area.is_some() - && !rec.draws_nothing() - && !rec.color_over_canvas() - && w <= max_side - && rows <= max_side - && self.mask_fits(i, (row as u64).saturating_mul(rows as u64))? => - { - layer_channel(data, rows, row, self.h.psb, self.h.depth).ok() + // The layers whose stored pixels show where it draws, when they all do. + let layers = if group { + match find_group(self.tree, i) { + Some(items) => { + let mut layers = vec![]; + self.painters(items, &mut layers)?.then_some(layers) } - _ => None, - }; - // Is its pixel at `x`, `y`, inside `area`, fully transparent? - let transparent = |x: i64, y: i64| { - alpha.as_ref().is_some_and(|plane| { - let (dx, dy) = ((x - i64::from(rec.bounds.left)) as usize, (y - i64::from(rec.bounds.top)) as usize); - plane.get(dy * row..(dy + 1) * row).is_some_and(|r| byte(sample(r, dx, self.h.depth, false)) == 0) - }) - }; - // These reads aren't counted against the import's allowance: the mask and the - // transparency are read again, and counted, where the layer is drawn or its opacity - // mask is made. + None => None, + } + } else { + (!rec.stores_nothing() && !matches!(rec.content, Content::Adjustment(_))).then(|| vec![i]) + }; + let outside = rec.mask.map_or(0, |m| if m.inverted { 255 - m.default } else { m.default }); + // Whether a read skipped for lack of memory decided it. + let mut squeezed = false; + let out = if (layers.is_none() && outside != 0) || !self.has_mask(Some(i))? { + false + } else if !self.mask_fits(i, 0)? { + squeezed = true; + false + } else { + // Not counted against the import's allowance: the mask is read again, and counted, where + // the layer is drawn or its opacity mask is made. let spent = self.spent.get(); let read = self.mask(i, false); self.spent.set(spent); match read { - // Its values outside `area`, and over its fully transparent pixels, hide nothing of it. - Ok(Some((left, top, m, _))) => m.enumerate_pixels().all(|(x, y, p)| { - let (x, y) = (left + i64::from(x), top + i64::from(y)); - p.0[0] == 0 || area.is_some_and(|a| !inside(a, x, y)) || transparent(x, y) - }), - _ => false, + // 0 everywhere hides all of anything. + Ok(Some((_, _, m, 0))) if m.pixels().all(|p| p.0[0] == 0) => true, + Ok(Some(mask)) => match &layers { + Some(layers) => { + let mut hides = true; + for &l in layers { + if !self.hides(i, l, &mask, &mut squeezed)? { + hides = false; + break; + } + } + hides + } + None => false, + }, + Ok(None) => false, + Err(_) => { + squeezed = true; + false + } } }; - if let Some(c) = self.masked_out.get(i) { + if (out || !squeezed) + && let Some(c) = self.masked_out.get(i) + { c.set(Some(out)); } Ok(out) } + /// Push onto `out` the layers in `items` (in the groups inside them too) that store pixels. + /// `false` when one of them can change or draw pixels where it stores none: an adjustment layer, + /// or a fill that stores no pixels. + fn painters(&self, items: &[Item], out: &mut Vec) -> Result { + for item in items { + match item { + Item::Layer(l) => { + let r = self.record(*l)?; + if r.covers_without_drawing() || r.color_over_canvas() || matches!(r.content, Content::Adjustment(_)) { + return Ok(false); + } + if !r.stores_nothing() { + out.push(*l); + } + } + Item::Group(_, children) => { + if !self.painters(children, out)? { + return Ok(false); + } + } + } + } + Ok(true) + } + + /// Does `mask`, record `i`'s layer mask read with [`Self::mask`], hide every pixel of layer `l` + /// that isn't fully transparent? Every pixel counts when `l`'s transparency can't be read beside + /// the mask; `squeezed` is set when that is for lack of memory. + fn hides(&self, i: usize, l: usize, mask: &(i64, i64, image::GrayImage, u8), squeezed: &mut bool) -> Result { + let (left, top, m, outside) = mask; + let (left, top, outside) = (*left, *top, *outside); + let (right, bottom) = (left + i64::from(m.width()), top + i64::from(m.height())); + let rec = self.record(l)?; + let b = rec.bounds; + let (bl, bt, br, bb) = (i64::from(b.left), i64::from(b.top), i64::from(b.right), i64::from(b.bottom)); + let max_side = if self.h.psb { 300_000 } else { 30_000 }; + let (w, rows) = b.size(); + // The sides are checked first: the row's size could overflow otherwise. + let fits = w <= max_side && rows <= max_side; + let row = if fits { row_bytes(w, self.h.depth) } else { 0 }; + // Its transparency, when it stores one that can be read beside the mask. Not counted against + // the import's allowance: it is read again, and counted, where the layer is drawn. + let alpha = match rec.channels.iter().find(|(c, _)| *c == -1) { + Some((_, data)) if fits && !rec.draws_nothing() && !rec.color_over_canvas() => { + if self.mask_fits(i, (row as u64).saturating_mul(rows as u64))? { + layer_channel(data, rows, row, self.h.psb, self.h.depth).ok() + } else { + *squeezed = true; + None + } + } + _ => None, + }; + let within = left <= bl && top <= bt && br <= right && bb <= bottom; + if outside != 0 && !within && alpha.is_none() { + return Ok(false); + } + // Its pixels the mask's value outside it can show, or only those under the mask. + let (x0, y0, x1, y1) = if outside != 0 { (bl, bt, br, bb) } else { (bl.max(left), bt.max(top), br.min(right), bb.min(bottom)) }; + for y in y0..y1 { + let line = match &alpha { + Some(plane) => match plane.get((y - bt) as usize * row..((y - bt) as usize + 1) * row) { + Some(r) => Some(r), + None => return Ok(false), + }, + None => None, + }; + for x in x0..x1 { + let under = (left..right).contains(&x) && (top..bottom).contains(&y); + let v = if under { m.get_pixel((x - left) as u32, (y - top) as u32).0[0] } else { outside }; + if v != 0 && line.is_none_or(|r| byte(sample(r, (x - bl) as usize, self.h.depth, false)) != 0) { + return Ok(false); + } + } + } + Ok(true) + } + /// Multiply `c`'s transparency by record `i`'s layer mask. fn apply_mask(&self, c: &mut Canvas, i: usize) -> Result<(), String> { let Some((left, top, m, default)) = self.mask(i, false)? else { return Ok(()) }; @@ -1628,12 +1720,13 @@ impl [f32; 3]> Builder<'_, F> { // Clipped layers merged with a base that has no pixels have none either. Body::Merged(c) => c.px.iter().any(|p| p[3] > 0.0), }; - // A base merged with the layers clipped to it isn't checked: its canvas may reach past the - // base's own pixels. + // A base merged with the layers clipped to it draws within its own pixels, or, when it covers + // the canvas without drawing, anywhere: its mask hides all of it as it hides the base (see + // `base_draws`). let hidden = |m: usize| match &u.body { Body::Layer(_) => self.masked_out(m, false), Body::Group(..) => self.masked_out(m, true), - Body::Merged(_) => Ok(false), + Body::Merged(_) => self.masked_out(m, matches!(self.record(m)?.divider, 1 | 2)), }; Ok(draws && !u.mask_of.map(hidden).transpose()?.unwrap_or(false)) } @@ -2627,6 +2720,7 @@ pub(super) fn import( let mut b = Builder { h: &h, records: &records, + tree: &items, hidden, max_alloc, held: 0, diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs index 56322787da..46a8f5eb9f 100644 --- a/crates/engine/src/cmd/fileio/tests_psdlayers.rs +++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs @@ -99,10 +99,15 @@ fn predict(row: &[u8], depth: u16) -> Vec { } } -/// A channel of `n` samples of `v` (in 32 bits, `v` / 255 as a float) at `depth`, raw, zipped -/// (with prediction when `zip` is `Some(true)`) or PackBits rows of `width` when `rle`. +/// One sample of `v` at `depth` (in 32 bits, `v` / 255 as a float). +fn sample_of(v: u8, depth: u16) -> Vec { + if depth == 32 { (f32::from(v) / 255.0).to_be_bytes().to_vec() } else { vec![v; usize::from(depth / 8)] } +} + +/// A channel of `n` samples of `v` (see [`sample_of`]) at `depth`, raw, zipped (with prediction +/// when `zip` is `Some(true)`) or PackBits rows of `width` when `rle`. fn channel(v: u8, n: usize, width: usize, depth: u16, rle: bool, psb: bool, zip: Option) -> Vec { - let sample = if depth == 32 { (f32::from(v) / 255.0).to_be_bytes().to_vec() } else { vec![v; usize::from(depth / 8)] }; + let sample = sample_of(v, depth); let row: Vec = std::iter::repeat_n(sample.as_slice(), width).flatten().copied().collect(); if let Some(predicted) = zip { let rows = n.checked_div(width).unwrap_or(0); @@ -157,14 +162,14 @@ fn layer_info(layers: &[L], depth: u16, rle: bool, psb: bool) -> Vec { if let (Some(pixels), Some((_, d))) = (&l.alpha, channels.first_mut()) { *d = vec![0, 0]; for &p in pixels { - d.extend(std::iter::repeat_n(p, usize::from(depth / 8))); + d.extend(sample_of(p, depth)); } } let mut mask = vec![]; if let Some(([mt, ml, mb, mr], default, flags, pixels)) = &l.mask { let mut d = vec![0, 0]; for &p in pixels { - d.extend(std::iter::repeat_n(p, usize::from(depth / 8))); + d.extend(sample_of(p, depth)); } channels.push((-2, d)); for v in [mt, ml, mb, mr] { @@ -1841,8 +1846,10 @@ fn an_adjustment_layer_over_transparent_pixels_changes_what_is_below_the_group() /// A layer or group whose layer mask hides all of it draws nothing: an adjustment layer above it in /// a pass-through group still changes what is below the group, and a shallow knockout hidden that /// way merges nothing, so the adjustment layers below it stay kept. A layer's mask hides all of it -/// when it hides each pixel that isn't fully transparent. The layers in a pass-through group hidden -/// that way don't count as drawing below an adjustment layer above the group. +/// when it hides each of its pixels that isn't fully transparent, and a group's when it hides each +/// such pixel of the group's layers, whatever the mask's value elsewhere; a layer hidden that way +/// hides the layers clipped to it too. The layers in a pass-through group hidden that way don't +/// count as drawing below an adjustment layer above the group. #[test] fn an_adjustment_layer_over_layers_their_masks_hide_changes_what_is_below_the_group() { let black = |l: L| L { mask: Some(([0, 0, 1, 2], 0, 0, vec![0, 0])), ..l }; @@ -1892,7 +1899,7 @@ fn an_adjustment_layer_over_layers_their_masks_hide_changes_what_is_below_the_gr black(group("Hidden", b"pass")), adjustment("Invert", b"nvrt", &[]), group("Inner", b"pass"), - layer("Blue", [0, 0, 1, 1], [0, 0, 255, 255]), + layer("Blue", [0, 0, 1, 1], [0, 0, 100, 255]), adjustment("Posterize", b"post", &[0, 4, 0, 0]), group("Folder", b"pass"), dodge(), @@ -1905,19 +1912,58 @@ fn an_adjustment_layer_over_layers_their_masks_hide_changes_what_is_below_the_gr group_end(), adjustment("Invert", b"nvrt", &[]), black(group("Hidden", b"pass")), - layer("Blue", [0, 0, 1, 1], [0, 0, 255, 255]), + layer("Blue", [0, 0, 1, 1], [0, 0, 100, 255]), adjustment("Posterize", b"post", &[0, 4, 0, 0]), group("Folder", b"pass"), dodge(), ]; + // A mask over only the pixels that aren't fully transparent, white outside it. + let corner = |l: L| L { mask: Some(([0, 0, 1, 1], 255, 0, vec![0])), ..l }; + let half_photo = || L { alpha: Some(vec![255, 0]), ..photo() }; + let corner_layer = [under(), group_end(), corner(half_photo()), adjustment("Invert", b"nvrt", &[]), group("Folder", b"pass"), dodge()]; + let corner_group = [ + under(), + group_end(), + group_end(), + half_photo(), + corner(group("Inner", b"norm")), + adjustment("Invert", b"nvrt", &[]), + group("Folder", b"pass"), + dodge(), + ]; + // The same mask over a group with a pixel drawn outside it: the group draws there. + let drawn_group = [ + under(), + group_end(), + group_end(), + photo(), + corner(group("Inner", b"norm")), + adjustment("Invert", b"nvrt", &[]), + group("Folder", b"pass"), + dodge(), + ]; + // A layer its mask hides, with a layer clipped to it. + let clipped_base = [ + under(), + group_end(), + black(photo()), + L { clipped: true, ..layer("Red", [0, 0, 1, 2], [200, 0, 0, 255]) }, + adjustment("Invert", b"nvrt", &[]), + group("Folder", b"pass"), + dodge(), + ]; let cases = [ ("layer", &masked_layer[..], inverted), ("covered layer", &covered_layer[..], inverted), ("group", &masked_group[..], inverted), ("knockout", &masked_knockout[..], [[85, 85, 85, 255], [255, 255, 255, 255]]), ("transparent knockout", &transparent_knockout[..], [[85, 85, 85, 255], [255, 255, 255, 255]]), - ("pass-through group", &masked_pass[..], [[0, 0, 255, 255], [255, 255, 255, 255]]), - ("adjustment in a pass-through group", &masked_invert[..], [[0, 0, 255, 255], [10, 20, 30, 255]]), + ("pass-through group", &masked_pass[..], [[0, 0, 85, 255], [255, 255, 255, 255]]), + ("adjustment in a pass-through group", &masked_invert[..], [[0, 0, 85, 255], [10, 20, 30, 255]]), + ("layer covered where it draws", &corner_layer[..], inverted), + ("group covered where it draws", &corner_group[..], inverted), + ("group drawn outside its mask", &drawn_group[..], [[10, 20, 30, 255], [155, 155, 155, 255]]), + ("clipped base", &clipped_base[..], inverted), ]; let rows = |layers: &[L]| { let (s, _) = open(&file(2, 1, layers, 8, false, false), json!({})); From 91fd78e27a85884c36f6edcaeae5c464cb820802 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 12:33:10 -0800 Subject: [PATCH 8/9] PSD import: looking for drawn pixels takes nothing from the import's allowance Checking whether a layer's pixels are all fully transparent no longer counts its transparency against the memory allowed for the whole import. The layer is counted where it is drawn, so an import that fits no longer fails because the check counted the same pixels first. --- crates/engine/src/cmd/fileio/psdlayers.rs | 13 +++++++------ crates/engine/src/cmd/fileio/tests_psdlayers.rs | 6 ++++++ 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/fileio/psdlayers.rs b/crates/engine/src/cmd/fileio/psdlayers.rs index 75aadb1c01..67958a550b 100644 --- a/crates/engine/src/cmd/fileio/psdlayers.rs +++ b/crates/engine/src/cmd/fileio/psdlayers.rs @@ -1156,13 +1156,14 @@ impl [f32; 3]> Builder<'_, F> { let bytes = (row as u64).saturating_mul(rows as u64); if bytes > self.room() { return Ok(false); - } else { - self.spend(bytes)?; - match layer_channel(data, rows, row, self.h.psb, depth) { - Ok(plane) => (0..rows) - .all(|y| plane.get(y * row..(y + 1) * row).is_some_and(|r| (0..w).all(|x| byte(sample(r, x, depth, false)) == 0))), - Err(_) => false, + } + // Not counted against the import's allowance: the transparency is read again, and + // counted, where the layer is drawn. + match layer_channel(data, rows, row, self.h.psb, depth) { + Ok(plane) => { + (0..rows).all(|y| plane.get(y * row..(y + 1) * row).is_some_and(|r| (0..w).all(|x| byte(sample(r, x, depth, false)) == 0))) } + Err(_) => false, } } _ => false, diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs index 46a8f5eb9f..09acabbfa0 100644 --- a/crates/engine/src/cmd/fileio/tests_psdlayers.rs +++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs @@ -2247,6 +2247,12 @@ fn damaged_layers_never_panic() { assert!(psdlayers::import(&file(8, 8, &many[..16], 8, false, false), false, 512, cms).unwrap().is_some()); let e = psdlayers::import(&file(8, 8, &many, 8, false, false), false, 512, cms).err(); assert!(e.as_deref().is_some_and(|e| e.contains("take more memory to read than allowed")), "{e:?}"); + // Looking through those layers' transparency for pixels that draw, below an adjustment layer, + // takes nothing from the allowance. + let mut clear: Vec = (0..16).map(|_| layer("x", [0, 0, 8, 8], [1, 2, 3, 0])).collect(); + clear.push(adjustment("Invert", b"nvrt", &[])); + let opened = psdlayers::import(&file(8, 8, &clear, 8, false, false), false, 512, cms); + assert!(opened.as_ref().is_ok_and(Option::is_some), "{:?}", opened.err()); } /// A layer in a mode VectorCraft lacks above a pass-through group merges with the group's layers From fa3c5af490ad255d7fe45255688b19dc91c08de9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 12:37:12 -0800 Subject: [PATCH 9/9] Docs: when a group's mask, or a clipping base's, hides all of it on PSD import --- docs/mcp.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/mcp.md b/docs/mcp.md index 504eab27ae..b79832226d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10920,7 +10920,9 @@ The rest are VectorCraft's own rules: that stores no pixels, other than a solid color fill drawn over the canvas, a layer whose pixels are all transparent, or one at 0 opacity or 0 fill with nothing clipped to it doesn't, nor does a group of only such layers, nor a layer or group whose layer mask hides all of it, for a layer a mask of 0 over each of its pixels that - isn't fully transparent) changes nothing, and so does one at 0 opacity or 0 fill; in a Pass Through group it changes what is below the group only when the group is merged, and is otherwise not + isn't fully transparent, for a group the same over its layers' pixels, or a mask of 0 everywhere when it holds an + adjustment layer or a fill that stores no pixels, and for a layer with layers clipped to it the same as for the + layer) changes nothing, and so does one at 0 opacity or 0 fill; in a Pass Through group it changes what is below the group only when the group is merged, and is otherwise not applied. One whose layer mask needs more memory than allowed beside the canvases it would change is not applied, and a clip, or a merge for another layer, that it is part of goes on without it. - Other adjustment layers, Invert, Threshold and Posterize layers that others are clipped to, that are clipped to