Merge remote-tracking branch 'origin/main' into fix/12938-sharpen-protect-detail

This commit is contained in:
Sven Lafebre committed 2026-11-13 01:49:50 +01:00
commit c3d855ce4f
21 files changed
+1242 -55

No files matched your search

+249 -6
View File
@@ -63,7 +63,11 @@ pub fn sample_stops(stops: &[(f32, [f32; 4])], t: f32) -> [f32; 4] {
}
}
/// Composites `color(i)` over `area` of the surface with per-pixel coverage.
/// Composites `color(i)` over `area` of the surface with per-pixel coverage. Where the coverage is
/// zero, `rim(x, y)` (when given) is the strength of a bucket's transparent-seed fringe there: the
/// pixel takes the fill at coverage `rim × (1 − α)`, its own transparency (#11354 review; see
/// [`bucket_fill_inks`]). Lock Transparent Pixels and Clear ignore it.
#[allow(clippy::too_many_arguments)]
fn composite_area(
s: &mut Surface,
area: Rect,
@@ -72,6 +76,7 @@ fn composite_area(
color: impl Fn(i32, i32) -> [f32; 4] + Sync,
lock_transparency: bool,
inks: Option<[f32; 4]>,
rim: Option<&(dyn Fn(i32, i32) -> f32 + Sync)>,
) {
// Composite tile by tile (in parallel on native); tiles with zero coverage are left untouched,
// so their copy-on-write storage (and GPU residency) survives.
@@ -86,8 +91,12 @@ fn composite_area(
let mut enc = [0.0f32; 8];
for y in r.y0..r.y1 {
for x in r.x0..r.x1 {
let k = coverage(x, y);
if k <= 0.0 {
let mut k = coverage(x, y);
let on_rim = match rim {
Some(rim) if k <= 0.0 && !lock_transparency && matches!(mode, FillMode::Blend(_)) => rim(x, y),
_ => 0.0,
};
if k <= 0.0 && on_rim <= 0.0 {
continue;
}
if !any {
@@ -97,6 +106,13 @@ fn composite_area(
let i = ((y - r.y0) as usize * w + (x - r.x0) as usize) * n;
let px = &mut region[i..i + n];
let d = photocraft_raster::to_rgba(&fmt, px);
if k <= 0.0 {
// A rim pixel: only its transparency takes the fill, so opaque art stays as it is.
k = on_rim * (1.0 - d[3].clamp(0.0, 1.0));
if k.is_nan() || k <= 0.0 {
continue;
}
}
let o = match mode {
FillMode::Blend(m) if lock_transparency => blend::composite_atop(m, d, color(x, y), k),
FillMode::Blend(m) => blend::composite(m, d, color(x, y), k),
@@ -166,6 +182,7 @@ pub fn paint_gradient(
},
lock_transparency,
None,
None,
);
}
@@ -228,8 +245,20 @@ pub fn bucket_fill_inks(
}
let img = crate::selection::rgba8_image(s, area);
let Some(region) = crate::selection::wand_region(&img, area, seed, tolerance, contiguous, anti_alias) else { return false };
// Clicked on transparency with Anti-alias on: the wand's fringe gives the partly transparent
// pixels around the flood no coverage (their alpha is measured against the seed's 0), but the
// reference application fills each pixel 8-adjacent to the flood at coverage `1 − α`, so the
// soft rim a cleared selection leaves rises partly (α 187 → 205, 56 → 211, 3 → 252; the
// reference gives 204, 211, 253) and a black edge pixel of alpha 40 filled green becomes
// (0, 248, 0, 221) (#11311, #12528, #11354 review). Pixels further out stay as they are; with
// Anti-alias off nothing outside the flood changes.
let at_seed = usize::try_from(seed.1 - area.y0)
.ok()
.and_then(|y| y.checked_mul(area.width() as usize))
.and_then(|row| row.checked_add(usize::try_from(seed.0 - area.x0).ok()?));
let empty_seed = anti_alias && at_seed.and_then(|i| img.get(i)).is_some_and(|p| p[3] == 0);
drop(img);
bucket_fill_region_inks(s, &region, opacity, selection, lock_transparency, src, inks, mode);
fill_region(s, &region, opacity, selection, lock_transparency, src, inks, mode, empty_seed);
true
}
@@ -258,9 +287,55 @@ pub fn bucket_fill_region_inks(
inks: Option<[f32; 4]>,
mode: FillMode,
) {
// Composite only over the filled region's box.
fill_region(s, region, opacity, selection, lock_transparency, src, inks, mode, false);
}
/// [`bucket_fill_region_inks`]; with `rim`, the pixels 8-adjacent to the region's fully covered
/// pixels that the region itself leaves uncovered take the fill at coverage `1 − α` (see
/// [`composite_area`]). Fully covered pixels and pixels further out are filled as without it.
#[allow(clippy::too_many_arguments)]
fn fill_region(
s: &mut Surface,
region: &crate::selection::Region,
opacity: f32,
selection: Option<&Surface>,
lock_transparency: bool,
src: impl Fn(i32, i32) -> [f32; 4] + Sync,
inks: Option<[f32; 4]>,
mode: FillMode,
rim: bool,
) {
// Composite only over the filled region's box (with Anti-alias on it already holds the
// one-pixel ring around the flood).
let b = region.bbox;
composite_area(s, b, mode, |x, y| region.at(x, y) * opacity * selection.map_or(1.0, |m| m.sample_channel(x, y, 0)), src, lock_transparency, inks);
let strength = |x: i32, y: i32| opacity * selection.map_or(1.0, |m| m.sample_channel(x, y, 0));
// The ring is only ever read for an unlocked Blend fill (see composite_area), and it is
// empty when the region covers every pixel, so do not build it in those cases: on a large
// canvas it is a bool per pixel plus a full scan of the mask.
let use_rim = rim && !lock_transparency && matches!(mode, FillMode::Blend(_)) && region.mask.contains(&0);
let ring = if use_rim { rim_ring(region) } else { Vec::new() };
let on_ring = |x: i32, y: i32| {
let at = usize::try_from(y - b.y0).ok().zip(usize::try_from(x - b.x0).ok()).filter(|_| b.contains(x, y));
let hit = at.and_then(|(yy, xx)| yy.checked_mul(b.width() as usize)?.checked_add(xx)).and_then(|i| ring.get(i));
if hit == Some(&true) { strength(x, y) } else { 0.0 }
};
let rim: Option<&(dyn Fn(i32, i32) -> f32 + Sync)> = if use_rim { Some(&on_ring) } else { None };
composite_area(s, b, mode, |x, y| region.at(x, y) * strength(x, y), src, lock_transparency, inks, rim);
}
/// Over `region.bbox` (row-major): the pixels the region leaves uncovered that touch one of its
/// fully covered pixels, diagonals included.
fn rim_ring(region: &crate::selection::Region) -> Vec<bool> {
let (w, h) = (region.bbox.width() as usize, region.bbox.height() as usize);
let full = |x: usize, y: usize| y.checked_mul(w).and_then(|r| r.checked_add(x)).and_then(|i| region.mask.get(i)) == Some(&255);
let n = w.saturating_mul(h).min(region.mask.len());
(0..n)
.map(|i| {
let (x, y) = (i % w, i / w);
region.mask.get(i) == Some(&0)
&& (y.saturating_sub(1)..=(y + 1).min(h - 1)).any(|ny| (x.saturating_sub(1)..=(x + 1).min(w - 1)).any(|nx| (nx, ny) != (x, y) && full(nx, ny)))
})
.collect()
}
#[cfg(test)]
@@ -349,6 +424,174 @@ mod tests {
assert_eq!(s.rgba(-4, 4), [0.0; 4], "outside the region");
}
/// #11311: flooding transparency with anti-aliasing fills the empty part of the region's edge
/// pixels at the fill's opacity, so the edge is no semi-transparent ring; opaque pixels the
/// anti-aliasing reaches blend exactly as before.
#[test]
fn bucket_on_transparency_fills_the_edge_pixels_in_full() {
let a = Rect::new(0, 0, 8, 1);
let white = |_, _| [1.0, 1.0, 1.0, 1.0];
for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F] {
for (opaque, opacity) in [([1.0, 1.0, 1.0, 1.0], 1.0), ([1.0, 1.0, 1.0, 1.0], 0.5), ([1.0, 0.0, 0.0, 1.0], 1.0)] {
let mut s = Surface::new(fmt);
s.fill_rect(Rect::new(4, 0, 8, 1), &opaque);
// The same region filled without the rule: what the bucket used to do.
let mut before = s.clone();
let img = crate::selection::rgba8_image(&before, a);
let region = crate::selection::wand_region(&img, a, (1, 0), 0.0, true, true).unwrap();
bucket_fill_region_inks(&mut before, &region, opacity, None, false, white, None, FillMode::Blend(BlendMode::Normal));
assert!(bucket_fill_inks(&mut s, a, (1, 0), 0.0, true, true, opacity, None, false, white, None, FillMode::Blend(BlendMode::Normal)));
for x in 0..4 {
let p = s.rgba(x, 0);
assert!(p[..3].iter().all(|c| (c - 1.0).abs() < 1e-3) && (p[3] - opacity).abs() < 3e-3, "{fmt:?} {opaque:?} at {x}: {p:?}");
}
for x in 4..8 {
assert_eq!(s.rgba(x, 0), before.rgba(x, 0), "{fmt:?} {opaque:?} at {x}: opaque pixels blend as before");
}
assert!(s.rgba(4, 0)[3] > 0.999);
}
}
}
/// #11354 review: on a CMYK target, the edge pixels a transparent-seed bucket makes
/// opaque take the picked inks like the fully covered interior — their colour is the
/// fill alone. A partially transparent destination the fill touches keeps the blended
/// colour it already had, so its inks stay the conversion of that blend.
#[test]
fn bucket_on_transparency_writes_the_picked_cmyk_inks_at_the_edge() {
let a = Rect::new(0, 0, 8, 1);
let inks = [1.0f32, 0.0, 0.0, 0.0];
let rgb = photocraft_color::convert::cmyk_to_rgb(inks).map(|c| c.clamp(0.0, 1.0));
let src = |_, _| [rgb[0], rgb[1], rgb[2], 1.0];
let raw = |s: &Surface, x: i32| -> Vec<f32> { s.read_region(Rect::new(x, 0, x + 1, 1)).into_iter().take(4).collect() };
let is_inks = |got: &[f32]| got.iter().zip(inks).all(|(a, b)| (a - b).abs() < 0.02);
// Transparent run against opaque white: x=3 is the anti-aliased edge (coverage < 1).
let mut s = Surface::new(PixelFormat::CMYKA8);
s.fill_rect(Rect::new(4, 0, 8, 1), &[0.0, 0.0, 0.0, 0.0, 1.0]);
assert!(bucket_fill_inks(&mut s, a, (1, 0), 0.0, true, true, 1.0, None, false, src, Some(inks), FillMode::Blend(BlendMode::Normal)));
assert!(is_inks(&raw(&s, 1)), "fully covered: {:?}", raw(&s, 1));
assert!(is_inks(&raw(&s, 3)), "the made-opaque edge takes the picked inks: {:?}", raw(&s, 3));
// The edge pixel holds white at half alpha instead: the fill raises its alpha,
// but the colour is a blend, so the picked inks do not replace it.
let mut s = Surface::new(PixelFormat::CMYKA8);
s.fill_rect(Rect::new(3, 0, 4, 1), &[0.0, 0.0, 0.0, 0.0, 0.5]);
s.fill_rect(Rect::new(4, 0, 8, 1), &[0.0, 0.0, 0.0, 0.0, 1.0]);
assert!(bucket_fill_inks(&mut s, a, (1, 0), 0.0, true, true, 1.0, None, false, src, Some(inks), FillMode::Blend(BlendMode::Normal)));
let edge = s.rgba(3, 0);
assert!(edge[3] > 0.5, "the fill raised the partial pixel's alpha: {edge:?}");
assert!(!is_inks(&raw(&s, 3)), "a blended destination keeps its own encoding: {:?}", raw(&s, 3));
}
/// #11354 review: the soft rim a Clear leaves rises only partly. The reference application
/// takes rim alphas 187, 56 and 3 to 204, 211 and 253; the rule here, `α + (1 − α)²`, gives
/// 205, 211 and 252, each within one level of it (fit in PR #11354's review round). The rim pixel
/// sits on the bucket's anti-aliased fringe; the hole beside it fills in full and the opaque
/// art behind it is untouched by the rule.
#[test]
fn bucket_on_transparency_raises_the_cleared_rim_partly() {
let a = Rect::new(0, 0, 8, 1);
let white = |_, _| [1.0, 1.0, 1.0, 1.0];
let level = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as i32;
// (rim alpha after the Clear, the reference application's result, ours)
for (rim, reference, ours) in [(187, 204, 205), (56, 211, 211), (3, 253, 252)] {
for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F] {
let mut s = Surface::new(fmt);
// The cleared hole is [0, 0, 0, 0] (Clear zeroes its RGB), the rim straight white.
s.fill_rect(Rect::new(4, 0, 5, 1), &[1.0, 1.0, 1.0, rim as f32 / 255.0]);
s.fill_rect(Rect::new(5, 0, 8, 1), &[1.0, 1.0, 1.0, 1.0]);
let before = s.clone();
assert!(bucket_fill_inks(&mut s, a, (1, 0), 32.0, true, true, 1.0, None, false, white, None, FillMode::Blend(BlendMode::Normal)));
let p = s.rgba(4, 0);
assert_eq!(level(p[3]), ours, "{fmt:?}: rim {rim} -> {p:?}");
assert!((ours - reference).abs() <= 1, "rim {rim}: ours {ours}, reference {reference}");
assert!(p[..3].iter().all(|c| (c - 1.0).abs() < 1e-3), "{fmt:?}: the rim stays white: {p:?}");
for x in 0..4 {
assert_eq!(level(s.rgba(x, 0)[3]), 255, "{fmt:?} rim {rim}: the hole and its edge fill in full at {x}");
}
for x in 5..8 {
assert_eq!(s.rgba(x, 0), before.rgba(x, 0), "{fmt:?} rim {rim}: opaque art at {x}");
}
}
}
}
/// The rule is for a click on transparency only: from an opaque seed the fill is exactly the
/// wand region's own fill, fringe included.
#[test]
fn bucket_on_opaque_pixels_keeps_neighbouring_transparency() {
let a = Rect::new(0, 0, 8, 1);
let mut s = Surface::new(PixelFormat::RGBA8);
s.fill_rect(Rect::new(0, 0, 4, 1), &[1.0, 1.0, 1.0, 0.5]);
s.fill_rect(Rect::new(4, 0, 8, 1), &[1.0, 1.0, 1.0, 1.0]);
let mut plain = s.clone();
let img = crate::selection::rgba8_image(&plain, a);
let region = crate::selection::wand_region(&img, a, (6, 0), 0.0, true, true).unwrap();
bucket_fill_region_inks(&mut plain, &region, 1.0, None, false, |_, _| [1.0; 4], None, FillMode::Blend(BlendMode::Normal));
assert!(bucket_fill_inks(&mut s, a, (6, 0), 0.0, true, true, 1.0, None, false, |_, _| [1.0; 4], None, FillMode::Blend(BlendMode::Normal)));
for x in 0..8 {
assert_eq!(s.rgba(x, 0), plain.rgba(x, 0), "at {x}");
}
assert!((s.rgba(1, 0)[3] - 0.5).abs() < 0.01, "outside the region");
}
/// #12528 (reference application, transparent seed, Tolerance 32, Anti-alias on): a black
/// edge pixel bordering the filled area takes the green fill at coverage `1 − α`, so its
/// colour as well as its alpha follow the reference within two levels; with Anti-alias off it
/// stays as it was.
#[test]
fn bucket_on_transparency_blends_into_the_edge_at_its_transparency() {
let a = Rect::new(0, 0, 8, 1);
let green = |_, _| [0.0, 1.0, 0.0, 1.0];
let level = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as i32;
// (edge alpha, the reference application's result)
for (alpha, reference) in [(40, [0, 248, 0, 221]), (112, [0, 190, 0, 192]), (197, [0, 70, 0, 210]), (253, [0, 2, 0, 253])] {
for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F] {
for anti_alias in [true, false] {
let mut s = Surface::new(fmt);
s.fill_rect(Rect::new(4, 0, 5, 1), &[0.0, 0.0, 0.0, alpha as f32 / 255.0]);
s.fill_rect(Rect::new(5, 0, 8, 1), &[0.0, 0.0, 0.0, 1.0]);
let before = s.clone();
assert!(bucket_fill_inks(&mut s, a, (1, 0), 32.0, true, anti_alias, 1.0, None, false, green, None, FillMode::Blend(BlendMode::Normal)));
let got = s.rgba(4, 0).map(level);
if anti_alias {
assert!(got.iter().zip(reference).all(|(g, r)| (g - r).abs() <= 2), "{fmt:?} alpha {alpha}: {got:?}, reference {reference:?}");
} else {
assert_eq!(s.rgba(4, 0), before.rgba(4, 0), "{fmt:?} alpha {alpha}: Anti-alias off leaves the edge");
}
for x in 5..8 {
assert_eq!(s.rgba(x, 0), before.rgba(x, 0), "{fmt:?} alpha {alpha}: opaque art at {x}");
}
}
}
}
}
/// #11354 review (measured in the reference application with a 4 px feathered rim): only the
/// one-pixel ring 8-adjacent to the flood rises, diagonals included; pixels further out keep
/// their alpha exactly.
#[test]
fn bucket_on_transparency_raises_only_the_ring_next_to_the_flood() {
let a = Rect::new(0, 0, 7, 7);
let mut s = Surface::new(PixelFormat::RGBA8);
s.fill_rect(a, &[1.0, 1.0, 1.0, 100.0 / 255.0]);
s.fill_rect(Rect::new(3, 3, 4, 4), &[0.0; 4]);
let before = s.clone();
assert!(bucket_fill_inks(&mut s, a, (3, 3), 32.0, true, true, 1.0, None, false, |_, _| [1.0; 4], None, FillMode::Blend(BlendMode::Normal)));
for y in 0..7 {
for x in 0..7 {
let (p, was) = (s.rgba(x, y), before.rgba(x, y));
match ((x - 3).abs(), (y - 3).abs()) {
(0, 0) => assert!(p[3] > 0.999, "the flood at ({x},{y}): {p:?}"),
(dx, dy) if dx <= 1 && dy <= 1 => assert!(p[3] > was[3] + 0.1, "the ring at ({x},{y}) rises: {p:?}"),
_ => assert_eq!(p, was, "beyond the ring at ({x},{y})"),
}
}
}
}
/// The Paint Bucket's Mode: Multiply darkens what's there, Clear erases it (half at 50 %).
#[test]
fn bucket_mode_blends_or_clears() {
+12
View File
@@ -305,6 +305,18 @@ pub(crate) fn transform_doc_marks(doc: &mut Document, a: &Affine) {
}
}
/// Runs `f` (Image Size, Canvas Size, Image Rotation) and puts the count points back where they
/// were: they keep their document coordinates, also where they end up off the canvas, as in the
/// reference application (#11762). Other marks follow the map as `f` applies it.
pub(crate) fn keeping_count_points<R>(doc: &mut Document, f: impl FnOnce(&mut Document) -> R) -> R {
let saved: Vec<Vec<[f64; 2]>> = doc.measurement.count_groups.iter().map(|g| g.points.clone()).collect();
let r = f(doc);
for (g, points) in doc.measurement.count_groups.iter_mut().zip(saved) {
g.points = points;
}
r
}
/// Applies `a` to all non-pixel geometry of the document (layers and document marks).
pub(crate) fn transform_geometry(doc: &mut Document, a: &Affine) {
let dpi = doc.resolution_dpi;
+3 -1
View File
@@ -37,7 +37,7 @@ fn turn(s: &mut Session, label: &str, t: crate::canvas_geom::Turn) -> Result<Val
s.set_canvas_map(a, half.then(&a).then(&photocraft_geom::Affine::translate(-0.5, -0.5)));
}
s.edit(label, |doc, _| {
crate::canvas_geom::turn_canvas(doc, t);
crate::canvas_geom::keeping_count_points(doc, |doc| crate::canvas_geom::turn_canvas(doc, t));
Ok(())
})?;
Ok(Value::Null)
@@ -73,6 +73,8 @@ mod count_delete_group_tests;
mod count_history_names_tests;
#[cfg(test)]
mod count_record_label_tests;
#[cfg(test)]
mod count_resize_tests;
pub mod cutout_cmds;
pub mod distort_cmds;
pub mod document_preset_cmds;
+8 -1
View File
@@ -795,7 +795,14 @@ fn straighten(s: &mut Session, p: &Value) -> Result<Value> {
let (w0, h0) = (f64::from(d.size.width), f64::from(d.size.height));
compound(s, "Straighten", |s| {
if crop {
s.execute("image.rotation.arbitrary", json!({"angle": rot, "direction": "cw"}))?;
// Count points turn with the image here, since the crop after it moves them too.
// Called directly rather than through `execute`, so an untrusted session's gate is
// asked here, as dispatch would have asked it for the nested rotation.
let rotation = json!({"angle": rot, "direction": "cw"});
if let Some(gate) = s.authorize {
gate("image.rotation.arbitrary", &rotation)?;
}
crate::mode_cmds::rotate_arbitrary_with(s, &rotation, false)?;
let nd = doc(s)?;
let (cw, ch) = inscribed(w0, h0, rot.to_radians());
let (nw, nh) = (f64::from(nd.size.width), f64::from(nd.size.height));
+4
View File
@@ -45,6 +45,7 @@ mod steps_direct_adjustments;
mod steps_distort;
mod steps_doc;
mod steps_droplet;
mod steps_frame_section;
mod steps_gallery;
mod steps_gradient;
mod steps_image;
@@ -205,6 +206,9 @@ mod selection_tests;
#[cfg(test)]
mod render_tests;
#[cfg(test)]
mod frame_section_tests;
#[cfg(test)]
mod recorded_tools_tests;
+1
View File
@@ -856,6 +856,7 @@ pub(super) const EVENTS: &[Event] = &[
"image.calculations",
"type.convertToShape",
"type.createWorkPath",
super::steps_frame_section::COMMAND,
"layer.new.layer",
"layer.layerStyle.createLayer",
"layer.new.group",
@@ -0,0 +1,254 @@
//! #10723: Layer › New › Frame from Layers, recorded as a Make of class `framedGroupSection`
//! (`docs/atn.md`, "Recorded through the menus").
use super::*;
use photocraft_doc::{Layer, LayerId};
use photocraft_geom::Rect;
const FRAME: &str = "layer.new.frameFromLayers";
const SOURCE: &str = "_atnFrameSectionDescriptor";
/// `From`: the layer `name`, by name.
fn by_name(name: &str) -> D {
D::Reference(vec![ReferenceItem::Name { class: class("Lyr "), name: UnicodeString::new_nul(name) }])
}
/// The measured step, session ids included, built here independently of the converter.
fn recorded(from: D, name: &str) -> Descriptor {
Descriptor::new("null")
.with("null", D::Reference(vec![ReferenceItem::Class(class("framedGroupSection"))]))
.with("From", from)
.with("layerSectionStart", D::Integer(4))
.with("layerSectionEnd", D::Integer(5))
.with("Nm ", D::Text(UnicodeString::new_nul(name)))
}
/// `d` without the keys `drop`.
fn without(mut d: Descriptor, drop: &[&str]) -> Descriptor {
d.items.retain(|(k, _)| !drop.iter().any(|key| k.is(key)));
d
}
/// The step PhotoCraft writes: the measured keys without the session ids.
fn canonical(from: D, name: Option<&str>) -> Descriptor {
let d = without(recorded(from, name.unwrap_or("")), &["layerSectionStart", "layerSectionEnd"]);
if name.is_some() { d } else { without(d, &["Nm "]) }
}
/// The target layer, the `From` of a step recorded in PhotoCraft without a layer of its own.
fn target_layer() -> D {
D::Reference(vec![ReferenceItem::Enumerated { class: class("Lyr "), type_id: Id::new("Ordn"), value: Id::new("Trgt") }])
}
/// Load the Make steps holding `ds` as action "A" through `actions.load`.
fn load(ds: Vec<Descriptor>) -> (Session, Value) {
let items = ds.into_iter().map(|d| AtnItem { event: AtnEvent::Code(*b"Mk "), dictionary: b"Make".to_vec(), descriptor: Some(d), ..Default::default() });
let file = AtnFile {
name: UnicodeString::new_nul("Frames"),
actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items: items.collect(), ..Default::default() }],
..Default::default()
};
let mut s = Session::new();
let r = s.execute("actions.load", json!({"data": photocraft_paint::tile::b64_encode(&atn::write(&file).unwrap())})).unwrap();
(s, r)
}
/// The descriptor of the first step of action "A" as `actions.save` writes it.
fn saved(s: &mut Session) -> Option<Vec<u8>> {
let r = s.execute("actions.save", json!({"action": "A"})).unwrap();
assert_eq!(r["skipped"], json!([]), "{r}");
let mut items = atn::parse(&photocraft_paint::tile::b64_decode(r["data"].as_str().unwrap()).unwrap()).unwrap().actions.remove(0).items;
assert_eq!(items[0].event, AtnEvent::Code(*b"Mk "));
items.remove(0).descriptor.as_ref().map(Descriptor::to_bytes)
}
/// The descriptor a native Frame from Layers step with `p` saves as, if it saves.
fn exported(p: &Value) -> Option<Descriptor> {
export_item(FRAME, p, "S").and_then(|item| item.descriptor)
}
/// A 100 × 80 document with "Photo" (pixels at (10, 15)–(40, 45)) under "Other" (pixels at
/// (60, 5)–(90, 25)), "Other" selected.
fn two_layers(s: &mut Session) -> (LayerId, LayerId) {
s.execute("file.new", json!({"width": 100, "height": 80})).unwrap();
let mut add = |name: &str, r: Rect| {
s.edit(name, |doc, active| {
let fmt = doc.pixel_format();
let mut l = Layer::raster(name, fmt);
l.surface_mut().unwrap().fill_rect(r, &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0]));
let id = doc.insert_above(None, l);
*active = Some(id);
Ok(id)
})
.unwrap()
};
let photo = add("Photo", Rect::new(10, 15, 40, 45));
let other = add("Other", Rect::new(60, 5, 90, 25));
s.execute("layer.select", json!({"layer": other.0, "mode": "replace"})).unwrap();
(photo, other)
}
/// The frame layers named `name`, as (group id, frame `[x, y, w, h]`).
fn frames(s: &Session, name: &str) -> Vec<(LayerId, [f64; 4])> {
let doc = &s.active().unwrap().doc;
doc.walk()
.into_iter()
.filter(|(_, _, l)| l.name == name)
.filter_map(|(_, _, l)| l.frame.as_ref().map(|f| (l.id, [f.transform.m[4], f.transform.m[5], f.transform.m[0], f.transform.m[3]])))
.collect()
}
/// Recorded steps load with the exact layer and name and save back byte for byte: the measured
/// form, another key order, no session ids, no name, and the target-layer form.
#[test]
fn recorded_steps_load_and_save_back_unchanged() {
let mut reordered = recorded(by_name("Photo"), "Frame 1");
reordered.items.reverse();
let cases = [
(recorded(by_name("Photo"), "Frame 1"), json!({"layer": "Photo", "name": "Frame 1"})),
(reordered, json!({"layer": "Photo", "name": "Frame 1"})),
(without(recorded(by_name("Ébène"), "Cadre"), &["layerSectionStart", "layerSectionEnd"]), json!({"layer": "Ébène", "name": "Cadre"})),
(without(recorded(by_name("Photo"), ""), &["Nm "]), json!({"layer": "Photo"})),
(recorded(by_name("Photo"), ""), json!({"layer": "Photo", "name": ""})),
(canonical(target_layer(), Some("Frame 1")), json!({"name": "Frame 1"})),
];
for (d, params) in cases {
let (mut s, r) = load(vec![d.clone()]);
assert_eq!(r["unsupported"], json!([]), "{r}");
let (id, p) = &s.actions.list[0].steps[0];
let mut p = p.clone();
p.as_object_mut().unwrap().remove(SOURCE);
assert_eq!((id.as_str(), &p), (FRAME, &params));
assert_eq!(saved(&mut s), Some(d.to_bytes()));
}
}
/// A loaded step frames the layer it names, not the selected one: the frame fits that layer's
/// pixels, the other layer stays where it was, and one Undo takes the frame back.
#[test]
fn a_loaded_step_frames_the_named_layer_and_undoes() {
let (mut s, _) = load(vec![recorded(by_name("Photo"), "Frame 1")]);
let (photo, other) = two_layers(&mut s);
let played = s.execute("actions.play", json!({"action": "A"})).unwrap();
assert_eq!(played["ran"], 1, "{played}");
assert_eq!(frames(&s, "Frame 1").into_iter().map(|f| f.1).collect::<Vec<_>>(), vec![[10.0, 15.0, 30.0, 30.0]]);
let doc = &s.active().unwrap().doc;
assert!(doc.layer(photo).is_none(), "Photo went into the frame");
assert!(doc.layers.iter().any(|l| l.id == other), "Other stays a top-level layer");
s.execute("history.undo", json!({})).unwrap();
assert!(frames(&s, "Frame 1").is_empty());
let doc = &s.active().unwrap().doc;
assert!(doc.layers.iter().any(|l| l.id == photo) && doc.layers.iter().any(|l| l.id == other));
}
/// A step that names its layer plays with no layer selected: the command is admitted on the
/// named layer, not the (empty) selection.
#[test]
fn a_loaded_step_plays_with_no_layer_selected() {
let (mut s, _) = load(vec![recorded(by_name("Photo"), "Frame 1")]);
let (photo, other) = two_layers(&mut s);
s.execute("select.deselectLayers", json!({})).unwrap();
let played = s.execute("actions.play", json!({"action": "A"})).unwrap();
assert_eq!(played["ran"], 1, "{played}");
assert_eq!(frames(&s, "Frame 1").into_iter().map(|f| f.1).collect::<Vec<_>>(), vec![[10.0, 15.0, 30.0, 30.0]]);
// The frame took in Photo, not Other.
let doc = &s.active().unwrap().doc;
assert!(doc.layer(photo).is_none(), "Photo went into the frame");
assert!(doc.layers.iter().any(|l| l.id == other), "Other stays a top-level layer");
}
/// Without a layer of its own the command still frames the selected layers.
#[test]
fn without_a_layer_the_selected_layers_are_framed() {
let mut s = Session::new();
let (photo, other) = two_layers(&mut s);
s.execute(FRAME, json!({"name": "Frame 1"})).unwrap();
assert_eq!(frames(&s, "Frame 1").into_iter().map(|f| f.1).collect::<Vec<_>>(), vec![[60.0, 5.0, 30.0, 20.0]]);
let doc = &s.active().unwrap().doc;
assert!(doc.layer(other).is_none() && doc.layers.iter().any(|l| l.id == photo));
}
/// A step recorded in PhotoCraft writes the measured keys without the session ids: the layer by
/// name (the target layer without one) and `Nm ` for a name that isn't blank. It loads back to
/// the same settings.
#[test]
fn native_steps_save_the_measured_keys() {
for (p, d, back) in [
(json!({"layer": "Photo", "name": "Frame 1"}), canonical(by_name("Photo"), Some("Frame 1")), json!({"layer": "Photo", "name": "Frame 1"})),
(json!({"layer": "Photo"}), canonical(by_name("Photo"), None), json!({"layer": "Photo"})),
(json!({"name": "Frame 1"}), canonical(target_layer(), Some("Frame 1")), json!({"name": "Frame 1"})),
(json!({"name": " ", "layer": null}), canonical(target_layer(), None), json!({})),
(json!({}), canonical(target_layer(), None), json!({})),
] {
assert_eq!(exported(&p), Some(d.clone()), "{p}");
let (s, _) = load(vec![d]);
assert_eq!(s.actions.list[0].steps[0], (FRAME.to_string(), back), "{p}");
}
}
/// A native step the event can't hold is refused: a layer by id or selector, a name that isn't
/// text, or the group options the command passes on (colour, mode, opacity), which the step
/// doesn't record.
#[test]
fn settings_the_event_cannot_hold_are_refused() {
for p in [
json!({"layer": 3}),
json!({"layer": {"index": 2}}),
json!({"layer": {"background": true}}),
json!({"name": 4}),
json!({"name": "Frame 1", "color": "red"}),
json!({"mode": "multiply"}),
json!({"opacity": 50}),
json!({"name": "Frame 1", "width": 200}),
] {
assert!(exported(&p).is_none(), "{p}");
}
}
/// Any other form keeps the reference step: no `From`, another `From`, a repeated or extra key,
/// values of another type, or another `null`.
#[test]
fn other_forms_keep_the_photoshop_step() {
let measured = recorded(by_name("Photo"), "Frame 1");
let replaced = |key: &str, v: D| {
let mut d = measured.clone();
d.items.iter_mut().filter(|(k, _)| k.is(key)).for_each(|slot| slot.1 = v.clone());
d
};
let forms = [
without(measured.clone(), &["From"]),
replaced("From", D::Reference(vec![ReferenceItem::Index { class: class("Lyr "), index: 2 }])),
replaced("From", D::Reference(vec![ReferenceItem::Name { class: class("Chnl"), name: UnicodeString::new_nul("Photo") }])),
replaced("From", D::Reference(vec![ReferenceItem::Enumerated { class: class("Lyr "), type_id: Id::new("Ordn"), value: Id::new("Al ") }])),
replaced("From", D::Text(UnicodeString::new_nul("Photo"))),
replaced("Nm ", D::Integer(1)),
replaced("layerSectionEnd", D::Double(5.0)),
replaced("null", D::Reference(vec![ReferenceItem::Class(class("frame"))])),
measured.clone().with("Nm ", D::Text(UnicodeString::new_nul("Again"))),
measured.clone().with("From", by_name("Other")),
measured.clone().with("Wdth", D::UnitFloat { unit: PX, value: 200.0 }),
];
for d in forms {
let (mut s, r) = load(vec![d.clone()]);
assert_eq!(r["unsupported"].as_array().map(Vec::len), Some(1), "{d:?}");
assert_eq!(s.actions.list[0].steps[0].0, PHOTOSHOP_STEP, "{d:?}");
assert_eq!(saved(&mut s), Some(d.to_bytes()));
}
}
/// A loaded step whose layer or name was changed saves the new settings, not the stale
/// recording; one whose recording is damaged still saves its settings.
#[test]
fn changed_or_damaged_steps_save_their_settings() {
let (s, _) = load(vec![recorded(by_name("Photo"), "Frame 1")]);
let mut p = s.actions.list[0].steps[0].1.clone();
assert!(p.get(SOURCE).is_some(), "{p}");
p["layer"] = json!("Other");
assert_eq!(exported(&p), Some(canonical(by_name("Other"), Some("Frame 1"))));
p["layer"] = json!("Photo");
p["name"] = json!(" ");
assert_eq!(exported(&p), Some(canonical(by_name("Photo"), None)));
p["name"] = json!("Frame 1");
p[SOURCE] = json!("not base64!");
assert_eq!(exported(&p), Some(canonical(by_name("Photo"), Some("Frame 1"))));
}
@@ -0,0 +1,121 @@
//! Layer › New › Frame from Layers, recorded as a Make of class `framedGroupSection`, as
//! `docs/atn.md` ("Recorded through the menus") measures it (#10723): `From` = the layer **by
//! name**, `layerSectionStart`, `layerSectionEnd` (longs) and `Nm ` (text). The dialog's width
//! and height are not in the step.
//!
//! `layerSectionStart` and `layerSectionEnd` are ids of the recording session, so they are not
//! settings: a loaded step keeps them only inside its recorded descriptor.
use super::descriptors::{class_ref, desc, jstr, name_ref, target_ref, text};
use super::fields::{Mapped, step};
use super::{D, Descriptor, ReferenceItem, Value, json};
/// The native command the step plays as.
pub(super) const COMMAND: &str = "layer.new.frameFromLayers";
/// The recorded descriptor, kept when it differs from the one [`to`] would write (session ids,
/// key order), so a load and save keeps the step unchanged.
const SOURCE: &str = "_atnFrameSectionDescriptor";
/// The settings a step holds: the layer it frames (`None`: the selected layers) and the frame's
/// name (`None`: no `Nm `, so the frame takes the command's default name).
#[derive(Debug, PartialEq)]
struct Settings {
layer: Option<String>,
name: Option<String>,
}
/// Text without the trailing NUL the format may carry.
fn plain(t: &super::UnicodeString) -> Option<String> {
String::from_utf16(t.0.strip_suffix(&[0]).unwrap_or(&t.0)).ok()
}
/// `From`: a layer by name, or the target layer (`Lyr ` `Ordn.Trgt`), the form a step recorded
/// in PhotoCraft without a layer of its own writes.
fn source_layer(v: &D) -> Option<Option<String>> {
let D::Reference(r) = v else { return None };
match r.as_slice() {
[ReferenceItem::Name { class, name }] if class.class_id.is("Lyr ") => Some(Some(plain(name)?)),
[ReferenceItem::Enumerated { class, type_id, value }] if class.class_id.is("Lyr ") && type_id.is("Ordn") && value.is("Trgt") => Some(None),
_ => None,
}
}
/// The measured form only: `null` = class `framedGroupSection`, `From`, optional session ids
/// (longs) and an optional `Nm `, each key at most once and nothing else.
fn recorded(d: &Descriptor) -> Option<Settings> {
const KEYS: [&str; 5] = ["null", "From", "layerSectionStart", "layerSectionEnd", "Nm "];
let once = |key: &str| d.items.iter().filter(|(k, _)| k.is(key)).count() <= 1;
if d.items.iter().any(|(k, _)| !KEYS.iter().any(|key| k.is(key))) || !KEYS.iter().all(|key| once(key)) {
return None;
}
let section = matches!(d.get("null")?, D::Reference(r) if matches!(r.as_slice(), [ReferenceItem::Class(c)] if c.class_id.is("framedGroupSection")));
if !section || ["layerSectionStart", "layerSectionEnd"].iter().any(|key| d.get(key).is_some_and(|v| !matches!(v, D::Integer(_)))) {
return None;
}
let name = match d.get("Nm ") {
None => None,
Some(D::Text(t)) => Some(plain(t)?),
Some(_) => return None,
};
Some(Settings { layer: source_layer(d.get("From")?)?, name })
}
/// The descriptor a step recorded in PhotoCraft saves as: the measured keys without the session
/// ids, `Nm ` only for a name of the step's own (not blank).
fn canonical(settings: &Settings) -> Descriptor {
let from = settings.layer.as_deref().map_or_else(|| target_ref("Lyr "), |layer| name_ref("Lyr ", layer));
let d = desc("null").with("null", class_ref("framedGroupSection")).with("From", from);
match &settings.name {
Some(name) => d.with("Nm ", text(name)),
None => d,
}
}
/// Map the measured form; any other stays a complete kept step.
pub(super) fn from(d: &Descriptor) -> Mapped {
let Some(settings) = recorded(d) else { return Mapped::Unsupported { harmless: false } };
let mut p = json!({});
if let Some(layer) = &settings.layer {
p["layer"] = layer.as_str().into();
}
if let Some(name) = &settings.name {
p["name"] = name.as_str().into();
}
if *d != canonical(&settings) {
p[SOURCE] = photocraft_paint::tile::b64_encode(&d.to_bytes()).into();
}
step(COMMAND, p)
}
/// A native step the event holds: the selected layers or a layer by name, and a name. A layer by
/// id (meaningless in another document) and the group options the command passes on to the
/// group it frames (colour, mode, opacity) refuse export: the step records none of them.
fn native(p: &Value) -> Option<Settings> {
let m = p.as_object()?;
if m.keys().any(|key| !["layer", "name", SOURCE].contains(&key.as_str())) {
return None;
}
let layer = match m.get("layer") {
None | Some(Value::Null) => None,
Some(Value::String(layer)) => Some(layer.clone()),
Some(_) => return None,
};
let name = match m.get("name") {
None | Some(Value::Null) => None,
// A blank name is no name to the command either.
Some(Value::String(n)) => Some(n.clone()).filter(|n| !n.trim().is_empty()),
Some(_) => return None,
};
Some(Settings { layer, name })
}
/// Save the recorded descriptor while the step still frames the same layer with the same name,
/// otherwise the canonical form of the step's settings.
pub(super) fn to(p: &Value) -> Option<Descriptor> {
let settings = native(p)?;
let source = jstr(p, SOURCE)
.and_then(photocraft_paint::tile::b64_decode)
.and_then(|bytes| Descriptor::from_bytes(&bytes).ok())
.filter(|d| recorded(d).is_some_and(|r| r.layer == settings.layer && r.name.filter(|n| !n.trim().is_empty()) == settings.name));
Some(source.unwrap_or_else(|| canonical(&settings)))
}
+21 -8
View File
@@ -540,20 +540,30 @@ fn type_shape_descriptor() -> Descriptor {
desc("null").with("null", class_ref("contentLayer")).with("Usng", target_ref("textLayer"))
}
/// Make events another module maps: a type path, an artboard, a layer style or a frame,
/// tried in that order.
fn delegated_make_from(d: &Descriptor) -> Option<Mapped> {
let class = get_ref(d, "null").and_then(ref_class);
match class.as_deref() {
Some("Path") => return Some(super::steps_type_path::from(d)),
// Layer › New › Artboard and Artboard from Layers (#10723).
Some("artboardSection") => return Some(super::steps_artboard_section::from(d)),
_ => {}
}
if let Some(mapped) = super::steps_layer_style::create_from_descriptor(d) {
return Some(mapped);
}
// Layer › New › Frame from Layers (#10723).
(class.as_deref() == Some("framedGroupSection")).then(|| super::steps_frame_section::from(d))
}
/// Import Make events only when their geometry and options can be represented faithfully,
/// including the exact target-text-to-content-layer references.
pub(super) fn make_from(d: &Descriptor) -> Mapped {
if let Some(mapped) = super::steps_calculations::from_descriptor(d) {
return mapped;
}
if get_ref(d, "null").and_then(ref_class).as_deref() == Some("Path") {
return super::steps_type_path::from(d);
}
// Layer › New › Artboard and Artboard from Layers (#10723).
if get_ref(d, "null").and_then(ref_class).as_deref() == Some("artboardSection") {
return super::steps_artboard_section::from(d);
}
if let Some(mapped) = super::steps_layer_style::create_from_descriptor(d) {
if let Some(mapped) = delegated_make_from(d) {
return mapped;
}
if d.items == type_shape_descriptor().items {
@@ -727,6 +737,9 @@ pub(super) fn make_to(id: &str, p: &Value) -> Option<Descriptor> {
if id == super::steps_layer_style::CREATE {
return super::steps_layer_style::style_to(id, p);
}
if id == super::steps_frame_section::COMMAND {
return super::steps_frame_section::to(p);
}
if id == "type.convertToShape" {
return p.as_object().filter(|p| p.is_empty()).map(|_| type_shape_descriptor());
}
+1
View File
@@ -706,6 +706,7 @@ fn every_mapped_command_exports_and_imports_back() {
"rotationAdaptation":"none","scale":true,"mirror":false,"output":"new"}),
),
("edit.fade", json!({"opacity":50,"mode":"Multiply"})),
("layer.new.frameFromLayers", json!({"layer": "Photo", "name": "Frame 1"})),
("layer.linkLayers", json!({})),
("layer.new.artboard", json!({"rect": [10, 20, 100, 50], "name": "Hero"})),
("layer.new.artboardFromLayers", json!({"name": "Cards"})),
@@ -0,0 +1,94 @@
//! #11762: count points keep their document coordinates through Image Size, Canvas Size and Image
//! Rotation (right angles, flips and arbitrary), also off the new canvas; other marks still follow
//! the image, and Crop keeps today's behaviour.
use serde_json::{Value, json};
use crate::Session;
const POINT: [f64; 2] = [99.3, 99.7];
fn doc() -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 600, "height": 400})).unwrap();
s.execute("count.add", json!({"x": POINT[0], "y": POINT[1]})).unwrap();
s.execute("notes.add", json!({"x": 100, "y": 100})).unwrap();
s
}
fn count_point(s: &Session) -> [f64; 2] {
s.active().unwrap().doc.measurement.count_groups[0].points[0]
}
fn note(s: &Session) -> [f64; 2] {
s.active().unwrap().doc.notes[0].position
}
#[test]
fn count_points_keep_their_coordinates() {
// The note at [100, 100] on the 600×400 canvas, where each command moves it.
let steps: [(&str, Value, [f64; 2]); 8] = [
("image.imageSize", json!({"width": 300, "height": 200}), [50.0, 50.0]),
("image.canvasSize", json!({"width": 400, "height": 300, "anchor": "center"}), [0.0, 50.0]),
("image.imageRotation.90cw", json!({}), [300.0, 100.0]),
("image.imageRotation.90ccw", json!({}), [100.0, 500.0]),
("image.imageRotation.180", json!({}), [500.0, 300.0]),
("image.imageRotation.flipCanvasHorizontal", json!({}), [500.0, 100.0]),
("image.imageRotation.flipCanvasVertical", json!({}), [100.0, 300.0]),
("image.rotation.arbitrary", json!({"angle": 30}), [236.794_919_243_112_3, 136.897_459_621_556_2]),
];
for (cmd, p, moved) in steps {
let mut s = doc();
let before = note(&s);
s.execute(cmd, p).unwrap();
assert_eq!(count_point(&s), POINT, "{cmd}");
let n = note(&s);
assert!((n[0] - moved[0]).abs() < 1e-6 && (n[1] - moved[1]).abs() < 1e-6, "{cmd}: note at {n:?}, expected {moved:?}");
s.undo();
assert_eq!((count_point(&s), note(&s)), (POINT, before), "{cmd}: undo");
}
}
#[test]
fn all_three_in_a_row_leave_the_point_where_it_was() {
let mut s = doc();
s.execute("image.imageSize", json!({"width": 300, "height": 200})).unwrap();
s.execute("image.canvasSize", json!({"width": 400, "height": 300, "anchor": "center"})).unwrap();
s.execute("image.imageRotation.90cw", json!({})).unwrap();
assert_eq!(count_point(&s), POINT);
}
#[test]
fn crop_still_moves_count_points() {
let mut s = doc();
s.execute("image.crop", json!({"x": 50, "y": 50, "width": 300, "height": 200})).unwrap();
assert_ne!(count_point(&s), POINT, "not measured: Crop keeps today's behaviour");
}
#[test]
fn ruler_straighten_with_crop_moves_count_points_with_the_image() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 600, "height": 400})).unwrap();
s.execute("count.add", json!({"x": 250, "y": 150})).unwrap();
s.execute("notes.add", json!({"x": 250, "y": 150})).unwrap();
// Straighten Layer is off for the Background (#12033).
s.execute("layer.new.layer", json!({})).unwrap();
s.execute("image.analysis.rulerTool", json!({"start": [0, 0], "end": [100, 10]})).unwrap();
s.execute("image.analysis.straightenLayer", json!({"crop": true})).unwrap();
let (c, n) = (count_point(&s), note(&s));
assert!((c[0] - n[0]).abs() < 1e-6 && (c[1] - n[1]).abs() < 1e-6, "count {c:?} vs note {n:?}");
}
#[test]
fn ruler_straighten_with_crop_asks_the_gate_for_its_rotation() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 600, "height": 400})).unwrap();
// Straighten Layer is off for the Background (#12033).
s.execute("layer.new.layer", json!({})).unwrap();
s.execute("image.analysis.rulerTool", json!({"start": [0, 0], "end": [100, 10]})).unwrap();
let size = s.active().unwrap().doc.size;
s.authorize = Some(|id, _| if id == "image.rotation.arbitrary" { Err(crate::EngineError::Other("denied".into())) } else { Ok(()) });
assert!(s.execute("image.analysis.straightenLayer", json!({"crop": true})).is_err(), "the nested rotation is denied");
s.authorize = None;
assert_eq!(s.active().unwrap().doc.size, size, "nothing turned");
}
+71 -23
View File
@@ -727,11 +727,20 @@ pub(crate) fn kind_of(s: &Session, id: LayerId) -> Option<&'static str> {
})
}
fn has_vector_mask(s: &Session, id: LayerId, only: Option<&str>) -> bool {
only.is_none() && s.active().and_then(|d| d.doc.layer(id)).is_some_and(|l| l.vector_mask.is_some())
}
/// Whether `rasterize_one` has something to do for this layer.
fn has_rasterize_work(s: &Session, id: LayerId, only: Option<&str>) -> bool {
kind_of(s, id).is_some_and(|k| only.is_none_or(|o| o == k)) || has_vector_mask(s, id, only)
}
/// Rasterize one layer; `only` restricts it to one kind. Without `only` (Rasterize › Layer / All
/// Layers: "all vector data") a vector mask becomes a pixel mask too; layer effects stay live, as
/// in Photoshop (Rasterize › Layer Style bakes them). Returns false when there was nothing to do.
pub(crate) fn rasterize_one(s: &mut Session, id: LayerId, only: Option<&str>, key: &str) -> Result<bool> {
let vector_mask = only.is_none() && s.active().and_then(|d| d.doc.layer(id)).is_some_and(|l| l.vector_mask.is_some());
let vector_mask = has_vector_mask(s, id, only);
let content = rasterize_content(s, id, only, key)?;
if vector_mask {
s.execute("layer.rasterize.vectorMask", json!({"layer": id.0, "coalesce": key}))?;
@@ -800,36 +809,75 @@ fn rasterize_content(s: &mut Session, id: LayerId, only: Option<&str>, key: &str
/// rasterize"), every selected layer the command applies to, in one history step.
pub(crate) fn rasterize(s: &mut Session, p: &Value, only: Option<&'static str>) -> Result<Value> {
let ids = crate::layer_multi_cmds::targets(s, p)?;
let many = ids.len() > 1;
let key = step_key(s, "rasterize");
let mut done = Vec::new();
for id in ids {
if rasterize_one(s, id, only, &key)? {
done.push(id.0);
}
rasterize_layers(s, ids, only, rasterize_one)
}
/// The history label of a Rasterize step: the kind it was limited to, or plain "Rasterize".
fn rasterize_label(only: Option<&str>) -> &'static str {
match only {
Some("type") => "Rasterize Type",
Some("shape") => "Rasterize Shape",
Some("fill") => "Rasterize Fill Content",
Some("smart") => "Rasterize Smart Object",
_ => "Rasterize",
}
let Some(&first) = done.first() else {
return Err(EngineError::Other(match (only, many) {
(Some(k), false) => format!("the layer is not a {k} layer"),
(Some(k), true) => format!("none of the selected layers is a {k} layer"),
(None, false) => "the layer has nothing to rasterize".into(),
(None, true) => "none of the selected layers has anything to rasterize".into(),
}));
};
}
fn nothing_to_rasterize(only: Option<&str>, many: bool) -> EngineError {
EngineError::Other(match (only, many) {
(Some(k), false) => format!("the layer is not a {k} layer"),
(Some(k), true) => format!("none of the selected layers is a {k} layer"),
(None, false) => "the layer has nothing to rasterize".into(),
(None, true) => "none of the selected layers has anything to rasterize".into(),
})
}
/// Convert `ids` with `convert` as one history step; a layer that fails takes back the ones
/// converted before it (#4974).
fn rasterize_layers(
s: &mut Session,
ids: Vec<LayerId>,
only: Option<&str>,
convert: impl Fn(&mut Session, LayerId, Option<&str>, &str) -> Result<bool>,
) -> Result<Value> {
let many = ids.len() > 1;
// Refused before a step starts: a failed `compound` still moves the revision, and a command
// that changes nothing must leave it alone.
if !ids.iter().any(|&id| has_rasterize_work(s, id, only)) {
return Err(nothing_to_rasterize(only, many));
}
let key = step_key(s, "rasterize");
let (first, done) = crate::analysis_cmds::compound(s, rasterize_label(only), |s| {
let mut done = Vec::new();
for id in ids {
if convert(s, id, only, &key)? {
done.push(id.0);
}
}
let Some(&first) = done.first() else { return Err(nothing_to_rasterize(only, many)) };
Ok((first, done))
})?;
let active = s.active().and_then(|d| d.active_layer).map(|id| id.0).filter(|id| done.contains(id));
Ok(json!({"layer": active.unwrap_or(first), "layers": done}))
}
pub(crate) fn rasterize_all(s: &mut Session) -> Result<Value> {
let ids: Vec<LayerId> = s.active().map(|d| d.doc.walk().into_iter().map(|(_, _, l)| l.id).collect()).unwrap_or_default();
let key = step_key(s, "rasterizeAll");
let mut n = 0;
for id in ids {
// Every sub-step shares one history entry via the coalescing key.
if rasterize_one(s, id, None, &key)? {
n += 1;
}
let ids: Vec<LayerId> = ids.into_iter().filter(|&id| has_rasterize_work(s, id, None)).collect();
if ids.is_empty() {
return Ok(json!({"rasterized": 0}));
}
let key = step_key(s, "rasterizeAll");
let n = crate::analysis_cmds::compound(s, "Rasterize All Layers", |s| {
let mut n = 0;
for id in ids {
// Every sub-step shares one history entry via the coalescing key.
if rasterize_one(s, id, None, &key)? {
n += 1;
}
}
Ok(n)
})?;
Ok(json!({"rasterized": n}))
}
+52
View File
@@ -94,6 +94,10 @@ fn active(s: &Session) -> &Layer {
d.doc.layer(d.active_layer.unwrap()).unwrap()
}
fn layer_of(s: &Session, id: u64) -> &Layer {
doc(s).layer(LayerId(id)).unwrap()
}
fn pixel(s: &Session, x: i32, y: i32) -> Vec<f32> {
active(s).surface().unwrap().pixel(x, y)
}
@@ -1165,6 +1169,54 @@ fn rasterize_fill_and_all_in_one_step() {
assert!(doc(&s).walk().iter().all(|(_, _, l)| !matches!(l.content, LayerContent::Fill(_))));
}
/// #4974: Rasterize converts its layers as one step, so a layer that fails after another was
/// converted leaves the document, history, journal and dirty state as they were.
#[test]
fn a_later_layer_failing_takes_back_the_rasterized_ones() {
let mut s = session(8);
let a = s.execute("layer.newFillLayer.solidColor", json!({"color": "#00ff00"})).unwrap()["layer"].as_u64().unwrap();
let b = s.execute("layer.newFillLayer.solidColor", json!({"color": "#0000ff"})).unwrap()["layer"].as_u64().unwrap();
let st = s.active_mut().unwrap();
st.saved_revision = st.revision;
let before = s.active().unwrap().doc.clone();
let steps = s.active().unwrap().history.past_len();
let journal = s.journal.len();
let ids = vec![LayerId(a), LayerId(b)];
let r = rasterize_layers(&mut s, ids.clone(), None, |s, id, only, key| {
if id.0 == b { Err(EngineError::Other("second layer failed".into())) } else { rasterize_one(s, id, only, key) }
});
assert!(r.is_err());
assert!(matches!(layer_of(&s, a).content, LayerContent::Fill(_)));
assert!(matches!(layer_of(&s, b).content, LayerContent::Fill(_)));
assert!(std::sync::Arc::ptr_eq(&s.active().unwrap().doc, &before));
assert_eq!(s.active().unwrap().history.past_len(), steps);
assert!(!s.active().unwrap().history.can_redo());
assert_eq!(s.journal.len(), journal);
assert!(!s.active().unwrap().is_dirty());
// Without the failure both are converted in a single step.
rasterize_layers(&mut s, ids, None, rasterize_one).unwrap();
assert!(matches!(layer_of(&s, a).content, LayerContent::Raster(_)));
assert!(matches!(layer_of(&s, b).content, LayerContent::Raster(_)));
assert_eq!(s.active().unwrap().history.past_len(), steps + 1);
}
/// A refused Rasterize starts no step: the revision and the saved state do not move.
#[test]
fn rasterize_with_nothing_to_convert_changes_nothing() {
let mut s = session(8);
let st = s.active_mut().unwrap();
st.saved_revision = st.revision;
let (revision, steps) = (s.active().unwrap().revision, s.active().unwrap().history.past_len());
assert!(s.execute("layer.rasterize.layer", json!({})).is_err());
assert!(s.execute("layer.rasterize.type", json!({})).is_err());
assert_eq!(s.execute("layer.rasterize.allLayers", json!({})).unwrap()["rasterized"], 0);
assert_eq!(s.active().unwrap().revision, revision);
assert_eq!(s.active().unwrap().history.past_len(), steps);
assert!(!s.active().unwrap().is_dirty());
}
#[test]
fn rasterize_smart_object_layer() {
let mut s = session(8);
+8 -2
View File
@@ -135,8 +135,11 @@ fn new_frame(s: &mut Session, p: &Value) -> Result<Value> {
Ok(result)
}
fn frame_from_layers(s: &mut Session, p: &Value) -> Result<Value> {
// A `layer` of its own (a recorded step names its layer) is what the grouping below takes
// in, so the frame fits that layer, not whatever is selected.
let explicit = crate::commands::explicit_layer(s, p)?;
let st = s.active().ok_or(EngineError::NoDocument)?;
let ids = st.selected_layers();
let ids = explicit.map_or_else(|| st.selected_layers(), |id| vec![id]);
let bounds = ids
.iter()
.filter_map(|id| st.doc.layer(*id))
@@ -359,7 +362,10 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
new_frame,
),
CommandSpec { menu: &["Layer", "New"], ..spec("layer.new.frameFromLayers", "Frame from Layers", r#"{name?:str}"#, has_layer, frame_from_layers) },
CommandSpec {
menu: &["Layer", "New"],
..spec("layer.new.frameFromLayers", "Frame from Layers", r#"{"layer":id?,"name":str?}"#, has_layer, frame_from_layers)
},
spec("layer.frame.set", "Frame Properties", r#"{"layer":id?,"transform":[a,b,c,d,x,y]?,"stroke":object|null?,"name":str?}"#, has_doc, set),
CommandSpec { journal: false, ..spec("layer.frame.info", "Frame Info", r#"{"layer":id?}"#, has_doc, query) },
spec("layer.frame.convert", "Convert to Frame", r#"{"layer":id?,"name":str?,"width":px?,"height":px?}"#, has_doc, convert),
+3 -3
View File
@@ -318,7 +318,7 @@ fn image_size(s: &mut Session, p: &Value) -> Result<Value> {
Method::Automatic if nw > ow || nh > oh => Resample::PreserveDetails,
Method::Automatic => Resample::BicubicSharper,
};
resample_doc_with_styles(doc, "image.imageSize", nw, nh, filter, scale_styles)
crate::canvas_geom::keeping_count_points(doc, |doc| resample_doc_with_styles(doc, "image.imageSize", nw, nh, filter, scale_styles))
})?;
// The size the document has now: without resampling `width`/`height` are ignored (#1815).
let size = s.active().ok_or(EngineError::NoDocument)?.doc.size;
@@ -714,7 +714,7 @@ fn canvas_size(s: &mut Session, p: &Value) -> Result<Value> {
let ext = extension_color(s, p);
s.set_sampler_map(photocraft_geom::Affine::translate(f64::from(dx), f64::from(dy)));
s.edit("Canvas Size", |doc, _| {
translate_doc(doc, "image.canvasSize", dx, dy)?;
crate::canvas_geom::keeping_count_points(doc, |doc| translate_doc(doc, "image.canvasSize", dx, dy))?;
doc.size = Size::new(nw, nh);
if nw > ow as u32 || nh > oh as u32 {
drop_fill_caches(&mut doc.layers);
@@ -1049,7 +1049,7 @@ fn rotated_crop(s: &mut Session, r: Rect, angle: f64, delete: bool, content_awar
Ok(())
})?;
}
crate::mode_cmds::rotate_arbitrary(s, &json!({"angle": angle, "direction": "ccw"}))?;
crate::mode_cmds::rotate_arbitrary_with(s, &json!({"angle": angle, "direction": "ccw"}), false)?;
// Color Sampler points follow the crop's origin shift too (the rotation moved them above).
s.set_sampler_map(crop_target.sampler_map(target));
let extension = s.tools.background;
+11 -1
View File
@@ -63,6 +63,12 @@ pub fn rotated_size(size: Size, deg: f64) -> Size {
}
pub(crate) fn rotate_arbitrary(s: &mut Session, p: &Value) -> Result<Value> {
rotate_arbitrary_with(s, p, true)
}
/// [`rotate_arbitrary`]; `keep_counts` leaves the count points where they were (Image Rotation,
/// #11762). The Crop tool's straighten turn moves them with the image, as before.
pub(crate) fn rotate_arbitrary_with(s: &mut Session, p: &Value, keep_counts: bool) -> Result<Value> {
const CMD: &str = "image.rotation.arbitrary";
// At full precision: an f32 angle can grow the canvas 1 px past what `rotated_size` gives callers.
let angle = p.get("angle").and_then(Value::as_f64).unwrap_or(0.0);
@@ -132,7 +138,11 @@ pub(crate) fn rotate_arbitrary(s: &mut Session, p: &Value) -> Result<Value> {
// What Free Transform leaves alone: unlinked vector masks, gradient angles, artboards…
crate::canvas_geom::transform_layer_geometry(l, &a, false, dpi);
}
crate::canvas_geom::transform_doc_marks(doc, &a);
if keep_counts {
crate::canvas_geom::keeping_count_points(doc, |doc| crate::canvas_geom::transform_doc_marks(doc, &a));
} else {
crate::canvas_geom::transform_doc_marks(doc, &a);
}
for ch in doc.channels.iter_mut().chain(doc.quick_mask.as_mut()) {
ch.surface = crate::transform_cmds::warp_gray(&ch.surface, &h, interp)?;
}
+98
View File
@@ -329,3 +329,101 @@ fn bucket_and_gradient_reject_non_numeric_opacity_without_editing() {
assert!((px(&s, 5, 5)[0] - 128.0 / 255.0).abs() < 0.01, "{cmd}: null opacity is 100%");
}
}
/// #11311: a white layer (the Background made a normal layer), a selection cleared to
/// transparency, Deselect, then the Paint Bucket clicked in the hole with white at 100 %. Returns
/// the session after the fill and the layer's pixels right after the clear.
fn clear_then_bucket(depth: u32, selection: Value, bucket_aa: bool) -> (Session, Vec<[f32; 4]>) {
let mut s = Session::new();
s.execute("file.new", json!({"width": 120, "height": 100, "depth": depth, "background": "white"})).unwrap();
s.execute("layer.new.layerFromBackground", json!({})).unwrap();
s.execute("select.rect", selection).unwrap();
s.execute("edit.clear", json!({})).unwrap();
let cleared = layer_rgba(&s);
s.execute("select.deselect", json!({})).unwrap();
s.execute("paint.bucket", json!({"x": 60, "y": 50, "color": "#ffffff", "antiAlias": bucket_aa})).unwrap();
(s, cleared)
}
/// The active layer's pixels over the canvas, row by row.
fn layer_rgba(s: &Session) -> Vec<[f32; 4]> {
let d = s.active().unwrap();
let surf = d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap();
let b = d.doc.bounds();
(b.y0..b.y1).flat_map(|y| (b.x0..b.x1).map(move |x| (x, y))).map(|(x, y)| surf.rgba(x, y)).collect()
}
/// The first `n` pixels (as `x, y, rgba`) that aren't opaque white at 8 bits.
fn not_white(px: &[[f32; 4]], width: usize, n: usize) -> Vec<(usize, usize, [f32; 4])> {
let is_white = |p: &[f32; 4]| p.iter().all(|c| (c.clamp(0.0, 1.0) * 255.0).round() == 255.0);
px.iter().enumerate().filter(|(_, p)| !is_white(p)).take(n).map(|(i, p)| (i % width, i / width, *p)).collect()
}
fn assert_all_white(s: &Session, what: &str) {
let doc = &s.active().unwrap().doc;
let width = doc.bounds().width() as usize;
let layer = layer_rgba(s);
assert_eq!(not_white(&layer, width, 8), vec![], "{what}: layer pixels left after the fill");
let composite = photocraft_compose::render(doc, doc.bounds()).px.clone();
assert_eq!(composite.len(), layer.len());
assert_eq!(not_white(&composite, width, 8), vec![], "{what}: composite pixels left after the fill");
}
/// #11311 / #11354 review: after clearing an anti-aliased selection and bucket-filling the hole
/// white at 100 %, the hole and the hole's edge are opaque white and the opaque art is untouched.
/// The soft rim the Clear left (straight white at partial alpha) rises only partly, as in the
/// reference application: a pixel of the one-pixel ring 8-adjacent to the flood, at alpha `α`,
/// ends at `α + (1 − α)²`, and pixels further out keep their alpha, so a faint rim stays. Before the first round the hole's own edge stayed semi-transparent (a grey ring);
/// the first round filled the rim to 255 too, which the reference does not do.
#[test]
fn bucket_after_clearing_an_antialiased_selection_fills_the_hole_and_raises_the_rim_partly() {
let level = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as i32;
for depth in [8, 16, 32] {
let ellipse = json!({"x": 20, "y": 10, "width": 80, "height": 80, "ellipse": true, "antiAlias": true});
let (s, cleared) = clear_then_bucket(depth, ellipse, true);
// A transparent hole (its RGB zeroed) inside a rim of straight white at partial alpha,
// which the bucket's similarity test (RGB 255 away from the hole's 0) leaves out.
assert_eq!(cleared[50 * 120 + 60], [0.0; 4], "depth {depth}: the hole is empty");
let rim: Vec<&[f32; 4]> = cleared.iter().filter(|p| p[3] > 0.0 && p[3] < 1.0).collect();
assert!(!rim.is_empty(), "depth {depth}: an anti-aliased clear leaves a soft rim");
assert!(rim.iter().all(|p| p[..3].iter().all(|c| (c - 1.0).abs() < 1e-3)), "depth {depth}: the rim keeps its white");
let after = layer_rgba(&s);
// The flood is every pixel the 8-bit wand sees as empty; the ring is the pixels 8-adjacent to it.
let empty = |x: i64, y: i64| (0..120).contains(&x) && (0..100).contains(&y) && level(cleared[(y * 120 + x) as usize][3]) == 0;
let mut raised = 0;
for (i, (was, now)) in cleared.iter().zip(&after).enumerate() {
let at = (i % 120, i / 120);
let (x, y) = (at.0 as i64, at.1 as i64);
let next_to_flood = (-1..=1).any(|dy| (-1..=1).any(|dx| (dx, dy) != (0, 0) && empty(x + dx, y + dy)));
if level(was[3]) == 0 || was[3] >= 1.0 {
assert_eq!(level(now[3]), 255, "depth {depth} at {at:?}: hole, hole edge and opaque art end opaque: {now:?}");
} else if next_to_flood {
raised += 1;
let want = was[3] + (1.0 - was[3]).powi(2);
assert!((now[3] - want).abs() < 1.5 / 255.0, "depth {depth} at {at:?}: rim {was:?} -> {now:?}, want alpha {want}");
} else {
assert_eq!(now, was, "depth {depth} at {at:?}: a rim pixel beyond the ring next to the flood stays");
}
assert!(now[..3].iter().all(|c| (c - 1.0).abs() < 1e-3), "depth {depth} at {at:?}: white: {now:?}");
}
assert!(raised > 0, "depth {depth}: the fill reaches the rim");
assert!(after.iter().any(|p| level(p[3]) < 255), "depth {depth}: a faint rim stays, as in the reference");
}
}
/// Controls for #11311: a hard-edged selection leaves no soft rim, but the bucket's own
/// anti-aliasing used to leave the hole's edge pixels partly transparent too, so hard edges end
/// white as well; with neither anti-aliased (the case that was always right) it stays white.
#[test]
fn bucket_after_clearing_a_hard_selection_leaves_no_ring() {
let hard_ellipse = json!({"x": 20, "y": 10, "width": 80, "height": 80, "ellipse": true, "antiAlias": false});
let rect = json!({"x": 30, "y": 20, "width": 60, "height": 60});
for depth in [8, 16, 32] {
for (selection, bucket_aa) in [(hard_ellipse.clone(), true), (rect.clone(), true), (rect.clone(), false)] {
let (s, cleared) = clear_then_bucket(depth, selection.clone(), bucket_aa);
assert!(cleared.iter().all(|p| p[3] == 0.0 || p[3] == 1.0), "depth {depth} {selection}: a hard clear leaves no rim");
assert_all_white(&s, &format!("depth {depth} {selection}, bucket antiAlias {bucket_aa}"));
}
}
}
+22 -9
View File
@@ -106,17 +106,30 @@ fn bake_one(s: &mut Session, id: LayerId, key: &str) -> Result<bool> {
/// one history step.
fn rasterize_layer_style(s: &mut Session, p: &Value) -> Result<Value> {
let ids = crate::layer_multi_cmds::targets(s, p)?;
bake_layers(s, ids, bake_one)
}
/// Bake `ids` with `bake` as one history step; a layer that fails takes back the ones baked before
/// it (#4974).
fn bake_layers(s: &mut Session, ids: Vec<LayerId>, bake: impl Fn(&mut Session, LayerId, &str) -> Result<bool>) -> Result<Value> {
let many = ids.len() > 1;
let key = crate::extra_cmds::step_key(s, "rasterizeLayerStyle");
let mut done = Vec::new();
for id in ids {
if bake_one(s, id, &key)? {
done.push(id.0);
}
let nothing = || EngineError::Other(if many { "none of the selected layers has layer effects" } else { "the layer has no layer effects" }.into());
// Refused before a step starts: a failed `compound` still moves the revision, and a command
// that changes nothing must leave it alone.
if !ids.iter().any(|&id| s.active().and_then(|d| d.doc.layer(id)).is_some_and(can_bake)) {
return Err(nothing());
}
let Some(&first) = done.first() else {
return Err(EngineError::Other(if many { "none of the selected layers has layer effects" } else { "the layer has no layer effects" }.into()));
};
let key = crate::extra_cmds::step_key(s, "rasterizeLayerStyle");
let (first, done) = crate::analysis_cmds::compound(s, "Rasterize Layer Style", |s| {
let mut done = Vec::new();
for id in ids {
if bake(s, id, &key)? {
done.push(id.0);
}
}
let Some(&first) = done.first() else { return Err(nothing()) };
Ok((first, done))
})?;
let active = s.active().and_then(|d| d.active_layer).map(|id| id.0).filter(|id| done.contains(id));
Ok(json!({"layer": active.unwrap_or(first), "layers": done}))
}
@@ -162,3 +162,58 @@ fn disabled_and_bad_params_fail_gracefully() {
s.execute("layer.layerStyle.stroke", json!({"layer": g})).unwrap();
assert!(s.execute(ID, json!({"layer": g})).is_err(), "group styles are not baked");
}
/// #4974: a layer that fails to bake takes back the ones baked before it.
#[test]
fn a_later_layer_failing_takes_back_the_baked_ones() {
let (mut s, id) = scene(8);
let st = s.active_mut().unwrap();
st.saved_revision = st.revision;
let before = s.active().unwrap().doc.clone();
let steps = s.active().unwrap().history.past_len();
let journal = s.journal.len();
let calls = std::cell::Cell::new(0);
let r = bake_layers(&mut s, vec![LayerId(id), LayerId(id)], |s, id, key| {
calls.set(calls.get() + 1);
if calls.get() == 1 { bake_one(s, id, key) } else { Err(EngineError::Other("second layer failed".into())) }
});
assert!(r.is_err());
assert_eq!(calls.get(), 2);
assert_eq!(layer(&s, id).effects.items.len(), 5);
assert!(std::sync::Arc::ptr_eq(&s.active().unwrap().doc, &before));
assert_eq!(s.active().unwrap().history.past_len(), steps);
assert!(!s.active().unwrap().history.can_redo());
assert_eq!(s.journal.len(), journal);
assert!(!s.active().unwrap().is_dirty());
}
/// A layer with no effects is refused before a step starts: the revision does not move.
#[test]
fn a_layer_without_effects_changes_nothing() {
let (mut s, _) = scene(8);
let plain = s.execute("layer.new.layer", json!({"name": "plain"})).unwrap()["layer"].as_u64().unwrap();
let st = s.active_mut().unwrap();
st.saved_revision = st.revision;
let (revision, steps) = (s.active().unwrap().revision, s.active().unwrap().history.past_len());
let err = bake_layers(&mut s, vec![LayerId(plain)], bake_one).unwrap_err().to_string();
assert!(err.contains("no layer effects"), "{err}");
assert_eq!(s.active().unwrap().revision, revision);
assert_eq!(s.active().unwrap().history.past_len(), steps);
assert!(!s.active().unwrap().is_dirty());
}
/// Through the command itself: a layer without effects is refused and nothing moves.
#[test]
fn rasterize_layer_style_on_a_layer_without_effects_changes_nothing() {
let (mut s, _) = scene(8);
s.execute("layer.new.layer", json!({"name": "plain"})).unwrap();
let st = s.active_mut().unwrap();
st.saved_revision = st.revision;
let (revision, steps, journal) = (s.active().unwrap().revision, s.active().unwrap().history.past_len(), s.journal.len());
let err = s.execute(ID, json!({})).unwrap_err().to_string();
assert!(err.contains("no selected layer has layer effects"), "{err}");
assert_eq!(s.active().unwrap().revision, revision);
assert_eq!(s.active().unwrap().history.past_len(), steps);
assert_eq!(s.journal.len(), journal);
assert!(!s.active().unwrap().is_dirty());
}
@@ -3,7 +3,7 @@
//! only on the one that was clicked. An explicit `layer` param still targets exactly that layer.
use photocraft_doc::{LayerContent, LayerId};
use photocraft_engine::Session;
use photocraft_engine::{EngineError, Session};
use serde_json::{Value, json};
fn kind(s: &Session, id: LayerId) -> &'static str {
@@ -143,3 +143,141 @@ fn bad_targets_fail_gracefully() {
assert!(sc.s.execute(id, json!({"layer": u64::MAX})).is_err(), "{id}: no such layer");
}
}
fn deny(denied: &'static str, id: &str) -> photocraft_engine::Result<()> {
if id == denied { Err(EngineError::Other("denied".into())) } else { Ok(()) }
}
fn deny_shape_rasterize(id: &str, _: &Value) -> photocraft_engine::Result<()> {
deny("layer.rasterize.shape", id)
}
fn deny_vector_mask_rasterize(id: &str, _: &Value) -> photocraft_engine::Result<()> {
deny("layer.rasterize.vectorMask", id)
}
fn deny_type_rasterize(id: &str, _: &Value) -> photocraft_engine::Result<()> {
deny("type.rasterize", id)
}
/// Everything a refused Rasterize has to leave as it was (#4974).
struct Snapshot {
doc: std::sync::Arc<photocraft_doc::Document>,
steps: usize,
journal: usize,
selection: Vec<LayerId>,
}
impl Snapshot {
fn of(s: &mut Session) -> Snapshot {
// A clean document, and a redo entry that a step recorded by mistake would drop.
let st = s.active_mut().unwrap();
st.saved_revision = st.revision;
let st = s.active().unwrap();
assert!(st.history.can_redo(), "the test needs a redo entry");
Snapshot { doc: st.doc.clone(), steps: st.history.past_len(), journal: s.journal.len(), selection: st.selected_layers() }
}
fn assert_restored(&self, s: &Session) {
let st = s.active().unwrap();
assert!(std::sync::Arc::ptr_eq(&st.doc, &self.doc), "the document is the one from before");
assert_eq!(st.history.past_len(), self.steps);
assert!(st.history.can_redo(), "the redo entry survives");
assert_eq!(s.journal.len(), self.journal);
assert!(!st.is_dirty());
assert_eq!(st.selected_layers(), self.selection);
}
}
impl Scene {
/// Leave a redo entry behind: a layer that was made, then undone.
fn make_redo_entry(&mut self) {
self.s.execute("layer.new.layer", json!({})).unwrap();
assert!(self.s.undo());
assert!(self.s.active().unwrap().history.can_redo());
}
}
#[test]
fn rasterize_layer_takes_back_a_converted_layer_when_a_later_one_is_refused() {
let mut sc = scene();
// The type layer is lower, so it is converted first; the shape layer's step is then denied.
sc.select(&[sc.text, sc.shape]);
sc.make_redo_entry();
let before = Snapshot::of(&mut sc.s);
sc.s.authorize = Some(deny_shape_rasterize);
assert!(sc.s.execute("layer.rasterize.layer", json!({})).is_err());
assert_eq!(kinds(&sc.s, &[sc.text, sc.shape]), ["type", "shape"]);
before.assert_restored(&sc.s);
// Allowed again, the same command converts both in one step.
sc.s.authorize = None;
sc.s.execute("layer.rasterize.layer", json!({})).unwrap();
assert_eq!(kinds(&sc.s, &[sc.text, sc.shape]), ["raster", "raster"]);
assert_eq!(sc.s.active().unwrap().history.past_len(), before.steps + 1);
}
#[test]
fn rasterize_layer_takes_back_the_content_when_its_vector_mask_step_is_refused() {
let mut sc = scene();
let square = json!({"subpaths": [{"closed": true, "knots": [[4, 4], [40, 4], [40, 30], [4, 30]]}]});
sc.s.execute("layer.vectorMask.add", json!({"layer": sc.text.0, "path": square})).unwrap();
sc.select(&[sc.text]);
sc.make_redo_entry();
let before = Snapshot::of(&mut sc.s);
// The type content converts, then the mask step is denied.
sc.s.authorize = Some(deny_vector_mask_rasterize);
assert!(sc.s.execute("layer.rasterize.layer", json!({})).is_err());
assert_eq!(kind(&sc.s, sc.text), "type");
assert!(sc.s.active().unwrap().doc.layer(sc.text).unwrap().vector_mask.is_some());
before.assert_restored(&sc.s);
}
#[test]
fn rasterize_layer_style_takes_back_a_baked_layer_when_a_later_one_is_refused() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 64, "height": 64})).unwrap();
let pixels = id_of(s.execute("layer.new.layer", json!({"name": "Pixels"})).unwrap());
s.execute("paint.stroke", json!({"points": [[20, 20]], "size": 12})).unwrap();
let shadow = json!({"blend": "normal", "distance": 4, "size": 2, "color": "#102040"});
s.execute("layer.layerStyle.dropShadow", shadow.clone()).unwrap();
let text = id_of(s.execute("type.create", json!({"text": "Hi", "size": 24, "x": 4, "y": 30})).unwrap());
s.execute("layer.layerStyle.dropShadow", shadow).unwrap();
let mut sc = Scene { s, text, shape: pixels, smart: pixels, fill: pixels, bystander: pixels };
// The pixel layer is lower, so it is baked first; the type layer's content step is then denied.
sc.select(&[pixels, text]);
sc.make_redo_entry();
let before = Snapshot::of(&mut sc.s);
sc.s.authorize = Some(deny_type_rasterize);
assert!(sc.s.execute("layer.rasterize.layerStyle", json!({})).is_err());
let st = sc.s.active().unwrap();
assert!(!st.doc.layer(pixels).unwrap().effects.items.is_empty(), "the baked layer has its effects back");
assert_eq!(kind(&sc.s, text), "type");
before.assert_restored(&sc.s);
sc.s.authorize = None;
sc.s.execute("layer.rasterize.layerStyle", json!({})).unwrap();
assert!(sc.s.active().unwrap().doc.layer(pixels).unwrap().effects.items.is_empty());
assert_eq!(kind(&sc.s, text), "raster");
}
#[test]
fn each_rasterize_command_names_its_history_step() {
let cases = [
("layer.rasterize.layer", "text", "Rasterize"),
("layer.rasterize.type", "text", "Rasterize Type"),
("layer.rasterize.shape", "shape", "Rasterize Shape"),
("layer.rasterize.fillContent", "fill", "Rasterize Fill Content"),
("layer.rasterize.smartObject", "smart", "Rasterize Smart Object"),
];
for (cmd, which, label) in cases {
let mut sc = scene();
let id = match which {
"text" => sc.text,
"shape" => sc.shape,
"fill" => sc.fill,
_ => sc.smart,
};
sc.select(&[id]);
sc.s.execute(cmd, json!({})).unwrap();
assert_eq!(sc.s.active().unwrap().history.undo_label(), Some(label), "{cmd}");
}
}
+15
View File
@@ -147,6 +147,7 @@ row; the action still adds only one Undo entry.
| `CtTL` | cutToLayer | Layer Via Cut | `layer.new.layerViaCut` |
| `LnsF` | lensFlare | Lens Flare | `filter.render.lensFlare` |
| `Lvls` | levels | Levels | `image.adjustments.levels`, `image.autoTone`, `image.autoContrast` |
| `Mk ` | make | Make | `image.calculations`, `layer.layerStyle.createLayer`, `layer.new.layer`, `layer.new.group`, `layer.groupLayers`, `layer.new.frameFromLayers` (Layer › New › Frame from Layers), `layer.duplicate`, `layer.new.layerViaCopy`, `layer.new.layerViaCut`, `layer.newFillLayer.solidColor`, `layer.newFillLayer.pattern`, `layer.newFillLayer.gradient`, `layer.newAdjustmentLayer.levels`, `layer.newAdjustmentLayer.curves`, `layer.newAdjustmentLayer.hueSaturation`, `layer.newAdjustmentLayer.brightnessContrast`, `layer.newAdjustmentLayer.threshold`, `layer.newAdjustmentLayer.posterize`, `layer.newAdjustmentLayer.invert`, `layer.newAdjustmentLayer.colorBalance`, `layer.newAdjustmentLayer.vibrance`, `layer.newAdjustmentLayer.exposure`, `layer.newAdjustmentLayer.photoFilter`, `layer.newAdjustmentLayer.blackWhite`, `layer.newAdjustmentLayer.channelMixer`, `layer.newAdjustmentLayer.selectiveColor`, `layer.newAdjustmentLayer.gradientMap`, `layer.layerMask.revealAll`, `layer.layerMask.hideAll`, `layer.layerMask.revealSelection`, `layer.layerMask.hideSelection`, `file.new`, `file.newFromClipboard`, `history.newSnapshot`, `type.convertToShape`, `type.createWorkPath` |
| `Mk ` | make | Make | `image.calculations`, `layer.layerStyle.createLayer`, `layer.new.layer`, `layer.new.group`, `layer.groupLayers`, `layer.duplicate`, `layer.new.layerViaCopy`, `layer.new.layerViaCut`, `layer.newFillLayer.solidColor`, `layer.newFillLayer.pattern`, `layer.newFillLayer.gradient`, `layer.newAdjustmentLayer.levels`, `layer.newAdjustmentLayer.curves`, `layer.newAdjustmentLayer.hueSaturation`, `layer.newAdjustmentLayer.brightnessContrast`, `layer.newAdjustmentLayer.threshold`, `layer.newAdjustmentLayer.posterize`, `layer.newAdjustmentLayer.invert`, `layer.newAdjustmentLayer.colorBalance`, `layer.newAdjustmentLayer.vibrance`, `layer.newAdjustmentLayer.exposure`, `layer.newAdjustmentLayer.photoFilter`, `layer.newAdjustmentLayer.blackWhite`, `layer.newAdjustmentLayer.channelMixer`, `layer.newAdjustmentLayer.selectiveColor`, `layer.newAdjustmentLayer.gradientMap`, `layer.layerMask.revealAll`, `layer.layerMask.hideAll`, `layer.layerMask.revealSelection`, `layer.layerMask.hideSelection`, `file.new`, `file.newFromClipboard`, `history.newSnapshot`, `type.convertToShape`, `type.createWorkPath`, `layer.new.artboard` (Layer › New › Artboard), `layer.new.artboardFromLayers` (Layer › New › Artboard from Layers) |
| (string ID only) | animationFramesFromLayers | Make Frames from Layers | |
| (string ID only) | matchColor | Match Color | `image.adjustments.matchColor` |
@@ -273,6 +274,20 @@ options are refused on export. Playback uses the native command's preconditions
and current state. Isolate Layers toggles the panel view; type defaults remain
session settings; Record Measurements uses the current measurement configuration.
Layer › New › Frame from Layers is a Make with `null` = the class
`framedGroupSection`, `From` = the layer by name and `Nm ` = the frame's name. It
plays as `layer.new.frameFromLayers` on that layer, and the frame fits that
layer's bounds whatever is selected. The dialog's width and height are not in the
step. `layerSectionStart` and `layerSectionEnd` are ids of the recording session:
a loaded step saves back its recorded descriptor, session ids included, while it
still frames the same layer with the same name, and a step recorded in PhotoCraft
writes `null`, `From` and `Nm ` (only for a name that isn't blank) without them. A
native step without a layer of its own frames the selected layers and writes
`From` = the target layer, a form the recordings don't show. Another `From`, a
repeated or extra key, or a value of another type stays a kept step; a native step
with a layer by id, or with the group options the command passes on (colour, mode,
opacity), refuses export.
Link Layers plays as the toggle the reference application performs (played twice on the same
layers it links, then unlinks them; see the measurements below). Unlink is explicit and
idempotent: it keeps an already unlinked selection unlinked and clears singleton link groups.