Merge remote-tracking branch 'origin/main' into automation/shared-live-client

This commit is contained in:
David Mann committed 2026-11-19 19:16:17 +01:00
commit 3152ed0703
86 files changed
+6273 -1461

No files matched your search

+34 -13
View File
@@ -442,6 +442,7 @@ pub struct StampParams<'a> {
pub hardness: f32,
pub opacity: f32,
pub flow: f32,
/// Tolerance as a fraction (Tolerance 50 % is `0.5`).
pub tolerance: f32,
/// Destination tile edge; `0` processes the whole buffer as one tile.
pub tile: i32,
@@ -581,26 +582,41 @@ fn dab_intersects(dab: &Dab, tile: (i32, i32, i32, i32)) -> bool {
x0 < tile.2 && x1 > tile.0 && y0 < tile.3 && y1 > tile.1
}
/// Mean difference between `src` and `dest` over the dab's covered pixels (working-space peak is
/// 1, so a tolerance of 50% is `0.5`). Per pixel it is the larger of the mean colour change and the
/// alpha change: an opaque pixel's unchanged alpha must not water a colour change down, and the
/// Eraser keeps the colour and lowers only the alpha. Fully transparent source samples are left
/// out; a dab whose samples are all transparent has a mean of `0.0`. `None` if nothing is covered.
fn dab_mean_diff(p: &StampParams<'_>, dab: &Dab) -> Option<f32> {
let (x0, y0, x1, y1) = dab_bounds(dab)?;
/// Radius, in pixels, of the neighbourhood around a stroke's start that Tolerance measures.
const START_RADIUS: f32 = 2.5;
/// Difference, in working-space units, that 100 % Tolerance asks for. The reference application
/// starts strokes on a 20-level change (about 8 %) at Tolerance 10 but not 20, and on red over grey
/// (about 50 %) at 80 but not 90, which a linear threshold of `0.6 × Tolerance` reproduces.
const TOLERANCE_SCALE: f32 = 0.6;
/// Mean difference between `src` and `dest` around the dab's centre, where its stroke starts
/// (working-space peak is 1). Per pixel it is the larger of the mean colour change and the alpha
/// change: an opaque pixel's unchanged alpha must not water a colour change down, and the Eraser
/// keeps the colour and lowers only the alpha. Fully transparent source samples are left out; a
/// start whose samples are all transparent has a mean of `0.0`. `None` if nothing is there.
fn start_diff(p: &StampParams<'_>, dab: &Dab) -> Option<f32> {
if !(dab.x.is_finite() && dab.y.is_finite()) {
return None;
}
let x0 = floor_i32(dab.x - START_RADIUS);
let y0 = floor_i32(dab.y - START_RADIUS);
let x1 = floor_i32(dab.x + START_RADIUS).saturating_add(1);
let y1 = floor_i32(dab.y + START_RADIUS).saturating_add(1);
let mut sampled = vec![0.0f32; p.ch];
let mut sum = 0.0f32;
let mut count = 0u32;
let mut transparent = 0u32;
for y in y0..y1 {
for x in x0..x1 {
if coverage_at(dab, x, y, p.hardness) <= 0.0 {
// The history state at the same position, not the dab's rotated read.
let (cx, cy) = (x as f32 + 0.5, y as f32 + 0.5);
if (cx - dab.x).hypot(cy - dab.y) > START_RADIUS {
continue;
}
let Some(di) = origin_index(p.dest_origin, x, y, p.dest_w, p.dest_h, p.ch) else { continue };
let Some(dst) = p.dest.get(di..di.saturating_add(p.ch)) else { continue };
let (sx, sy) = rotated_source(dab, x, y);
if !sample_bilinear(SrcView { data: p.src, w: p.src_w, h: p.src_h, origin: p.src_origin, ch: p.ch, alpha: p.alpha }, sx, sy, &mut sampled) {
if !sample_bilinear(SrcView { data: p.src, w: p.src_w, h: p.src_h, origin: p.src_origin, ch: p.ch, alpha: p.alpha }, cx, cy, &mut sampled) {
continue;
}
let nch = p.ch.min(dst.len()).min(sampled.len());
@@ -636,8 +652,10 @@ fn dab_mean_diff(p: &StampParams<'_>, dab: &Dab) -> Option<f32> {
/// Stamp posed dabs into `dest`, tile by tile, reading `src` at each dab's rotated positions.
///
/// Sequential dabs overlap: dab *n* sees dab *n − 1*. Returns how many destination pixels were
/// written (tolerance-skipped dabs count as zero).
/// Sequential dabs overlap: dab *n* sees dab *n − 1*. Tolerance is decided where a dab starts
/// (around its centre), so a dab that starts on a changed area also paints the unchanged pixels
/// it reaches. Returns how many destination pixels were written (tolerance-skipped dabs count as
/// zero).
pub fn stamp(p: &mut StampParams<'_>) -> Result<u32, StampError> {
dest_pixels(p)?;
if p.src_w == 0 || p.src_h == 0 {
@@ -653,9 +671,10 @@ pub fn stamp(p: &mut StampParams<'_>) -> Result<u32, StampError> {
let tiles = tile_grid(p.dest_w, p.dest_h, p.dest_origin, p.tile);
let mut written = 0u32;
let dabs: Vec<Dab> = p.dabs.to_vec();
let threshold = p.tolerance * TOLERANCE_SCALE;
for dab in &dabs {
let Some(bounds) = dab_bounds(dab) else { continue };
if p.tolerance > 0.0 && dab_mean_diff(p, dab).is_some_and(|m| m < p.tolerance) {
if p.tolerance > 0.0 && start_diff(p, dab).is_some_and(|m| m < threshold) {
continue;
}
let overlapping: Vec<(i32, i32, i32, i32)> = tiles.iter().copied().filter(|t| dab_intersects(dab, *t)).collect();
@@ -676,3 +695,5 @@ pub fn stamp(p: &mut StampParams<'_>) -> Result<u32, StampError> {
#[cfg(test)]
mod tests;
#[cfg(test)]
mod tolerance_tests;
+6 -4
View File
@@ -23,7 +23,8 @@ fn tolerance_ignores_fully_transparent_samples() {
}
});
let dab = Dab { x: 1.0, y: 0.5, theta: 0.0, radius: 2.0, pressure: 1.0 };
for tolerance in [0.6, 0.3] {
// Mean difference 0.4: under the 0.6 x Tolerance threshold at 1.0, over it at 0.3.
for tolerance in [1.0, 0.3] {
let mut dest = before.clone();
let written = stamp(&mut StampParams {
dest: &mut dest,
@@ -46,7 +47,7 @@ fn tolerance_ignores_fully_transparent_samples() {
alpha: Some(ch - 1),
})
.unwrap();
if tolerance == 0.6 {
if tolerance == 1.0 {
assert_eq!(written, 0, "channels={ch}, hidden={hidden}");
assert_eq!(dest, before);
} else {
@@ -377,12 +378,13 @@ fn tolerance_zero_writes_where_history_differs() {
#[test]
fn tolerance_ignores_unchanged_alpha() {
// Colour moved by 0.3 and alpha did not: the 0.25 threshold must not see a 0.225 average.
// Colour moved by 0.3 and alpha did not: the 0.27 threshold (Tolerance 45 %) must not see a
// 0.225 average.
let (w, h, ch) = (48usize, 48usize, 4);
let src = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.6 });
let dest0 = fill(w, h, ch, |_, _, c| if c == 3 { 1.0 } else { 0.3 });
let dab = Dab { x: 24.0, y: 24.0, theta: 0.0, radius: 8.0, pressure: 1.0 };
for (tolerance, paints) in [(0.25, true), (0.35, false)] {
for (tolerance, paints) in [(0.45, true), (0.55, false)] {
let mut dest = dest0.clone();
let mut p = StampParams {
dest: &mut dest,
@@ -0,0 +1,159 @@
//! Tolerance decides where a stroke may start, with the reference application's threshold (#12633).
use super::*;
const W: usize = 80;
const H: usize = 40;
const CH: usize = 4;
fn level(v: u8) -> f32 {
f32::from(v) / 255.0
}
/// Source: grey on the left half, green on the right half (the measured Setup state).
fn setup_source() -> Vec<f32> {
image(|x| if x < W / 2 { [128, 128, 128] } else { [40, 160, 60] })
}
/// Current layer: red on the left half (far from grey), 20 levels off the green on the right.
fn current_layer() -> Vec<f32> {
image(|x| if x < W / 2 { [255, 0, 0] } else { [60, 180, 80] })
}
fn image(rgb: impl Fn(usize) -> [u8; 3]) -> Vec<f32> {
let mut v = Vec::with_capacity(W * H * CH);
for _ in 0..H {
for x in 0..W {
let [r, g, b] = rgb(x);
v.extend_from_slice(&[level(r), level(g), level(b), 1.0]);
}
}
v
}
fn dab(x: f32, radius: f32) -> Dab {
Dab { x, y: H as f32 / 2.0, theta: 0.0, radius, pressure: 1.0 }
}
/// Stamps `dabs` at `tolerance` (a fraction, Tolerance 50 % = 0.5) and returns the new layer.
fn paint(dest: &[f32], dabs: &[Dab], tolerance: f32) -> Vec<f32> {
let src = setup_source();
let mut out = dest.to_vec();
let mut p = StampParams {
dest: &mut out,
dest_w: W,
dest_h: H,
dest_origin: (0, 0),
src: &src,
src_w: W,
src_h: H,
src_origin: (0, 0),
ch: CH,
dabs,
hardness: 1.0,
opacity: 1.0,
flow: 1.0,
tolerance,
tile: 0,
selection: None,
lock_transparent: false,
alpha: Some(3),
};
stamp(&mut p).unwrap();
out
}
/// Pixels changed in columns `x0..x1`.
fn changed(before: &[f32], after: &[f32], x0: usize, x1: usize) -> usize {
let mut n = 0;
for y in 0..H {
for x in x0..x1 {
let i = (y * W + x) * CH;
if (0..CH).any(|c| (before[i + c] - after[i + c]).abs() > 1.0e-4) {
n += 1;
}
}
}
n
}
const LEFT: f32 = 12.0;
const RIGHT: f32 = 68.0;
#[test]
fn a_small_difference_starts_strokes_at_10_but_not_at_20() {
let before = current_layer();
let dabs = [dab(RIGHT, 6.0)];
assert!(changed(&before, &paint(&before, &dabs, 0.10), 40, 80) > 0, "20 levels off paints at Tolerance 10");
assert_eq!(changed(&before, &paint(&before, &dabs, 0.20), 0, 80), 0, "20 levels off paints nothing at Tolerance 20");
}
#[test]
fn red_over_grey_starts_strokes_up_to_80_and_nothing_from_90() {
let before = current_layer();
let dabs = [dab(LEFT, 6.0)];
for tolerance in [0.60, 0.80] {
assert!(changed(&before, &paint(&before, &dabs, tolerance), 0, 40) > 0, "red over grey paints at {tolerance}");
}
let both = [dab(LEFT, 6.0), dab(RIGHT, 6.0)];
for tolerance in [0.90, 0.95, 0.99, 1.0] {
assert_eq!(changed(&before, &paint(&before, &both, tolerance), 0, 80), 0, "nothing paints at {tolerance}");
}
}
#[test]
fn tolerance_zero_paints_everywhere() {
let before = current_layer();
let after = paint(&before, &[dab(LEFT, 6.0), dab(RIGHT, 6.0)], 0.0);
assert!(changed(&before, &after, 0, 40) > 0);
assert!(changed(&before, &after, 40, 80) > 0);
// Even where the layer equals the source, the dab is stamped (nothing visible changes).
let src = setup_source();
let mut out = src.clone();
let d = [dab(LEFT, 6.0)];
let mut p = StampParams {
dest: &mut out,
dest_w: W,
dest_h: H,
dest_origin: (0, 0),
src: &src,
src_w: W,
src_h: H,
src_origin: (0, 0),
ch: CH,
dabs: &d,
hardness: 1.0,
opacity: 1.0,
flow: 1.0,
tolerance: 0.0,
tile: 0,
selection: None,
lock_transparent: false,
alpha: Some(3),
};
assert!(stamp(&mut p).unwrap() > 0);
}
/// Several dabs across both halves at Tolerance 20: only those starting on the red half paint, and
/// the right half changes only where a red-half dab reaches into it.
#[test]
fn at_20_strokes_start_only_on_the_large_difference() {
let before = current_layer();
let dabs: Vec<Dab> = [8.0, 20.0, 36.0, 52.0, 64.0, 76.0].iter().map(|&x| dab(x, 6.0)).collect();
let after = paint(&before, &dabs, 0.20);
assert!(changed(&before, &after, 0, 40) > 0);
assert_eq!(changed(&before, &after, 44, 80), 0, "no dab starts on the 20-level half");
assert!(changed(&before, &after, 40, 44) > 0, "the dab at x 36 runs into the right half");
}
/// The rule is where a stroke starts, not the mean under the whole dab: a big dab that starts just
/// inside the red half paints over the right half too, and one that starts just inside the right
/// half paints nothing although a large part of it covers red.
#[test]
fn the_start_decides_not_the_whole_dab() {
let before = current_layer();
let started_on_red = paint(&before, &[dab(37.0, 14.0)], 0.80);
assert!(changed(&before, &started_on_red, 40, 80) > 0, "a stroke started on red runs into the green half");
let started_on_green = paint(&before, &[dab(43.0, 14.0)], 0.20);
assert_eq!(changed(&before, &started_on_green, 0, 80), 0, "a stroke started on the 20-level half stays unpainted");
}
+10 -6
View File
@@ -193,11 +193,15 @@ pub(super) fn bevel_maps(shape: &Map, b: &Bevel, light: &GlobalLight, tex: &Text
let on_bevel = |x: i64, y: i64| {
hmap.get(x, y) > BEVEL_H_EPS || (reach_past && [(1, 0), (-1, 0), (0, 1), (0, -1)].iter().any(|(dx, dy)| hmap.get(x + dx, y + dy) > BEVEL_H_EPS))
};
// The gloss contour remaps the shading `n · light` before it splits into highlight (above
// what it maps a flat face's `sin(altitude)` to) and shadow. Applied to the highlight and shadow amounts
// instead, a contour that starts high (Rolling Slope - Descending) lit every pixel the light
// missed, so a bevelled glyph's flat face took the full highlight (#7360) where Photoshop
// leaves it at the layer's colour. The Linear contour changes nothing either way.
// The gloss contour remaps the shading `n · light` before it splits into highlight (above a
// flat face's own, unmapped `sin(altitude)`) and shadow (below it). Applied to the highlight
// and shadow amounts instead, a contour that starts high (Rolling Slope - Descending) lit
// every pixel the light missed (#7360). With the mapped `lut(sin(altitude))` as the neutral,
// a high light washed out whole faces: at altitude 69 that contour maps the flat 0.93 to
// 0.16, so every slope above 0.16 took the full highlight where Photoshop only glints where
// the shading nears 0. A contour that moves the flat shading lights or darkens the flat face
// too, as Photoshop does (oracles bevel-inner-gloss-ramp-peak / -double-ring-aa: faces at
// the full highlight and a 0.69 shadow). The Linear contour changes nothing either way.
let gloss = contour_lut(&b.gloss_contour);
let shade_into = |depth: f32, region_kind: u8| -> (Map, Map) {
let (mut hi, mut sh) = (Map::new(shape.w, shape.h, 0.0), Map::new(shape.w, shape.h, 0.0));
@@ -219,7 +223,7 @@ pub(super) fn bevel_maps(shape: &Map, b: &Bevel, light: &GlobalLight, tex: &Text
let len = (n[0] * n[0] + n[1] * n[1] + 1.0).sqrt();
let shade = (n[0] * light_v[0] + n[1] * light_v[1] + n[2] * light_v[2]) / len;
let region = if region_kind == 0 { shape.v[i] } else { f32::from(shape.v[i] < 1.0 - INSIDE_EPS && on_bevel(x, y)) };
let k = gloss.as_ref().map_or(shade - se, |l| lut_at(l, shade) - lut_at(l, se));
let k = gloss.as_ref().map_or(shade, |l| lut_at(l, shade)) - se;
if k > 0.0 {
hi_row[x as usize] = (k / (1.0 - se).max(1e-3)).clamp(0.0, 1.0) * region;
} else {
+58
View File
@@ -199,6 +199,64 @@ fn smooth_inner_bevel_lights_the_top_edge_inside_only() {
assert!(at(&maps[0], 20, 15) < 0.05);
}
/// A gloss contour from Photoshop's 0–255 contour editor points.
fn gloss_of(points: &[(f32, f32)]) -> Contour {
Contour::Custom {
name: "gloss".into(),
points: points.iter().map(|&(i, o)| photocraft_doc::adjust::CurvePoint { input: i / 255.0, output: o / 255.0 }).collect(),
corners: vec![],
}
}
/// Smooth inner bevel highlight and shadow maps of `shape` with `gloss`, light from `angle` at
/// `altitude`.
fn gloss_maps(shape: &Map, gloss: Contour, angle: f32, altitude: f32, size: f32, depth: f32) -> Vec<Map> {
let mut b = bevel_of(BevelStyle::InnerBevel, BevelTechnique::Smooth);
(b.angle, b.altitude, b.size, b.depth, b.gloss_contour) = (angle, altitude, size, depth, gloss);
bevel_maps(shape, &b, &GlobalLight::default(), &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES)).0
}
/// The gloss contour maps the shading, and the flat face's own unmapped shading `sin(altitude)`
/// stays the neutral. Photoshop's own composite of a purchased style pack's type (Rolling Slope -
/// Descending at altitude 69, 16 px smooth inner bevel at 358 %): the face stays at its colour, with white
/// glints only where the shading is within ~0.015 of zero (measured per pixel against this
/// bevel's shading). With the mapped `lut(sin 69°)` = 0.16 as the neutral, every slope pixel
/// whose mapped shading came out above it took the full highlight, and the type rendered white.
#[test]
fn high_altitude_descending_gloss_only_glints_where_the_light_misses() {
let n = 80;
let mut shape = Map::new(n, n, 0.0);
for y in 10..70 {
for x in 20..60 {
shape.v[y * n + x] = 1.0;
}
}
let rolling = gloss_of(&[(2.0, 255.0), (53.0, 100.0), (97.0, 107.0), (179.0, 153.0), (252.0, 0.0)]);
// Light from the left: the bar's right slope faces away from it.
let maps = gloss_maps(&shape, rolling, 180.0, 69.0, 16.0, 3.58);
let row: Vec<f32> = (20..60).map(|x| maps[0].v[40 * n + x]).collect();
let lit = row.iter().filter(|v| **v > 0.05).count();
assert!(lit <= 8, "only a few glint pixels, not the whole face: {row:?}");
assert!(row[..20].iter().all(|v| *v < 0.05), "no highlight on the slope facing the light: {row:?}");
assert!(row[20..].iter().any(|v| *v > 0.9), "a full glint where the slope faces away: {row:?}");
}
/// Photoshop 27.11 oracles (corpus `bevel-inner-gloss-ramp-peak` / `-double-ring-aa`: 12 px
/// smooth inner bevel at altitude 30, Screen white and Multiply black at 75 % over (90, 120,
/// 170)): a contour that maps the flat shading 0.5 above or below 0.5 lights or darkens the flat
/// face too. Ramp-peak (0,0)(128,255)(255,0) paints the face (214, 221, 234), the full
/// highlight; double-ring (…, (128, 40), …) paints it (44, 58, 83), a 0.69 shadow.
#[test]
fn a_gloss_contour_lights_or_darkens_the_flat_face_around_the_unmapped_neutral() {
let shape = square(40, 5, 35);
let face = |m: &Map| m.v[20 * 40 + 20];
let peak = gloss_maps(&shape, gloss_of(&[(0.0, 0.0), (128.0, 255.0), (255.0, 0.0)]), 120.0, 30.0, 5.0, 1.0);
assert!(face(&peak[0]) > 0.99 && face(&peak[1]) == 0.0, "ramp-peak: full highlight, {} / {}", face(&peak[0]), face(&peak[1]));
let ring = gloss_maps(&shape, gloss_of(&[(0.0, 0.0), (64.0, 255.0), (128.0, 40.0), (192.0, 255.0), (255.0, 0.0)]), 120.0, 30.0, 5.0, 1.0);
// (0.5 − 40/255) / 0.5: 90 × (1 − 0.75 × 0.686) = 43.7.
assert!(face(&ring[0]) == 0.0 && (face(&ring[1]) - 0.686).abs() < 0.02, "double-ring: shadow {}", face(&ring[1]));
}
/// Photoshop 27.11, measured across a straight edge (size 10, depth 100 %, light from the top
/// at 30°): a chisel facet has the slope `depth × size / (2 (size + 1))`, flat right up to the
/// edge pixel for Inner Hard; Inner Soft's edge pixel is half as steep again; Outer Hard
+64 -5
View File
@@ -1988,10 +1988,12 @@ fn satin_and_bevel_stay_inside_shape() {
/// #7360: a gloss contour that starts high (Rolling Slope - Descending, as the reporter's PSD
/// uses) left a bevelled shape's flat face at the full Overlay highlight, (255, 40, 42) on a
/// (151, 22, 23) fill, where Photoshop leaves the face at the fill colour. The contour maps the
/// shading, so the flat face stays neutral and only the slopes are shaded.
/// (151, 22, 23) fill. The contour maps the shading, with the unmapped flat shading
/// `sin(altitude)` as the neutral, so the face only takes what the contour moves 0.5 by:
/// Rolling Slope maps it to 0.55, a 0.09 highlight, (161, 24, 25). Photoshop's own composite of
/// the reporter's repro has the glyph's face at 151–161 in red, not the exact fill.
#[test]
fn a_gloss_contour_leaves_the_flat_face_of_a_bevel_unlit() {
fn a_gloss_contour_leaves_the_flat_face_of_a_bevel_near_its_fill() {
let fill = [151.0 / 255.0, 22.0 / 255.0, 23.0 / 255.0, 1.0];
let rolling = photocraft_doc::Contour::Custom {
name: "Rolling Slope - Descending".into(),
@@ -2029,14 +2031,71 @@ fn a_gloss_contour_leaves_the_flat_face_of_a_bevel_unlit() {
};
let d = render(rolling);
for (x, y) in [(20, 20), (16, 22), (24, 16)] {
let p = px(&d, x, y);
assert!(close4(p, fill), "flat face ({x},{y}) keeps the fill: {:?}", p.map(|v| (v * 255.0).round()));
let p = px(&d, x, y).map(|v| (v * 255.0).round());
assert!((158.0..=164.0).contains(&p[0]) && (22.0..=26.0).contains(&p[1]), "flat face ({x},{y}) near the fill: {p:?}");
}
let linear = render(photocraft_doc::Contour::Linear);
assert!(close4(px(&linear, 20, 20), fill), "Linear leaves the flat face too");
assert!(!close4(px(&d, 20, 11), fill), "the slopes are still shaded");
}
/// A deep bevel under a high light with a descending gloss contour (altitude 69, 358 %, Rolling
/// Slope - Descending, Screen white 78 %) keeps a red shape red at every depth: the slopes are
/// shaded around the unmapped `sin(altitude)`, so only the steepest pixels facing away glint.
/// Mapped through the contour, that neutral fell to 0.16 and the whole shape rendered white.
#[test]
fn a_high_light_descending_gloss_keeps_the_face_its_colour_at_every_depth() {
let red = [0.6, 0.0, 0.0, 1.0];
let rolling = photocraft_doc::Contour::Custom {
name: "Rolling Slope - Descending".into(),
points: [(0.0078, 1.0), (0.2078, 0.3922), (0.3804, 0.4196), (0.7020, 0.6), (0.9882, 0.0)]
.iter()
.map(|&(input, output)| CurvePoint { input, output })
.collect(),
corners: vec![],
};
let mut first: Option<Vec<[f32; 4]>> = None;
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
let mut d = Document::with_background("t", Size::new(80, 80), ColorMode::Rgb, depth, Color::BLACK);
let mut l = Layer::raster("bar", d.pixel_format());
l.surface_mut().unwrap().fill_rect(Rect::new(20, 10, 60, 70), &red);
l.effects.items = vec![Effect::BevelEmboss(photocraft_doc::Bevel {
enabled: true,
style: photocraft_doc::BevelStyle::InnerBevel,
technique: photocraft_doc::BevelTechnique::Smooth,
depth: 3.58,
up: true,
size: 16.0,
soften: 0.0,
angle: 180.0,
altitude: 69.0,
use_global_light: false,
gloss_contour: rolling.clone(),
gloss_anti_alias: false,
highlight: FxCommon::new(photocraft_color::BlendMode::Screen, 0.78),
highlight_color: Color::WHITE,
shadow: FxCommon::new(photocraft_color::BlendMode::Multiply, 0.09),
shadow_color: Color::BLACK,
contour: None,
texture: None,
})];
d.layers.push(l);
// The slope facing the light, the middle, and a slope pixel facing away short of its glint.
let got: Vec<[f32; 4]> = [(23, 40), (30, 40), (40, 40), (50, 40)].iter().map(|&(x, y)| px(&d, x, y)).collect();
for (p, at) in got.iter().zip([23, 30, 40, 50]) {
assert!(p[0] > 0.5 && p[1] < 0.05 && p[2] < 0.05, "{depth:?} x={at}: still red, not washed white: {p:?}");
}
match &first {
None => first = Some(got),
Some(f) => {
for (a, b) in f.iter().zip(&got) {
assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() <= 3.0 / 255.0), "{depth:?} agrees with 8-bit: {a:?} vs {b:?}");
}
}
}
}
}
#[test]
fn clipped_layer_effects_are_clipped_to_base() {
let mut d = doc_white(40, 40);
+144 -1221
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -403,7 +403,7 @@ pub(crate) fn adjust_as_filter(kind: &str, p: &Value, surf: &Surface, histogram_
})?;
} else if kind == "desaturate" {
let mode = surf.format().mode;
if crate::pixels::adjust_surface(&mut out, &crate::commands::desaturate_adjustment(), None, mode).is_err() {
if crate::pixels::adjust_surface(&mut out, &super::table::image::image_menu::desaturate_adjustment(), None, mode).is_err() {
return Ok(None);
}
} else if kind == "equalize" {
+133 -6
View File
@@ -659,10 +659,126 @@ pub fn artboard_document(doc: &Document, id: LayerId) -> Result<Option<Document>
Ok(Some(one))
}
/// Include Overlapping Areas: each visible artboard stacked above board `id` that overlaps it, as
/// the reference application writes it into the board's file: a plain group (no longer an
/// artboard) holding its layers over a new pixel layer "Background for <board>" filled with the
/// board's background where the two boards overlap, in source coordinates and bottom to top. A
/// group whose layers reach past its own board (effects, pixels outside the board, adjustments)
/// gets a hard mask to its board, which the artboard clipped them to.
///
/// The artboard painted its background beneath the group and then composited the group (its
/// blend mode, opacity, effects and masks) over it. A board with any of those keeps them on a
/// group of its own inside the plain group, above the background, so they still apply to its
/// layers only and its own mask keeps its feather and Layer Mask Hides Effects setting; the plain
/// group then carries nothing but the board clip.
fn overlapping_boards(doc: &Document, id: LayerId, rect: Rect) -> Vec<Layer> {
let above = doc.layers.iter().skip_while(|l| l.id != id).skip(1);
let mut out = Vec::new();
for l in above.filter(|l| l.visible) {
let Some(ab) = l.artboard().cloned() else { continue };
let overlap = ab.rect.intersect(&rect);
if overlap.is_empty() {
continue;
}
let mut board = l.clone();
if let LayerContent::Group(g) = &mut board.content {
g.artboard = None;
cut_pixels(&mut g.children, overlap, 0);
}
let bg = ab.background.rgba();
let mut group = if stacks_like_its_layers(&board) {
board
} else {
board.clipped = false;
let mut plain = Layer::group(l.name.clone(), vec![board]);
plain.label = l.label;
plain
};
if let (Some(bg), Some(children)) = (bg, group.children_mut()) {
let fmt = doc.pixel_format();
let mut surf = Surface::new(fmt);
surf.fill_rect(overlap, &photocraft_raster::from_rgba(&fmt, bg));
children.insert(0, Layer::new(format!("Background for {}", l.name), LayerContent::Raster(surf)));
}
// With the background in place: its pixels widen what the group's layers can reach.
let reach = photocraft_compose::change_bounds(&group, doc.bounds());
if reach.is_none_or(|r| !ab.rect.contains_rect(&r)) {
let mut mask = photocraft_doc::LayerMask::reveal_all();
mask.surface = Surface::with_default(PixelFormat::GRAY8, &[0.0]);
mask.surface.fill_rect(ab.rect, &[1.0]);
group.mask = Some(mask);
}
out.push(group);
}
out
}
/// Whether artboard `board` (already a plain group) composites over its background exactly as
/// its layers stacked over that background in one pass-through group do: pass-through (a Normal
/// group renders its layers on their own first, so a Multiply or Screen layer in it never blends
/// with the background), and no effects, masks, opacity, Blend If or other blending options of
/// its own, nor a mask the board clip would replace.
fn stacks_like_its_layers(board: &Layer) -> bool {
board.blend == photocraft_color::BlendMode::PassThrough
&& board.opacity >= 1.0
&& board.fill_opacity >= 1.0
&& board.mask.is_none()
&& board.vector_mask.is_none()
&& board.frame.is_none()
&& board.excluded_channels == 0
&& board.blend_if == photocraft_doc::BlendIf::default()
&& board.advanced == photocraft_doc::AdvancedBlending::default()
&& !photocraft_compose::effects::has_effects(board)
}
/// Cuts the pixel layers in `layers` (and in groups inside them, `depth` levels down so far) to
/// `keep`, as the reference application cuts an overlapping board's layers to the file. Layers
/// whose pixels can't be cut stay whole; the group's mask still hides what lies past its board.
/// A layer with effects, or inside a group with effects, stays whole too: pixels outside `keep`
/// can cast a shadow or glow into it.
fn cut_pixels(layers: &mut [Layer], keep: Rect, depth: usize) {
const MAX_DEPTH: usize = 64;
for l in layers {
if photocraft_compose::effects::has_effects(l) {
continue;
}
match &mut l.content {
LayerContent::Group(g) if depth < MAX_DEPTH => cut_pixels(&mut g.children, keep, depth + 1),
LayerContent::Raster(surf) => {
let r = surf.content_bounds().intersect(&keep);
let mut cut = Surface::with_default(surf.format(), &surf.default_pixel());
if !r.is_empty() {
let Ok(px) = surf.try_read_region(r) else { continue };
if cut.try_write_region(r, &px).is_err() {
continue;
}
}
*surf = cut;
}
_ => {}
}
}
}
/// [`artboard_document`] for each chosen board, all built before any file is written so a
/// board that can't be exported fails the export without leaving a partial set behind.
fn chosen_documents(doc: &Document, p: &Value) -> Result<Vec<Document>> {
chosen_artboards(doc, p).into_iter().filter_map(|id| artboard_document(doc, id).transpose()).collect()
/// board that can't be exported fails the export without leaving a partial set behind. With
/// `overlapping`, each file also holds the boards above that overlap it ([`overlapping_boards`]).
fn chosen_documents(doc: &Document, p: &Value, overlapping: bool) -> Result<Vec<Document>> {
let mut out = Vec::new();
for id in chosen_artboards(doc, p) {
let Some(mut one) = artboard_document(doc, id)? else { continue };
if overlapping && let Some(r) = doc.layer(id).and_then(|l| l.artboard()).map(|a| a.rect) {
// `artboard_document` has checked that the board's origin negates.
let (dx, dy) = (r.x0.saturating_neg(), r.y0.saturating_neg());
for mut group in overlapping_boards(doc, id, r) {
crate::commands::translate_layer(doc, &mut group, dx, dy);
crate::vector_cmds::translate_vectors(doc, &mut group, f64::from(dx), f64::from(dy));
one.layers.push(group);
}
}
out.push(one);
}
Ok(out)
}
/// The artboards an export covers: `"artboards": [ids]`, else all, top of the Layers panel first.
@@ -735,8 +851,16 @@ fn artboards_to_files(s: &mut Session, p: &Value) -> Result<Value> {
let save = SaveOpts::from_params(s, p, cmd)?;
let d = s.active().ok_or(EngineError::NoDocument)?;
let prefix = p.get("prefix").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name));
let overlapping = match p.get("content") {
None | Some(Value::Null) => true,
Some(v) => match v.as_str() {
Some("overlapping") => true,
Some("artboard") => false,
_ => return Err(bad(cmd, format!("`content` must be \"overlapping\" or \"artboard\", not {v}"))),
},
};
let doc = d.doc.clone();
let boards = chosen_documents(&doc, p)?;
let boards = chosen_documents(&doc, p, overlapping)?;
let names: Vec<&str> = boards.iter().map(|one| one.name.as_str()).collect();
let mut files = Vec::new();
for (one, name) in boards.iter().zip(artboard_file_stems(&prefix, &names, HYPHENATED_FORMATS.contains(&format.as_str()))) {
@@ -806,7 +930,7 @@ fn artboards_to_pdf(s: &mut Session, p: &Value) -> Result<Value> {
let mut pages = Vec::new();
// Pages go bottom artboard of the Layers panel first, as in the reference application (#13643);
// `chosen_documents` lists them top first, the order Artboards to Files keeps.
for one in chosen_documents(&doc, p)?.into_iter().rev() {
for one in chosen_documents(&doc, p, false)?.into_iter().rev() {
let buf = photocraft_compose::flatten(&one).over_background([1.0, 1.0, 1.0]);
let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::U8, true);
let mut flat = Document::new(&one.name, one.size, ColorMode::Rgb, SampleType::U8);
@@ -883,7 +1007,7 @@ pub fn specs() -> Vec<CommandSpec> {
"file.export.artboardsToFiles",
"Artboards to Files…",
&["File", "Export"],
r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name ("" = none),"artboards":[id]? (default all),"quality":0..12?} → {files} (one "<prefix><artboard name>.<format>" per board, no separator or index added: spaces become "-" in PNG, JPEG, BMP, Targa and TIFF and stay in PSD and other formats, characters a file name can't hold become "_", and a name an earlier board already took, ignoring case, gets "-2", "-3"…)"##,
r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name ("" = none),"content":"overlapping|artboard"="overlapping" (Include Overlapping Areas: a board's file also shows the visible boards above it where they overlap it, each as a plain group with a \"Background for <board>\" layer; artboard: Artboard Content Only),"artboards":[id]? (default all),"quality":0..12?} → {files} (one "<prefix><artboard name>.<format>" per board, no separator or index added: spaces become "-" in PNG, JPEG, BMP, Targa and TIFF and stay in PSD and other formats, characters a file name can't hold become "_", and a name an earlier board already took, ignoring case, gets "-2", "-3"…)"##,
export_artboards,
artboards_to_files
),
@@ -905,6 +1029,9 @@ mod file_names_tests;
#[path = "artboard_cmds/first_board_background_tests.rs"]
mod first_board_background_tests;
#[cfg(test)]
#[path = "artboard_cmds/overlapping_areas_tests.rs"]
mod overlapping_areas_tests;
#[cfg(test)]
#[path = "artboard_cmds/pdf_page_order_tests.rs"]
mod pdf_page_order_tests;
#[cfg(test)]
@@ -0,0 +1,340 @@
//! Artboards to Files › Include Overlapping Areas / Artboard Content Only (#13629): the boards
//! stacked above an exported board that overlap it show in its file (PNG pixels, PSD structure),
//! boards below never do, and the source document is left alone.
use super::*;
use photocraft_geom::Rect;
const RED: [u8; 3] = [220, 30, 30];
const BLUE: [u8; 3] = [30, 30, 220];
const WHITE: [u8; 3] = [255, 255, 255];
/// The measured test document: 800 x 400, transparent, bottom to top `Red Board` 0,0-200,150
/// (pixel layer `Red` at 20,20-120,100), `Blue Board` 120,30-320,230 (pixel layer `Blue` at
/// 130,40-230,140) and `Empty Board` 600,0-700,100, all with white backgrounds.
fn session(depth: u32) -> (Session, [u64; 3]) {
let mut s = Session::new();
s.execute("file.new", json!({"width": 800, "height": 400, "depth": depth, "background": "transparent"})).unwrap();
let board =
|s: &mut Session, name: &str, rect: [i64; 4]| s.execute("layer.new.artboard", json!({"rect": rect, "name": name})).unwrap()["layer"].as_u64().unwrap();
let red = board(&mut s, "Red Board", [0, 0, 200, 150]);
let blue = board(&mut s, "Blue Board", [120, 30, 200, 200]);
let empty = board(&mut s, "Empty Board", [600, 0, 100, 100]);
paint(&mut s, red, "Red", Rect::new(20, 20, 120, 100), RED);
paint(&mut s, blue, "Blue", Rect::new(130, 40, 230, 140), BLUE);
(s, [red, blue, empty])
}
/// A pixel layer `name` of `color` over `rect`, on top of board `board`'s layers.
fn paint(s: &mut Session, board: u64, name: &str, rect: Rect, color: [u8; 3]) {
s.edit(name, |doc, _| {
let fmt = doc.pixel_format();
let mut l = Layer::raster(name, fmt);
let [r, g, b] = color.map(|c| f32::from(c) / 255.0);
l.surface_mut().unwrap().fill_rect(rect, &photocraft_raster::from_rgba(&fmt, [r, g, b, 1.0]));
doc.layer_mut(LayerId(board)).unwrap().children_mut().unwrap().push(l);
Ok(())
})
.unwrap();
}
struct Out(std::path::PathBuf);
impl Out {
fn new(tag: &str) -> Self {
let dir = std::env::temp_dir().join(format!("photocraft-overlap-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
Out(dir)
}
fn dir(&self) -> String {
self.0.to_string_lossy().into_owned()
}
}
impl Drop for Out {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// Exports board `board` with `extra` params and reads the one file back.
fn export(s: &mut Session, out: &Out, board: u64, extra: Value) -> Document {
let mut p = json!({"dir": out.dir(), "prefix": "", "artboards": [board]});
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
let format = p.get("format").and_then(Value::as_str).unwrap_or("png").to_string();
let r = s.execute("file.export.artboardsToFiles", p).unwrap();
let files = r["files"].as_array().unwrap();
assert_eq!(files.len(), 1, "{r}");
let path = files[0].as_str().unwrap();
photocraft_io::import(&format!("x.{format}"), &std::fs::read(path).unwrap()).unwrap().document
}
/// The file's composite pixel at (x, y) as 8-bit RGBA.
fn px(d: &Document, x: i32, y: i32) -> [u8; 4] {
let flat = photocraft_compose::flatten(d);
let w = d.size.width as usize;
flat.px[y as usize * w + x as usize].map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)
}
fn rgb(p: [u8; 4]) -> [u8; 3] {
[p[0], p[1], p[2]]
}
fn names(layers: &[Layer]) -> Vec<&str> {
layers.iter().map(|l| l.name.as_str()).collect()
}
#[test]
fn include_overlapping_areas_is_the_default_and_shows_the_board_above() {
for depth in [8, 16] {
let (mut s, [red, _, _]) = session(depth);
let out = Out::new(&format!("default-{depth}"));
for extra in [json!({}), json!({"content": "overlapping"})] {
let f = export(&mut s, &out, red, extra.clone());
assert_eq!((f.size.width, f.size.height), (200, 150), "{depth} bit {extra}");
assert_eq!(rgb(px(&f, 150, 60)), BLUE, "{depth} bit {extra}: Blue's pixels");
assert_eq!(rgb(px(&f, 125, 35)), WHITE, "{depth} bit {extra}: Blue Board's background");
assert_eq!(rgb(px(&f, 125, 50)), WHITE, "{depth} bit {extra}: Blue Board's background");
assert_eq!(rgb(px(&f, 110, 50)), RED, "{depth} bit {extra}: Red stays red");
}
}
}
#[test]
fn artboard_content_only_keeps_the_board_on_its_own() {
let (mut s, [red, _, _]) = session(8);
let out = Out::new("content-only");
let f = export(&mut s, &out, red, json!({"content": "artboard"}));
assert_eq!(rgb(px(&f, 150, 60)), WHITE, "nothing of Blue Board");
assert_eq!(rgb(px(&f, 110, 50)), RED);
let psd = export(&mut s, &out, red, json!({"content": "artboard", "format": "psd"}));
assert_eq!(names(&psd.layers), ["Red Board"]);
}
#[test]
fn an_overlapping_psd_holds_the_board_above_as_a_plain_group_with_its_background() {
let (mut s, [red, _, _]) = session(8);
let out = Out::new("psd");
let psd = export(&mut s, &out, red, json!({"format": "psd"}));
assert_eq!((psd.size.width, psd.size.height), (200, 150));
// Bottom to top: the exported artboard, then the overlapping board as a plain group.
assert_eq!(names(&psd.layers), ["Red Board", "Blue Board"]);
let [board, group] = [&psd.layers[0], &psd.layers[1]];
assert_eq!(board.artboard().map(|a| a.rect), Some(Rect::new(0, 0, 200, 150)));
assert_eq!(names(board.children().unwrap()), ["Red"]);
assert!(matches!(&group.content, LayerContent::Group(g) if g.artboard.is_none()), "no longer an artboard");
let kids = group.children().unwrap();
assert_eq!(names(kids), ["Background for Blue Board", "Blue"]);
// Blue (130,40-230,140 in the source) is cut to the file: 130,40-200,140.
let blue = photocraft_compose::bounds::content_bounds(kids[1].surface().unwrap());
assert_eq!(blue, Rect::new(130, 40, 200, 140));
// The background covers where the boards overlap: 120..200 x 30..150.
let bg = photocraft_compose::bounds::content_bounds(kids[0].surface().unwrap());
assert_eq!(bg, Rect::new(120, 30, 200, 150));
assert_eq!(rgb(px(&psd, 150, 60)), BLUE);
assert_eq!(rgb(px(&psd, 125, 35)), WHITE);
assert_eq!(rgb(px(&psd, 110, 50)), RED);
}
#[test]
fn boards_below_do_not_show_in_either_mode() {
let (mut s, [_, blue, _]) = session(8);
// A transparent Blue Board shows whatever leaks in from Red Board's white background below.
s.execute("layer.artboard.set", json!({"layer": blue, "background": "transparent"})).unwrap();
let out = Out::new("below");
for content in ["overlapping", "artboard"] {
let f = export(&mut s, &out, blue, json!({"content": content}));
assert_eq!((f.size.width, f.size.height), (200, 200), "{content}");
// Source (125,35): Red Board's background, outside Blue's pixels.
assert_eq!(px(&f, 5, 5)[3], 0, "{content}: nothing of Red Board");
assert_eq!(rgb(px(&f, 30, 30)), BLUE, "{content}");
let psd = export(&mut s, &out, blue, json!({"content": content, "format": "psd"}));
assert_eq!(names(&psd.layers), ["Blue Board"], "{content}");
}
}
#[test]
fn the_source_document_is_unchanged_and_gets_no_history_entry() {
let (mut s, [red, blue, _]) = session(8);
let out = Out::new("source");
for content in ["overlapping", "artboard"] {
for board in [red, blue] {
let d = s.active().unwrap();
let (before, rev, past) = (d.doc.clone(), d.revision, d.history.past_len());
export(&mut s, &out, board, json!({"content": content, "format": "psd"}));
let d = s.active().unwrap();
assert!(d.doc == before, "{content} changed the document");
assert_eq!((d.revision, d.history.past_len()), (rev, past), "{content}");
}
}
}
/// The artboard clipped its layers to the board; as a plain group in the file they still stop
/// at the board's edge, so Blue pixels outside Blue Board never cover Red Board.
#[test]
fn the_layers_of_the_board_above_stay_inside_their_board() {
let (mut s, [red, blue, _]) = session(8);
paint(&mut s, blue, "Spill", Rect::new(100, 45, 125, 55), BLUE);
let out = Out::new("spill");
for format in ["png", "psd"] {
let f = export(&mut s, &out, red, json!({"format": format}));
assert_eq!(rgb(px(&f, 110, 50)), RED, "{format}: outside Blue Board");
assert_eq!(rgb(px(&f, 122, 50)), BLUE, "{format}: inside Blue Board");
assert_eq!(rgb(px(&f, 150, 60)), BLUE, "{format}");
}
}
/// A layer that covers the whole canvas (a solid colour fill) in the board above is clipped to
/// that board by a mask on the group, so it can't paint over the rest of the exported board.
#[test]
fn a_fill_layer_in_the_board_above_stays_inside_its_board() {
let (mut s, [red, blue, _]) = session(8);
s.edit("Fill", |doc, _| {
let fill = Layer::new("Green", LayerContent::Fill(photocraft_doc::Fill::Solid(Color::rgb(0.0, 1.0, 0.0))));
doc.layer_mut(LayerId(blue)).unwrap().children_mut().unwrap().push(fill);
Ok(())
})
.unwrap();
let out = Out::new("fill");
for format in ["png", "psd"] {
let f = export(&mut s, &out, red, json!({"format": format}));
assert_eq!(rgb(px(&f, 110, 50)), RED, "{format}: outside Blue Board");
assert_eq!(rgb(px(&f, 10, 140)), WHITE, "{format}: outside Blue Board");
assert_eq!(rgb(px(&f, 150, 60)), [0, 255, 0], "{format}: inside Blue Board");
}
}
/// A layer of the board above that lies outside the exported board still casts its drop shadow
/// into it, as it does in the document: its pixels are not cut away before the effect is built.
#[test]
fn a_shadow_cast_into_the_exported_board_from_outside_it_still_shows() {
use photocraft_doc::effects::{Contour, FxCommon, Shadow};
let (mut s, [red, blue, _]) = session(8);
// Caster at 210..240 x 160..180 (in Blue Board, outside Red Board); its shadow, 40 px up and
// to the left, falls on 170..200 x 120..140, inside Red Board.
paint(&mut s, blue, "Caster", Rect::new(210, 160, 240, 180), [0, 160, 0]);
s.edit("Shadow", |doc, _| {
let caster = doc.layer_mut(LayerId(blue)).unwrap().children_mut().unwrap().last_mut().unwrap();
caster.effects.items.push(photocraft_doc::Effect::DropShadow(Shadow {
common: FxCommon::new(photocraft_color::BlendMode::Normal, 1.0),
color: Color::rgb(0.0, 0.0, 0.0),
angle: -45.0,
use_global_light: false,
distance: 40.0_f32.hypot(40.0),
spread: 0.0,
size: 0.0,
contour: Contour::Linear,
anti_alias: false,
noise: 0.0,
knocks_out: true,
}));
Ok(())
})
.unwrap();
let source = px(&s.active().unwrap().doc, 185, 130);
assert_eq!(rgb(source), [0, 0, 0], "the shadow lands there in the document");
let out = Out::new("shadow");
for format in ["png", "psd"] {
let f = export(&mut s, &out, red, json!({"format": format}));
assert_eq!(px(&f, 185, 130), source, "{format}");
assert_eq!(rgb(px(&f, 110, 50)), RED, "{format}");
}
}
/// Not measured (keeps today's behaviour): a hidden board above shows nothing.
#[test]
fn a_hidden_board_above_does_not_show() {
let (mut s, [red, blue, _]) = session(8);
s.edit("Hide", |doc, _| {
doc.layer_mut(LayerId(blue)).unwrap().visible = false;
Ok(())
})
.unwrap();
let out = Out::new("hidden");
let f = export(&mut s, &out, red, json!({}));
assert_eq!(rgb(px(&f, 150, 60)), WHITE);
let psd = export(&mut s, &out, red, json!({"format": "psd"}));
assert_eq!(names(&psd.layers), ["Red Board"]);
}
#[test]
fn a_bad_content_value_is_rejected_without_writing_anything() {
let (mut s, _) = session(8);
let out = Out::new("bad");
for bad in [json!("both"), json!(""), json!(1), json!(true), json!(["overlapping"])] {
let d = s.active().unwrap();
let (before, past) = (d.doc.clone(), d.history.past_len());
let err = s.execute("file.export.artboardsToFiles", json!({"dir": out.dir(), "content": bad})).unwrap_err();
assert!(matches!(err, EngineError::BadParams { .. }), "{bad}: {err}");
let d = s.active().unwrap();
assert!(d.doc == before && d.history.past_len() == past, "{bad}");
assert_eq!(std::fs::read_dir(&out.0).unwrap().count(), 0, "{bad}: nothing written");
}
}
#[test]
fn the_params_doc_names_the_option() {
let spec = specs().into_iter().find(|c| c.id == "file.export.artboardsToFiles").unwrap();
assert!(spec.params.contains(r#""content":"overlapping|artboard"="overlapping""#), "{}", spec.params);
}
/// The source document's composite pixel at (x, y); Red Board sits at the canvas origin, so its
/// file pixels line up with these.
fn source_px(s: &Session, x: i32, y: i32) -> [u8; 4] {
px(&s.active().unwrap().doc, x, y)
}
/// A mask on the board above keeps hiding what it hid when the export clips that board to its
/// rect: the board clip is added beside it instead of replacing it.
#[test]
fn a_mask_on_the_board_above_still_hides_its_part() {
let (mut s, [red, blue, _]) = session(8);
s.edit("Mask", |doc, _| {
let board = doc.layer_mut(LayerId(blue)).unwrap();
// A canvas-wide fill reaches past the board, so the export clips the board to its rect.
let fill = Layer::new("Green", LayerContent::Fill(photocraft_doc::Fill::Solid(Color::rgb(0.0, 1.0, 0.0))));
board.children_mut().unwrap().insert(0, fill);
let mut mask = photocraft_doc::LayerMask::reveal_all();
mask.surface.fill_rect(Rect::new(140, 50, 160, 70), &[0.0]);
board.mask = Some(mask);
Ok(())
})
.unwrap();
assert_eq!(rgb(source_px(&s, 150, 60)), WHITE, "the mask shows Blue Board's background there");
let out = Out::new("board-mask");
for format in ["png", "psd"] {
let f = export(&mut s, &out, red, json!({"format": format}));
for (x, y) in [(150, 60), (145, 55), (170, 60), (125, 140), (110, 50), (10, 140)] {
assert_eq!(px(&f, x, y), source_px(&s, x, y), "{format} at ({x},{y})");
}
}
}
/// A Normal board renders its layers on their own before they go over its background, so a
/// Multiply layer in it does not blend with that background; the export keeps the board as a
/// group of its own above the background layer instead of stacking its layers on it.
#[test]
fn a_multiply_layer_in_a_normal_board_above_does_not_blend_with_its_background() {
let (mut s, [red, blue, _]) = session(8);
s.edit("Normal", |doc, _| {
let board = doc.layer_mut(LayerId(blue)).unwrap();
board.blend = photocraft_color::BlendMode::Normal;
if let LayerContent::Group(g) = &mut board.content {
g.artboard.as_mut().unwrap().background = photocraft_doc::ArtboardBackground::Custom(Color::rgb(0.0, 1.0, 0.0));
}
board.children_mut().unwrap().last_mut().unwrap().blend = photocraft_color::BlendMode::Multiply;
Ok(())
})
.unwrap();
assert_eq!(rgb(source_px(&s, 150, 60)), BLUE, "Blue, rendered on its own, covers the green background");
let out = Out::new("normal-multiply");
for format in ["png", "psd"] {
let f = export(&mut s, &out, red, json!({"format": format}));
for (x, y) in [(150, 60), (125, 35), (110, 50)] {
assert_eq!(px(&f, x, y), source_px(&s, x, y), "{format} at ({x},{y})");
}
}
}
+5
View File
@@ -23,6 +23,8 @@ use serde_json::{Value, json};
use crate::commands::CommandSpec;
use crate::{DocState, EngineError, Result, Session};
#[cfg(test)]
mod apply_image_lock_transparency_tests;
#[cfg(test)]
mod tests;
@@ -119,6 +121,9 @@ mod targeting;
mod tone_target;
mod view;
#[cfg(test)]
mod apply_image_locked_layer_tests;
use calc::{apply_image, calculations};
use manage::{delete_channel, duplicate_channel, move_channel, new_channel, new_spot, options, rename_channel, set_visible};
use planes::edit_mode;
@@ -0,0 +1,103 @@
//! Apply Image on a layer with Lock Transparent Pixels: the lock acts as Preserve Transparency.
use super::*;
/// A 40 x 20 document whose layer "Top" is empty except a half-transparent green 10 x 10 square
/// at (10,5), and a second document "source" filled with 50% gray.
fn session(depth: u32) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 40, "height": 20, "depth": depth})).unwrap();
s.execute("layer.new.layer", json!({"name": "Top"})).unwrap();
s.execute("select.rect", json!({"x": 10, "y": 5, "width": 10, "height": 10, "mode": "replace"})).unwrap();
s.execute("edit.fill", json!({"contents": "color", "color": "#00ff00", "opacity": 50})).unwrap();
s.execute("select.deselect", json!({})).unwrap();
s.execute("file.new", json!({"width": 40, "height": 20, "depth": depth, "name": "source"})).unwrap();
s.execute("edit.fill", json!({"contents": "color", "color": "#808080"})).unwrap();
s.set_active(0);
s
}
fn layer(s: &Session) -> &Layer {
let d = s.active().unwrap();
d.doc.layer(d.active_layer.unwrap()).unwrap()
}
fn pixels(s: &Session) -> Vec<f32> {
let d = s.active().unwrap();
layer(s).surface().unwrap().read_region(d.doc.bounds())
}
fn px(s: &Session, x: i32, y: i32) -> Vec<f32> {
layer(s).surface().unwrap().pixel(x, y)
}
fn close(a: &[f32], b: &[f32]) -> bool {
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-5)
}
/// The layer's pixels after Apply Image with `extra` params, unlocked and with Preserve transparency.
fn preserved(depth: u32, extra: &Value) -> Vec<f32> {
let mut s = session(depth);
let mut p = json!({"source": {"document": 1}, "blending": "normal", "preserveTransparency": true});
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
s.execute("image.applyImage", p).unwrap();
pixels(&s)
}
#[test]
fn transparency_lock_acts_as_preserve_transparency() {
for depth in [8, 16, 32] {
for extra in [json!({}), json!({"blending": "multiply"}), json!({"opacity": 50})] {
let want = preserved(depth, &extra);
let mut s = session(depth);
s.execute("layer.lockLayers", json!({"transparency": true})).unwrap();
let mut p = json!({"source": {"document": 1}, "blending": "normal"});
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
s.execute("image.applyImage", p).unwrap();
assert!(close(&pixels(&s), &want), "{depth} bit {extra}: the lock must keep the layer's transparency");
assert_eq!(px(&s, 30, 2), vec![0.0; 4], "{depth} bit {extra}: a transparent pixel stays transparent");
assert!((px(&s, 15, 10)[3] - px(&session(depth), 15, 10)[3]).abs() < 1e-5, "{depth} bit {extra}: the square keeps its alpha");
}
}
}
#[test]
fn transparency_lock_inside_a_selection_acts_as_preserve_transparency() {
let sel = |s: &mut Session| s.execute("select.rect", json!({"x": 0, "y": 0, "width": 15, "height": 20, "mode": "replace"})).unwrap();
let mut want = session(8);
sel(&mut want);
want.execute("image.applyImage", json!({"source": {"document": 1}, "preserveTransparency": true})).unwrap();
let mut s = session(8);
s.execute("layer.lockLayers", json!({"transparency": true})).unwrap();
sel(&mut s);
s.execute("image.applyImage", json!({"source": {"document": 1}})).unwrap();
assert!(close(&pixels(&s), &pixels(&want)));
assert_eq!(px(&s, 2, 2), vec![0.0; 4]);
}
#[test]
fn lock_stays_on_and_one_history_step_is_added() {
let mut s = session(8);
s.execute("layer.lockLayers", json!({"transparency": true})).unwrap();
let steps = s.active().unwrap().history.past_len();
s.execute("image.applyImage", json!({"source": {"document": 1}})).unwrap();
assert!(layer(&s).locks.transparency, "the lock stays on");
assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "one Apply Image step");
s.undo();
assert!(close(&pixels(&s), &pixels(&session(8))), "undo restores the layer");
}
#[test]
fn unlocked_layer_keeps_source_over() {
for depth in [8, 16, 32] {
let mut s = session(depth);
s.execute("image.applyImage", json!({"source": {"document": 1}, "blending": "normal"})).unwrap();
let g = 128.0 / 255.0;
let p = px(&s, 30, 2);
assert!(p[..3].iter().all(|v| (v - g).abs() < 0.003) && (p[3] - 1.0).abs() < 1e-5, "{depth} bit: {p:?}");
}
}
@@ -0,0 +1,149 @@
//! Apply Image on a fully locked or pixel-locked layer: it applies, and the layer keeps its
//! transparency as with Preserve transparency (#14476).
use super::*;
/// The spec's test document "target" (400 x 300): layer "Top" is empty except a 100 x 100 square
/// at (150,100) of 0/255/0 at alpha 128. Document "source" is 128/128/128 on the left half and
/// white on the right half.
fn session(depth: u32) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 400, "height": 300, "depth": depth, "name": "target"})).unwrap();
s.execute("layer.new.layer", json!({"name": "Top"})).unwrap();
s.execute("select.rect", json!({"x": 150, "y": 100, "width": 100, "height": 100, "mode": "replace"})).unwrap();
s.execute("edit.fill", json!({"contents": "color", "color": "#00ff00", "opacity": 128.0 / 255.0 * 100.0})).unwrap();
s.execute("select.deselect", json!({})).unwrap();
s.execute("file.new", json!({"width": 400, "height": 300, "depth": depth, "name": "source"})).unwrap();
s.execute("edit.fill", json!({"contents": "color", "color": "#ffffff"})).unwrap();
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 200, "height": 300, "mode": "replace"})).unwrap();
s.execute("edit.fill", json!({"contents": "color", "color": "#808080"})).unwrap();
s.execute("select.deselect", json!({})).unwrap();
s.set_active(0);
s
}
fn apply() -> Value {
json!({"source": {"document": 1}, "blending": "normal", "opacity": 100})
}
fn layer(s: &Session) -> &Layer {
let d = s.active().unwrap();
d.doc.layer(d.active_layer.unwrap()).unwrap()
}
fn pixels(s: &Session) -> Vec<f32> {
let d = s.active().unwrap();
layer(s).surface().unwrap().read_region(d.doc.bounds())
}
fn px(s: &Session, x: i32, y: i32) -> Vec<f32> {
layer(s).surface().unwrap().pixel(x, y)
}
fn close(a: &[f32], b: &[f32]) -> bool {
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-5)
}
fn lock(s: &mut Session, locks: &Value) {
s.execute("layer.setProps", json!({"locks": locks})).unwrap();
}
const LOCKS: [&str; 2] = [r#"{"all": true}"#, r#"{"pixels": true}"#];
fn locks() -> impl Iterator<Item = Value> {
LOCKS.iter().map(|l| serde_json::from_str(l).unwrap())
}
#[test]
fn a_locked_layer_takes_the_image_in_one_step_and_keeps_its_transparency() {
for depth in [8, 16, 32] {
for locks in locks() {
let mut s = session(depth);
lock(&mut s, &locks);
let before = px(&s, 175, 125);
let steps = s.active().unwrap().history.past_len();
s.execute("image.applyImage", apply()).unwrap();
let d = s.active().unwrap();
assert_eq!(d.history.past_len(), steps + 1, "{depth} bit {locks}: one history step");
assert_eq!(d.history.undo_label(), Some("Apply Image"), "{depth} bit {locks}");
assert!(!close(&px(&s, 175, 125), &before), "{depth} bit {locks}: (175,125) changes");
assert_eq!(px(&s, 50, 50), vec![0.0; 4], "{depth} bit {locks}: (50,50) stays transparent");
assert!((px(&s, 175, 125)[3] - before[3]).abs() < 1e-5, "{depth} bit {locks}: the square keeps its alpha");
}
}
}
#[test]
fn a_locked_layer_gets_the_preserve_transparency_result() {
for depth in [8, 16, 32] {
for extra in [json!({}), json!({"blending": "multiply"}), json!({"opacity": 50})] {
let with = |p: Value| {
let mut p = p;
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
p
};
let mut want = session(depth);
let mut p = with(apply());
p["preserveTransparency"] = json!(true);
want.execute("image.applyImage", p).unwrap();
for locks in locks() {
let mut s = session(depth);
lock(&mut s, &locks);
s.execute("image.applyImage", with(apply())).unwrap();
assert!(close(&pixels(&s), &pixels(&want)), "{depth} bit {locks} {extra}");
}
}
}
}
#[test]
fn the_locks_stay_and_other_commands_keep_refusing() {
for locks in locks() {
let mut s = session(8);
lock(&mut s, &locks);
let set = layer(&s).locks;
s.execute("image.applyImage", apply()).unwrap();
assert_eq!(layer(&s).locks, set, "{locks}: the lock flags are unchanged");
let after = pixels(&s);
let steps = s.active().unwrap().history.past_len();
let fill = s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap_err().to_string();
assert!(fill.contains("is locked"), "{locks}: Fill refuses: {fill}");
let stroke = s.execute("paint.stroke", json!({"points": [[160, 110], [240, 190]], "size": 20})).unwrap_err().to_string();
assert!(stroke.contains("is locked"), "{locks}: a brush stroke refuses: {stroke}");
assert!(close(&pixels(&s), &after), "{locks}: nothing else painted");
assert_eq!(s.active().unwrap().history.past_len(), steps, "{locks}: no more steps");
s.undo();
assert!(close(&pixels(&s), &pixels(&session(8))), "{locks}: undo restores the layer");
}
}
#[test]
fn a_lock_from_a_group_still_refuses() {
// Not measured in the reference application: keeps today's refusal, also when the layer is
// locked itself as well.
for own in [None, Some(json!({"pixels": true})), Some(json!({"all": true}))] {
let mut s = session(8);
let top = s.active().unwrap().active_layer.unwrap();
if let Some(own) = &own {
lock(&mut s, own);
}
s.execute("layer.new.groupFromLayers", json!({})).unwrap();
lock(&mut s, &json!({"all": true}));
s.set_active_layer(Some(top));
let before = pixels(&s);
let err = s.execute("image.applyImage", apply()).unwrap_err().to_string();
assert!(err.contains("is locked"), "{own:?}: {err}");
assert!(close(&pixels(&s), &before), "{own:?}");
}
}
#[test]
fn an_unlocked_layer_keeps_source_over() {
let mut s = session(8);
s.execute("image.applyImage", apply()).unwrap();
let p = px(&s, 50, 50);
let g = 128.0 / 255.0;
assert!(p[..3].iter().all(|v| (v - g).abs() < 0.003) && (p[3] - 1.0).abs() < 1e-5, "{p:?}");
}
@@ -0,0 +1,104 @@
//! #14473: Apply Image with Preserve Transparency gives a semi-transparent pixel the full blend
//! result and keeps its alpha, as the reference application does.
use crate::Session;
use serde_json::{Value, json};
/// Target "target" (document 0): white Background, layer "Top" transparent except a 0/255/0
/// square at alpha 128 over (10,4)-(19,13). Source "source" (document 1): 128/128/128.
fn session(depth: u32) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 40, "height": 20, "depth": depth, "name": "target"})).unwrap();
s.execute("file.new", json!({"width": 40, "height": 20, "depth": depth, "name": "source"})).unwrap();
s.execute("edit.fill", json!({"color": "#808080"})).unwrap();
s.set_active(0);
s.execute("layer.new.layer", json!({"name": "Top"})).unwrap();
s.execute("select.rect", json!({"x": 10, "y": 4, "width": 10, "height": 10, "mode": "replace"})).unwrap();
s.execute("edit.fill", json!({"color": "#00ff00", "opacity": 50})).unwrap();
s.execute("select.deselect", json!({})).unwrap();
s
}
fn px(s: &Session, x: i32, y: i32) -> Vec<f32> {
let d = s.active().unwrap();
d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().pixel(x, y)
}
fn apply(s: &mut Session, extra: Value) {
let mut p = json!({"source": {"document": 1, "layer": "merged", "channel": "composite"}});
if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) {
p.extend(extra.clone());
}
s.execute("image.applyImage", p).unwrap();
}
/// Checks RGBA in 0..=255 levels, one level of slack (the fill's 50% alpha is 127.5).
fn assert_rgba(got: &[f32], want: [f32; 4], what: &str) {
let got: Vec<f32> = got.iter().map(|v| v * 255.0).collect();
assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() <= 1.01), "{what}: {got:?}, want {want:?}");
}
const GRAY: f32 = 128.0;
const HALF: f32 = 127.5;
#[test]
fn normal_with_preserve_transparency_takes_the_source_and_keeps_alpha() {
for depth in [8, 16, 32] {
let mut s = session(depth);
apply(&mut s, json!({"blending": "normal", "preserveTransparency": true}));
assert_rgba(&px(&s, 15, 8), [GRAY, GRAY, GRAY, HALF], &format!("depth {depth}: green pixel"));
assert_rgba(&px(&s, 2, 2), [0.0; 4], &format!("depth {depth}: transparent pixel"));
}
}
#[test]
fn multiply_with_preserve_transparency_blends_fully_and_keeps_alpha() {
for depth in [8, 16, 32] {
let mut s = session(depth);
apply(&mut s, json!({"blending": "multiply", "preserveTransparency": true}));
assert_rgba(&px(&s, 15, 8), [0.0, GRAY, 0.0, HALF], &format!("depth {depth}: green pixel"));
assert_rgba(&px(&s, 2, 2), [0.0; 4], &format!("depth {depth}: transparent pixel"));
}
}
#[test]
fn opacity_and_selection_still_scale_the_preserved_blend() {
let mut s = session(8);
// 50% Normal: the colour moves half way to the source, the alpha stays.
apply(&mut s, json!({"blending": "normal", "opacity": 50, "preserveTransparency": true}));
assert_rgba(&px(&s, 15, 8), [64.0, 191.5, 64.0, HALF], "opacity 50");
s.undo();
// Outside the selection nothing changes.
s.execute("select.rect", json!({"x": 10, "y": 4, "width": 5, "height": 10, "mode": "replace"})).unwrap();
apply(&mut s, json!({"blending": "normal", "preserveTransparency": true}));
assert_rgba(&px(&s, 12, 8), [GRAY, GRAY, GRAY, HALF], "inside the selection");
assert_rgba(&px(&s, 17, 8), [0.0, 255.0, 0.0, HALF], "outside the selection");
}
#[test]
fn a_mask_still_scales_the_preserved_blend() {
let mut s = session(8);
// A 50% gray alpha channel as the mask halves the effect, like 50% opacity.
s.execute("channel.new", json!({"fill": "white"})).unwrap();
s.execute("channel.target", json!({"channel": 0})).unwrap();
s.execute("edit.fill", json!({"color": "#808080"})).unwrap();
s.execute("channel.target", json!({"channel": "composite"})).unwrap();
apply(&mut s, json!({"blending": "normal", "preserveTransparency": true, "mask": {"document": 0, "channel": 0}}));
assert_rgba(&px(&s, 15, 8), [64.0, 191.5, 64.0, HALF], "mask at 50%");
}
#[test]
fn without_preserve_transparency_the_results_stay() {
let mut s = session(8);
apply(&mut s, json!({"blending": "normal"}));
assert_rgba(&px(&s, 15, 8), [GRAY, GRAY, GRAY, 255.0], "normal, green pixel");
assert_rgba(&px(&s, 2, 2), [GRAY, GRAY, GRAY, 255.0], "normal, transparent pixel");
s.undo();
apply(&mut s, json!({"blending": "multiply"}));
assert_rgba(&px(&s, 15, 8), [64.0, GRAY, 64.0, 255.0], "multiply, green pixel");
assert_rgba(&px(&s, 2, 2), [GRAY, GRAY, GRAY, 255.0], "multiply, transparent pixel");
s.undo();
apply(&mut s, json!({"blending": "normal", "opacity": 50}));
assert_rgba(&px(&s, 15, 8), [85.0, 170.0, 85.0, 191.5], "normal 50%, green pixel");
assert_rgba(&px(&s, 2, 2), [GRAY, GRAY, GRAY, HALF], "normal 50%, transparent pixel");
}
+32 -8
View File
@@ -4,6 +4,10 @@ use super::refs::{Blending, bad, doc_index, mask_plane, source, source_spec};
use super::targeting::{Target, is_channel_target, is_spot_target, target_of, target_surface};
use super::{AlphaChannel, ColorMode, EngineError, Result, SelectionMode, Session, Value, json, sel};
#[cfg(test)]
#[path = "apply_image_preserve_tests.rs"]
mod apply_image_preserve_tests;
// ---------------------------------------------------------------------------------------------
// Apply Image / Calculations
@@ -55,8 +59,21 @@ pub(super) fn apply_image(s: &mut Session, p: &Value) -> Result<Value> {
return Ok(());
}
let id = layer.ok_or_else(|| EngineError::Other("no active layer".into()))?;
// Lock Transparent Pixels works as Preserve Transparency, ticked or not.
let preserve = preserve || doc.effective_locks(id).transparency;
let fmt = doc.pixel_format();
let surf = crate::commands::paint_surface(doc, id, &Value::Null)?;
// A fully locked or pixel-locked layer still takes the image, as in the reference
// application, and keeps its transparency as with Preserve transparency. A lock that comes
// from a group around it still refuses, through `paint_surface`.
let own = doc.layer(id).map(|l| l.locks).unwrap_or_default();
let groups = doc.path_of(id).map_or_else(Default::default, |p| doc.locks_at(p.get(..p.len().saturating_sub(1)).unwrap_or_default()));
let locked = (own.pixels || own.all) && !(groups.pixels || groups.all);
let preserve = preserve || locked;
let surf = if locked {
doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.surface_mut().ok_or_else(|| EngineError::Other("not a pixel layer".into()))?
} else {
crate::commands::paint_surface(doc, id, &Value::Null)?
};
let sf = surf.format();
if sf != fmt {
return Err(EngineError::Other("the target layer's format doesn't match the document".into()));
@@ -66,11 +83,9 @@ pub(super) fn apply_image(s: &mut Session, p: &Value) -> Result<Value> {
let mut v = surf.read_region(area);
for (i, px) in v.chunks_exact_mut(n).enumerate() {
let base_a = if sf.alpha { px[colors].clamp(0.0, 1.0) } else { 1.0 };
let mut w = weight(i);
if preserve {
w *= base_a;
}
if w <= 0.0 {
let w = weight(i);
// Preserve Transparency leaves transparent pixels as they are.
if w <= 0.0 || (preserve && base_a <= 0.0) {
continue;
}
// Painted over the layer like a brush: the blend only acts where the layer has
@@ -85,8 +100,17 @@ pub(super) fn apply_image(s: &mut Session, p: &Value) -> Result<Value> {
let k = if src_mode == ColorMode::Cmyk && sf.mode != ColorMode::Cmyk { src.get(3).map_or(1.0, |pl| tone(src_mode, pl[i])) } else { 1.0 };
let top = if src.len() > 1 { tone(src_mode, src.get(c).unwrap_or(&src[0])[i]) * k } else { src[0][i] };
let base = tone(sf.mode, *b);
let blended = top + (blending.apply(base, top) - top) * base_a;
*b = tone(sf.mode, if preserve { base + (blended - base) * w } else { (w * blended + base_a * (1.0 - w) * base) / out_a });
// With Preserve Transparency the colour takes the full blend and only the alpha
// stays the layer's (a pixel at 50% alpha turns fully to the source in Normal).
*b = tone(
sf.mode,
if preserve {
base + (blending.apply(base, top) - base) * w
} else {
let blended = top + (blending.apply(base, top) - top) * base_a;
(w * blended + base_a * (1.0 - w) * base) / out_a
},
);
}
if sf.alpha {
px[colors] = out_a;
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,35 @@
use super::{SPECS, command_specs};
/// Menus, the Command Palette and the automation docs list commands in registry order, so the
/// order is part of the behaviour. `command_ids.txt` pins it; regenerate the file from main when
/// rebasing, adding each new command's id after its predecessor. With `PHOTOCRAFT_WRITE_COMMAND_IDS`
/// set, the test writes the file from the registry instead; review the diff before committing it.
const HINT: &str = "\nadd the id to src/cmd/command_ids.txt, or run this test with PHOTOCRAFT_WRITE_COMMAND_IDS=1 and review the diff";
#[test]
fn registered_command_ids_keep_their_order() {
let ids: Vec<&str> = command_specs().iter().map(|c| c.id).collect();
if std::env::var_os("PHOTOCRAFT_WRITE_COMMAND_IDS").is_some() {
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/src/cmd/command_ids.txt");
std::fs::write(path, ids.iter().map(|id| format!("{id}\n")).collect::<String>()).expect("write command_ids.txt");
return;
}
let expected: Vec<&str> = include_str!("command_ids.txt").lines().collect();
if let Some(i) = ids.iter().zip(&expected).position(|(a, b)| a != b) {
panic!("command {i} is {} where {} was registered{}{HINT}", ids[i], expected[i], fragment_of(i));
}
assert_eq!(ids.len(), expected.len(), "the number of registered commands changed{}{HINT}", fragment_of(ids.len().min(expected.len())));
}
/// Names the fragment that registers command `index`, for the failure message.
fn fragment_of(index: usize) -> String {
let mut first = 0;
for (name, specs) in SPECS {
let len = specs().len();
if index < first + len {
return format!(" (fragment `{name}`, commands {first}..{})", first + len);
}
first += len;
}
String::new()
}
+29 -8
View File
@@ -86,19 +86,40 @@ fn parse(st: &DocState, p: &Value, cmd: &str) -> Result<Option<HistorySource>> {
/// Photoshop refuses too, "the current canvas size does not match that of the history state"
/// (its message as users report it; Adobe's help doesn't document the case).
pub(crate) fn paint_source(st: &DocState, p: &Value, cmd: &str) -> Result<Arc<Document>> {
checked_source(st, p, cmd)?.map_err(|why| {
EngineError::Other(match why {
SourceRefusal::NoSource => "the History Brush source was deleted: set a new source in the History panel".into(),
SourceRefusal::CanvasSize { source } => format!(
"the current canvas size ({}×{}) does not match that of the History Brush source ({}×{}): set a source of this size in the History panel",
st.doc.size.width, st.doc.size.height, source.width, source.height
),
})
})
}
/// Why [`checked_source`] found no source to paint from, so each tool can word it (#12638).
#[derive(Debug)]
pub(crate) enum SourceRefusal {
/// No `state` or `snapshot` passed, and the History panel's source was deleted.
NoSource,
/// The source has another canvas size than the document.
CanvasSize { source: photocraft_geom::Size },
}
/// [`paint_source`] with the refusal left to the caller: bad params and a `state` or `snapshot`
/// that is gone are errors, the two refusals the tools word themselves are the inner `Err`.
pub(crate) fn checked_source(st: &DocState, p: &Value, cmd: &str) -> Result<std::result::Result<Arc<Document>, SourceRefusal>> {
let doc = match parse(st, p, cmd)? {
Some(src) => source_of(st, src).ok_or_else(|| EngineError::Other("that history state or snapshot is gone".into()))?,
None => source(st)
.and_then(|src| source_of(st, src))
.ok_or_else(|| EngineError::Other("the History Brush source was deleted: set a new source in the History panel".into()))?,
None => match source(st).and_then(|src| source_of(st, src)) {
Some(doc) => doc,
None => return Ok(Err(SourceRefusal::NoSource)),
},
};
if doc.size != st.doc.size {
return Err(EngineError::Other(format!(
"the current canvas size ({}×{}) does not match that of the History Brush source ({}×{}): set a source of this size in the History panel",
st.doc.size.width, st.doc.size.height, doc.size.width, doc.size.height
)));
return Ok(Err(SourceRefusal::CanvasSize { source: doc.size }));
}
Ok(doc)
Ok(Ok(doc))
}
/// The History Brush's refusals after Image › Mode, with Photoshop's alert texts (#12842): only
+44 -10
View File
@@ -8,12 +8,15 @@
//! Background over the background colour where the quad reaches past the image, and pixels outside
//! the quad are deleted (Photoshop's Perspective Crop has no Delete Cropped Pixels option).
//!
//! Type, shape, fill and smart object layers are rasterized first: a projective map has no
//! editable equivalent for them. Vector masks, paths, notes, slices and guides follow the affine
//! map closest to the homography (exact when the quad is a parallelogram).
//! A document holding a type layer or a smart object anywhere, and a Bitmap mode document, are
//! refused with the tool's alerts ([`UNSUPPORTED_LAYERS_ERROR`] and [`BITMAP_MODE_ERROR`], #11799)
//! before anything is rasterized or warped, so the document stays exactly as it was. Shape and fill
//! layers are rasterized first: a projective map has no editable equivalent for them (keeping them
//! live is #11800). Vector masks, paths, notes, slices and guides follow the affine map closest to
//! the homography (exact when the quad is a parallelogram).
use photocraft_algo::transform::{Homography, Interp, convex_quad_any_winding, quad_free_size, quad_size, quad_to_rect, warp_surface_clipped};
use photocraft_color::PixelFormat;
use photocraft_color::{ColorMode, PixelFormat};
use photocraft_doc::{Document, Layer, LayerContent, LayerId, Size};
use photocraft_geom::{Affine, Rect};
use photocraft_raster::Surface;
@@ -31,6 +34,34 @@ const MAX_COORD: f64 = 1e7;
/// (#11977).
const MAX_RESOLUTION: f64 = 29_999.999;
/// The reference's alert when the document holds a layer the tool can't map (#11799): an alert with
/// only an OK button on the tool's first press. The UI shows this text through `tl!` (English is
/// the catalog source); the command returns it as its error.
pub const UNSUPPORTED_LAYERS_ERROR: &str = "Could not use the perspective crop tool because the image contains unsupported layers types.";
/// The reference's alert for a Bitmap mode document (#11799), shown the same way.
pub const BITMAP_MODE_ERROR: &str =
"Could not use the perspective crop tool because it does not work with Bitmap images (convert image to Grayscale mode to edit).";
/// Does `doc` hold a layer the perspective crop can't map: a type layer or a smart object, anywhere
/// in it - visible or hidden, active or not, also inside a group (#11799)? The alert is about the
/// document, not the targeted layer. Shape, fill, adjustment, pixel and group layers do not refuse
/// it (measured); keeping shape and fill layers live is #11800.
pub fn has_unsupported_layers(doc: &Document) -> bool {
doc.walk().iter().any(|(_, _, l)| matches!(l.content, LayerContent::Text(_) | LayerContent::Smart(_)))
}
/// The alert `doc` gets instead of a perspective crop, or `None` when the crop can go through
/// (#11799). The text is exactly what `image.perspectiveCrop` answers with, so the tool can refuse
/// the press with what the command would later refuse. Bitmap is checked first: converting to
/// Bitmap flattens the document (`mode_cmds`), so a Bitmap document never holds a type layer or a
/// smart object and the order is not observable.
pub fn refusal(doc: &Document) -> Option<&'static str> {
if doc.mode == ColorMode::Bitmap {
return Some(BITMAP_MODE_ERROR);
}
has_unsupported_layers(doc).then_some(UNSUPPORTED_LAYERS_ERROR)
}
fn bad(msg: impl Into<String>) -> EngineError {
EngineError::BadParams { cmd: CMD.into(), msg: msg.into() }
}
@@ -224,12 +255,15 @@ fn perspective_crop(s: &mut Session, p: &Value) -> Result<Value> {
let res = resolution(p)?;
let interp = interpolation(p)?;
let d = s.active().ok_or(EngineError::NoDocument)?;
// #11799: what the reference answers with an alert, it answers before it touches anything: no
// rasterization, no warp, no history step. The tool shows the same text on the press.
if let Some(msg) = refusal(&d.doc) {
return Err(EngineError::Other(msg.into()));
}
crate::image_cmds::check_resample_budget(CMD, &d.doc, w, h, "")?;
let rasterize = d
.doc
.walk()
.iter()
.any(|(_, _, l)| matches!(l.content, LayerContent::Text(_) | LayerContent::Shape(_) | LayerContent::Fill(_) | LayerContent::Smart(_)));
// A type layer or a smart object can't get here (they are refused above), so only shape and
// fill layers are ever rasterized (#11800 is about keeping those live).
let rasterize = d.doc.walk().iter().any(|(_, _, l)| matches!(l.content, LayerContent::Shape(_) | LayerContent::Fill(_)));
let map = quad_to_rect(&q, f64::from(w), f64::from(h)).ok_or_else(|| bad("the corners don't define a perspective"))?;
let bg = s.tools.background;
// The Color Sampler points follow their pixels through the homography, which the edit's
@@ -263,7 +297,7 @@ pub fn specs() -> Vec<CommandSpec> {
label: "Perspective Crop",
menu: &[],
shortcut: None,
params: r##"{"corners":[[x,y],[x,y],[x,y],[x,y]] (top-left, top-right, bottom-right, bottom-left; a convex quad, document px),"width":px,"height":px,"resolution":ppi,"interpolation":"bicubic|bilinear|nearest"="bicubic"} → {width,height,resolution,corners} (the quad is mapped onto an upright width x height canvas, all layers, one undo step; no width/height: the rectangle the quad shows in perspective, one alone keeps its proportions; type, shape, fill and smart object layers are rasterized)"##,
params: r##"{"corners":[[x,y],[x,y],[x,y],[x,y]] (top-left, top-right, bottom-right, bottom-left; a convex quad, document px),"width":px,"height":px,"resolution":ppi,"interpolation":"bicubic|bilinear|nearest"="bicubic"} → {width,height,resolution,corners} (the quad is mapped onto an upright width x height canvas, all layers, one undo step; no width/height: the rectangle the quad shows in perspective, one alone keeps its proportions; shape and fill layers are rasterized; refused with the tool's alert, and nothing changes: a document holding a type layer or a smart object anywhere, hidden or inside a group included, answers "Could not use the perspective crop tool because the image contains unsupported layers types.", a Bitmap mode document "Could not use the perspective crop tool because it does not work with Bitmap images (convert image to Grayscale mode to edit).")"##,
enabled: has_doc,
run: perspective_crop,
journal: true,
@@ -0,0 +1,205 @@
//! #11799: the Perspective Crop refuses a document that holds a type layer or a smart object, and
//! a Bitmap mode document, with the reference application's alerts, before anything is rasterized
//! or warped. Nothing about the document changes on a refusal: no history step, no warped pixels,
//! and the other layers keep their kind.
//!
//! Measured (issue #11799): the alert fires for the *document*, not the active layer, so a type
//! layer or a smart object counts wherever it sits - visible or hidden, active or not, also inside
//! a group. A Levels adjustment layer, a Color Fill layer, a rectangle shape layer, a group, a
//! mask, a style, a locked and a hidden layer do not trigger it: those documents still crop.
//! Keeping shape and fill layers live instead of rasterizing them is #11800, so this file pins
//! only that they still crop.
use photocraft_doc::{Color, ColorMode, Document, Fill, Group, Layer, LayerContent, SampleType, ShapeLayer, Size, SmartObject, SmartSource, TextLayer};
use photocraft_geom::{Affine, Rect};
use photocraft_raster::Surface;
use serde_json::{Value, json};
use crate::Session;
/// What the reference shows (an alert with one OK button) for a type layer or a smart object.
const UNSUPPORTED: &str = "Could not use the perspective crop tool because the image contains unsupported layers types.";
/// What it shows for a Bitmap mode document.
const NOT_BITMAP: &str = "Could not use the perspective crop tool because it does not work with Bitmap images (convert image to Grayscale mode to edit).";
const CMD: &str = "image.perspectiveCrop";
/// A skewed quad on the 160 x 120 fixture, and the upright output it is mapped onto.
const QUAD: [[f64; 2]; 4] = [[30.0, 12.0], [140.0, 25.0], [128.0, 110.0], [14.0, 95.0]];
fn crop_params() -> Value {
json!({"corners": QUAD, "width": 100, "height": 80})
}
fn rgb_format() -> photocraft_color::PixelFormat {
Document::with_background("f", Size::new(2, 2), ColorMode::Rgb, SampleType::U8, Color::WHITE).pixel_format()
}
/// 160 x 120 RGB/8 with a white Background and `extra` on top, in a fresh session: nothing has
/// been edited yet, so any history step the crop records shows up as `past_len() > 0`.
fn session(extra: Vec<Layer>) -> Session {
let mut doc = Document::with_background("refuse", Size::new(160, 120), ColorMode::Rgb, SampleType::U8, Color::WHITE);
for l in extra {
doc.insert_above(None, l);
}
let mut s = Session::new();
s.add_document(doc, None);
s
}
/// A type layer reading "Hello", visible or hidden.
fn type_layer(visible: bool) -> Layer {
let mut l = Layer::new("Hello", LayerContent::Text(TextLayer { text: "Hello".into(), ..Default::default() }));
l.visible = visible;
l
}
/// A smart object with a red cache and a linked source, visible or hidden.
fn smart_layer(visible: bool) -> Layer {
let mut cache = Surface::new(rgb_format());
cache.fill_rect(Rect::from_xywh(20, 20, 60, 40), &[1.0, 0.0, 0.0, 1.0]);
let mut l = Layer::new("Photo", LayerContent::Smart(SmartObject::new(SmartSource::Linked { path: "photo.psd".into() }, Affine::IDENTITY, Some(cache))));
l.visible = visible;
l
}
/// A red rectangle shape layer: what the crop rasterizes today alongside a type layer, so a
/// refusal that comes before the rasterize leaves it a shape.
fn shape_layer() -> Layer {
let path = photocraft_vector::shapes::rect(20.0, 20.0, 40.0, 30.0);
Layer::new("Rectangle 1", LayerContent::Shape(ShapeLayer { path, fill: Some(Fill::Solid(Color::rgb(0.8, 0.2, 0.1))), ..Default::default() }))
}
/// A group holding `children`, visible or hidden.
fn group_of(children: Vec<Layer>, visible: bool) -> Layer {
let mut l = Layer::new("Group 1", LayerContent::Group(Group { children, expanded: true, artboard: None, frame_stroke: None }));
l.visible = visible;
l
}
/// Every layer as a refusal must leave it: name, kind, visibility and, for a type layer, its text.
type LayerRecord = (String, &'static str, bool, String);
/// What a refusal must leave alone: the layers, the canvas size, the document revision, the steps.
type Snapshot = (Vec<LayerRecord>, Size, u64, usize);
/// Every layer in `doc`, bottom to top. A refusal leaves this list exactly as it was, so it is both
/// the layer-kind and the text check.
fn fingerprint(doc: &Document) -> Vec<LayerRecord> {
doc.walk()
.iter()
.map(|(_, _, l)| {
let text = match &l.content {
LayerContent::Text(t) => t.text.clone(),
_ => String::new(),
};
(l.name.clone(), l.content.kind_name(), l.visible, text)
})
.collect()
}
/// What a refusal must leave alone.
fn snapshot(s: &Session) -> Snapshot {
let d = s.active().unwrap();
(fingerprint(&d.doc), d.doc.size, d.revision, d.history.past_len())
}
/// The document holds a type layer or a smart object, wherever it sits; every other layer keeps
/// its kind, because the refusal comes before `rasterize_all`.
fn assert_refused(s: &mut Session, want: &str, case: &str) {
let before = snapshot(s);
let err = s.execute(CMD, crop_params()).unwrap_err().to_string();
assert_eq!(err, want, "{case}");
let d = s.active().unwrap();
assert_eq!(fingerprint(&d.doc), before.0, "{case}: layers unchanged");
assert_eq!(d.doc.size, before.1, "{case}: canvas unchanged");
assert_eq!(d.revision, before.2, "{case}: document unchanged");
assert_eq!(d.history.past_len(), 0, "{case}: no history step");
}
/// A type layer anywhere in the document - visible, hidden, or inside a group - is the reference's
/// unsupported-layers alert, not a rasterization (#11799).
#[test]
fn a_type_layer_anywhere_refuses_the_perspective_crop() {
for (case, extra) in [
("visible", vec![type_layer(true), shape_layer()]),
("hidden", vec![type_layer(false), shape_layer()]),
("in a group", vec![group_of(vec![type_layer(true), shape_layer()], true), shape_layer()]),
("in a hidden group", vec![group_of(vec![type_layer(true)], false), shape_layer()]),
] {
let mut s = session(extra);
assert_refused(&mut s, UNSUPPORTED, &format!("{case} type layer"));
let d = s.active().unwrap();
let text: Vec<&str> = d
.doc
.walk()
.iter()
.filter_map(|(_, _, l)| match &l.content {
LayerContent::Text(t) => Some(t.text.as_str()),
_ => None,
})
.collect();
assert_eq!(text, ["Hello"], "{case}: the type layer is still a type layer with its text");
assert!(d.doc.walk().iter().any(|(_, _, l)| l.content.kind_name() == "Shape"), "{case}: nothing was rasterized");
}
}
/// The same for a smart object: visible, hidden, or inside a group.
#[test]
fn a_smart_object_anywhere_refuses_the_perspective_crop() {
for (case, extra) in [
("visible", vec![smart_layer(true), shape_layer()]),
("hidden", vec![smart_layer(false), shape_layer()]),
("in a group", vec![group_of(vec![smart_layer(false)], true), shape_layer()]),
] {
let mut s = session(extra);
assert_refused(&mut s, UNSUPPORTED, &format!("{case} smart object"));
}
}
/// Both at once is still one refusal with the same message, and still changes nothing.
#[test]
fn a_type_layer_and_a_smart_object_refuse_once() {
let mut s = session(vec![type_layer(false), smart_layer(true), shape_layer()]);
assert_refused(&mut s, UNSUPPORTED, "type layer and smart object");
}
/// A Bitmap mode document is the reference's Bitmap alert (#11799).
#[test]
fn a_bitmap_document_refuses_the_perspective_crop() {
let doc = Document::with_background("bitmap", Size::new(160, 120), ColorMode::Bitmap, SampleType::U8, Color::WHITE);
let mut s = Session::new();
s.add_document(doc, None);
assert_refused(&mut s, NOT_BITMAP, "Bitmap document");
}
/// The measured rows that keep working: a document of only pixel, adjustment, Color Fill, shape
/// and group layers still crops, in one undo step (#11799). Whether the shape and the fill stay
/// live is #11800, so this pins the crop, not their kind.
#[test]
fn pixel_adjustment_fill_shape_and_group_layers_still_crop() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 800, "height": 500})).unwrap();
s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap();
s.execute("layer.newFillLayer.solidColor", json!({"color": "#3366cc"})).unwrap();
s.execute("shape.create", json!({"kind": "rect", "rect": [200, 300, 150, 100], "fill": "#cc3333"})).unwrap();
s.execute("layer.groupLayers", json!({"name": "G"})).unwrap();
let before = s.active().unwrap().history.past_len();
let r = s.execute(CMD, json!({"corners": [[100.0, 50.0], [700.0, 60.0], [690.0, 450.0], [110.0, 440.0]], "width": 600, "height": 400})).unwrap();
assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(600), Some(400)));
assert_eq!(s.active().unwrap().doc.size, Size::new(600, 400), "the crop went through");
assert_eq!(s.active().unwrap().history.past_len(), before + 1, "one undo step");
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(s.active().unwrap().doc.size, Size::new(800, 500), "one undo restores it");
}
/// Only Bitmap refuses on the mode: RGB, Grayscale and CMYK documents are unaffected (#11799).
#[test]
fn rgb_grayscale_and_cmyk_documents_are_not_refused() {
for mode in [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk] {
let doc = Document::with_background("m", Size::new(160, 120), mode, SampleType::U8, Color::WHITE);
let mut s = Session::new();
s.add_document(doc, None);
s.execute(CMD, crop_params()).unwrap();
assert_eq!(s.active().unwrap().doc.size, Size::new(100, 80), "{mode:?} cropped");
}
}
+2 -2
View File
@@ -411,9 +411,9 @@ pub fn specs() -> Vec<CommandSpec> {
menu: &[],
shortcut: None,
params: brush_params!(
r#","state":row (a History panel row, as history.setSource),"snapshot":id (a history.newSnapshot id; default: the History panel's source, as paint.historyBrush; a source of another canvas size or colour mode is an error),"style":"tightShort|tightMedium|tightLong|looseMedium|looseLong|dab|tightCurl|looseCurl"="tightShort","area":0..100=50,"tolerance":0..100=0,"opacity":0..100=100 (overrides the common 1..100: how strongly the history state is painted; 0 changes nothing; no flow, mode is Normal)"#
r#","state":row (a History panel row, as history.setSource),"snapshot":id (a history.newSnapshot id; default: the History panel's source, as paint.historyBrush; a source of another canvas size or colour mode is an error),"style":"tightShort|tightMedium|tightLong|looseMedium|looseLong|dab|tightCurl|looseCurl"="tightShort","area":0..500=50,"tolerance":0..100=0,"opacity":0..100=100 (overrides the common 1..100: how strongly the history state is painted; 0 changes nothing; no flow, mode is Normal)"#
),
enabled: has_pixel_layer,
enabled: art_history::enabled,
run: art_history::run,
journal: true,
},
@@ -163,6 +163,64 @@ fn stamp_region(
}
}
/// The reference application's alerts for the refusals below (#12638); a hidden target is
/// [`crate::hidden_target::ART_HISTORY_HIDDEN`].
pub const LOCKED: &str = "Could not use the art history brush because the layer is locked.";
pub const GROUP: &str = "Could not use the art history brush because the pixels in a group cannot be edited without merging the group.";
pub const LACKS_LAYER: &str = "Could not use the art history brush because the history state lacks a corresponding layer.";
pub const CANVAS_SIZE: &str = "Could not use the art history brush because the current canvas size does not match that of the history state.";
pub const NO_SOURCE: &str = "Could not use the art history brush because no history state has been designated as the source for painting.";
/// The command's precondition: a pixel layer, as the other retouching tools, with the alert text
/// when a group is active.
pub(super) fn enabled(s: &Session) -> std::result::Result<(), String> {
super::has_pixel_layer(s).map_err(|why| if crate::active_layer_of(s).is_ok_and(|l| l.is_group()) { GROUP.into() } else { why })
}
/// The targeted layer's pixels can't be painted: a group's (also one with a mask, which the
/// precondition lets through for its mask), or Lock All or Lock Image Pixels, refused with the
/// alert texts. A mask or channel target keeps the shared checks (not measured).
fn refuse_layer(s: &Session, id: Option<photocraft_doc::LayerId>, p: &Value) -> Result<()> {
let (Some(id), Some(st)) = (id, s.active()) else { return Ok(()) };
let Some(layer) = st.doc.layer(id).filter(|_| pixel_target(p)) else { return Ok(()) };
if layer.is_group() {
return Err(EngineError::Other(GROUP.into()));
}
let locks = st.doc.effective_locks(id);
if locks.all || locks.pixels { Err(EngineError::Other(LOCKED.into())) } else { Ok(()) }
}
fn pixel_target(p: &Value) -> bool {
crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::Pixels
}
/// The source the stroke paints from, the History Brush's (the `state` or `snapshot` passed, else
/// the History panel's source, through the shared [`super::history_source`]), refused with the
/// alert texts: no source, then another canvas size, then another colour mode or a depth but 8
/// bits ([`refuse_format`]), then a target layer the source state lacks. A mask or channel target
/// keeps the History Brush's texts for the source refusals (not measured).
fn source_surface(s: &Session, id: Option<photocraft_doc::LayerId>, p: &Value) -> Result<photocraft_raster::Surface> {
use crate::history_source_cmds::{SourceRefusal, checked_source, paint_source};
let st = s.active().ok_or(EngineError::NoDocument)?;
let pixels = pixel_target(p);
let doc = if pixels {
checked_source(st, p, CMD)?.map_err(|why| {
EngineError::Other(
match why {
SourceRefusal::NoSource => NO_SOURCE,
SourceRefusal::CanvasSize { .. } => CANVAS_SIZE,
}
.into(),
)
})?
} else {
paint_source(st, p, CMD)?
};
refuse_format(&st.doc, &doc)?;
super::history_source(s, id, p, CMD)
.map_err(|e| if pixels && crate::channel_cmds::read_target_surface(&doc, id, p).is_err() { EngineError::Other(LACKS_LAYER.into()) } else { e })
}
/// A source of another colour mode, then any document but an 8-bit one, refused with the reference
/// application's alert texts (#12637). The 16-bit text was seen with one layer only; two layers,
/// or a depth change after the source, showed "not directly editable", so that text covers every
@@ -204,7 +262,8 @@ pub fn run(s: &mut Session, p: &Value) -> Result<Value> {
let hardness = ranged(p, "hardness", s.tools.brush.hardness * 100.0, 0.0, 100.0)? / 100.0;
let opacity = ranged(p, "opacity", 100.0, 0.0, 100.0)? / 100.0;
let flow = ranged(p, "flow", 100.0, 0.0, 100.0)? / 100.0;
let area = ranged(p, "area", 50.0, 0.0, 100.0)?;
// Area takes 0..500 px, as the reference's field does (#12630).
let area = ranged(p, "area", 50.0, 0.0, 500.0)?;
// Percent of the channel range; 0 (paint everywhere) is the default, as in Photoshop.
let tolerance = ranged(p, "tolerance", 0.0, 0.0, 100.0)? / 100.0;
let style = style_of(p)?;
@@ -215,13 +274,9 @@ pub fn run(s: &mut Session, p: &Value) -> Result<Value> {
}
let (stroke, id) = parse_brush(s, p, CMD)?;
let _ = stroke;
// The same source as the History Brush: the `state` or `snapshot` passed, else the History
// panel's source, refused after a canvas size change, then after a colour mode change (#12826)
// or at a depth other than 8 bits, as Photoshop does, before a layer missing from it. Compare
// document modes: the pixel format reads Indexed and Multichannel as RGB.
let st = s.active().ok_or(EngineError::NoDocument)?;
refuse_format(&st.doc, &*crate::history_source_cmds::paint_source(st, p, CMD)?)?;
let src_surface = super::history_source(s, id, p, CMD)?;
refuse_layer(s, id, p)?;
// Compare document modes: the pixel format reads Indexed and Multichannel as RGB (#12826).
let src_surface = source_surface(s, id, p)?;
// Truncating a huge row index only changes the seed.
let seed = RNG_SEED ^ p.get("state").and_then(Value::as_u64).map_or(0, |i| i as u32);
let dabs = art_history::place_dabs(&pts, size, area, style, seed).map_err(|e| match e {
@@ -567,3 +622,7 @@ mod art_history_mode_mismatch_tests;
#[cfg(test)]
#[path = "art_history_depth_tests.rs"]
mod art_history_depth_tests;
#[cfg(test)]
#[path = "art_history_refusal_tests.rs"]
mod refusal_tests;
@@ -0,0 +1,172 @@
//! The Art History Brush's refusals use the reference application's alert texts (#12638): a
//! hidden target, Lock All or Lock Image Pixels, a group, a target layer the source state lacks,
//! another canvas size and no source. Each adds no history state and changes no pixel, and the
//! History Brush keeps its own texts.
use serde_json::{Value, json};
use super::{CANVAS_SIZE, GROUP, LACKS_LAYER, LOCKED, NO_SOURCE};
use crate::Session;
use crate::hidden_target::{ART_HISTORY_HIDDEN, HIDDEN};
/// An RGB document with a red "Layer 1" above the white Background, the layer active. History
/// rows: 0 Open, 1 New Layer, 2 Fill.
fn session() -> (Session, u64) {
let mut s = Session::new();
s.execute("file.new", json!({"width": 48, "height": 32, "background": "white"})).unwrap();
let id = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap();
s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();
(s, id)
}
fn stroke(cmd: &str) -> Value {
let mut p = json!({"points": [[8, 16], [40, 16]], "size": 12, "hardness": 100});
if cmd == "paint.artHistoryBrush" {
p["style"] = json!("tightMedium");
}
p
}
/// Runs `cmd` with `extra` params, expects a refusal and returns its text, checking that the
/// document and its history are unchanged.
fn refused(s: &mut Session, cmd: &str, extra: Value) -> String {
let mut p = stroke(cmd);
if let Some(map) = extra.as_object() {
for (k, v) in map {
p[k] = v.clone();
}
}
let (doc, steps) = (s.active().unwrap().doc.clone(), s.active().unwrap().history.entries().len());
let e = s.execute(cmd, p).unwrap_err().to_string();
let st = s.active().unwrap();
assert_eq!(st.history.entries().len(), steps, "{cmd}: no history state for {e}");
for l in &doc.layers {
assert_eq!(st.doc.layer(l.id).and_then(|n| n.surface()), l.surface(), "{cmd}: no pixel changes for {e}");
}
e
}
#[test]
fn a_hidden_target_layer() {
let (mut s, id) = session();
s.execute("layer.setProps", json!({"layer": id, "visible": false})).unwrap();
assert_eq!(refused(&mut s, "paint.artHistoryBrush", json!({})), ART_HISTORY_HIDDEN);
assert_eq!(refused(&mut s, "paint.historyBrush", json!({})), HIDDEN);
}
#[test]
fn lock_all_or_lock_image_pixels() {
for key in ["all", "pixels"] {
let (mut s, id) = session();
s.execute("layer.setProps", json!({"layer": id, "locks": {key: true}})).unwrap();
assert_eq!(refused(&mut s, "paint.artHistoryBrush", json!({})), LOCKED, "{key}");
// Row 1 holds Layer 1, so the History Brush gets as far as the lock.
let e = refused(&mut s, "paint.historyBrush", json!({"state": 1}));
assert!(e.contains("Could not complete your request because the layer \"Layer 1\" is locked"), "{key}: {e}");
}
}
/// Lock Transparent Pixels was not measured: it still paints, as before.
#[test]
fn lock_transparent_pixels_still_paints() {
let (mut s, id) = session();
s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap();
s.execute("layer.setProps", json!({"layer": id, "locks": {"transparency": true}})).unwrap();
s.execute("paint.artHistoryBrush", json!({"points": [[8, 16], [40, 16]], "size": 12, "hardness": 100, "state": 2})).unwrap();
}
#[test]
fn a_group_is_active() {
let (mut s, _) = session();
s.execute("layer.groupLayers", json!({})).unwrap();
let e = refused(&mut s, "paint.artHistoryBrush", json!({}));
assert!(e.contains(GROUP), "{e}");
assert!(!s.is_enabled("paint.artHistoryBrush"));
assert_eq!(s.disabled_reason("paint.artHistoryBrush").as_deref(), Some(GROUP));
let e = refused(&mut s, "paint.historyBrush", json!({}));
assert!(e.contains("not a pixel layer") && !e.contains("art history"), "{e}");
}
/// Row 1 (New Layer) holds the Background and Layer 1; a second layer added after it is missing.
#[test]
fn the_source_state_lacks_the_target_layer() {
let (mut s, _) = session();
s.execute("layer.new.layer", json!({})).unwrap();
assert_eq!(refused(&mut s, "paint.artHistoryBrush", json!({"state": 1})), LACKS_LAYER);
// The History panel's source too.
s.execute("history.setSource", json!({"state": 1})).unwrap();
assert_eq!(refused(&mut s, "paint.artHistoryBrush", json!({})), LACKS_LAYER);
let e = refused(&mut s, "paint.historyBrush", json!({}));
assert!(e.contains("the target did not exist"), "{e}");
}
#[test]
fn the_canvas_size_changed() {
let (mut s, _) = session();
s.execute("image.canvasSize", json!({"width": 60, "height": 32, "anchor": "topLeft"})).unwrap();
assert_eq!(refused(&mut s, "paint.artHistoryBrush", json!({})), CANVAS_SIZE);
assert_eq!(refused(&mut s, "paint.artHistoryBrush", json!({"state": 1})), CANVAS_SIZE);
let e = refused(&mut s, "paint.historyBrush", json!({}));
assert!(e.contains("does not match that of the History Brush source (48×32)"), "{e}");
}
#[test]
fn no_source_is_set() {
let (mut s, _) = session();
let snap = s.execute("history.newSnapshot", json!({})).unwrap()["snapshot"].clone();
s.execute("history.setSource", json!({"snapshot": snap})).unwrap();
s.execute("history.deleteSnapshot", json!({"snapshot": snap})).unwrap();
assert_eq!(refused(&mut s, "paint.artHistoryBrush", json!({})), NO_SOURCE);
let e = refused(&mut s, "paint.historyBrush", json!({}));
assert!(e.contains("the History Brush source was deleted"), "{e}");
}
/// No source and another canvas size: the missing source is reported, as before.
#[test]
fn no_source_comes_before_the_canvas_size() {
let (mut s, _) = session();
let snap = s.execute("history.newSnapshot", json!({})).unwrap()["snapshot"].clone();
s.execute("history.setSource", json!({"snapshot": snap})).unwrap();
s.execute("history.deleteSnapshot", json!({"snapshot": snap})).unwrap();
s.execute("image.canvasSize", json!({"width": 60, "height": 32, "anchor": "topLeft"})).unwrap();
assert_eq!(refused(&mut s, "paint.artHistoryBrush", json!({})), NO_SOURCE);
}
/// The checks don't stop a stroke that may paint: row 2 is the red layer, now blue.
#[test]
fn a_valid_stroke_still_paints() {
let (mut s, _) = session();
s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap();
let steps = s.active().unwrap().history.entries().len();
s.execute("paint.artHistoryBrush", json!({"points": [[8, 16], [40, 16]], "size": 12, "hardness": 100, "state": 2})).unwrap();
assert_eq!(s.active().unwrap().history.entries().len(), steps + 1);
}
/// A group with a mask passes the precondition (for its mask), but its pixels are still refused.
#[test]
fn a_group_with_a_mask_and_its_pixels_targeted() {
let (mut s, _) = session();
s.execute("layer.groupLayers", json!({})).unwrap();
s.execute("layer.layerMask.revealAll", json!({})).unwrap();
assert_eq!(refused(&mut s, "paint.artHistoryBrush", json!({"target": "pixels"})), GROUP);
}
/// A mask target was not measured: a hidden layer, no source and another canvas size keep the
/// History Brush's texts.
#[test]
fn a_mask_target_keeps_todays_texts() {
let (mut s, id) = session();
s.execute("layer.layerMask.revealAll", json!({})).unwrap();
let mask = json!({"target": "mask"});
s.execute("layer.setProps", json!({"layer": id, "visible": false})).unwrap();
assert_eq!(refused(&mut s, "paint.artHistoryBrush", mask.clone()), HIDDEN);
s.execute("layer.setProps", json!({"layer": id, "visible": true})).unwrap();
s.execute("image.canvasSize", json!({"width": 60, "height": 32, "anchor": "topLeft"})).unwrap();
let e = refused(&mut s, "paint.artHistoryBrush", mask.clone());
assert!(e.contains("does not match that of the History Brush source"), "{e}");
let snap = s.execute("history.newSnapshot", json!({})).unwrap()["snapshot"].clone();
s.execute("history.setSource", json!({"snapshot": snap})).unwrap();
s.execute("history.deleteSnapshot", json!({"snapshot": snap})).unwrap();
let e = refused(&mut s, "paint.artHistoryBrush", mask);
assert!(e.contains("the History Brush source was deleted"), "{e}");
}
+10 -1
View File
@@ -2187,6 +2187,11 @@ live_coordinate_regression!(
fn live_dodge_matches_the_commit_across_cells() {
let mut s = session(200, 90, 32, "rgb");
paint_layer(&mut s, texture);
// About the cells' summation order, not smoothing: the live stroke is compared before its
// release, and with the brush's default smoothing lag (#11888) the commit's end catch-up runs
// from the trailing brush along most of the last segment. Live against commit with smoothing
// is the hand-off tests' "smoothing" case.
s.tools.brush.smoothing.enabled = false;
let all = [[10.0, 40.0], [100.0, 60.0], [180.0, 40.0], [60.0, 30.0], [150.0, 70.0]];
let pts = |v: &[[f64; 2]]| v.iter().map(|q| StrokePoint::new(q[0], q[1], 1.0)).collect::<Vec<_>>();
let opts = |p: &[[f64; 2]]| json!({"points": p, "size": 40, "hardness": 30, "exposure": 60, "range": "midtones"});
@@ -2318,7 +2323,7 @@ fn live_dab_batches_match_the_accumulating_renderer() {
});
let id = s.active().unwrap().active_layer.unwrap();
let pre = s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().clone();
for case in ["soft", "hard", "sampled", "dynamics", "smoothing"] {
for case in ["soft", "hard", "sampled", "dynamics", "smoothing", "smoothing_catch_up"] {
s.tools.brush = BrushSettings::default();
match case {
"sampled" => s.tools.brush.tip = TipShape::Sampled(GrayTile::from_fn(9, 7, |x, y| ((x * 3 + y) % 11) as f32 / 10.0)),
@@ -2339,6 +2344,10 @@ fn live_dab_batches_match_the_accumulating_renderer() {
b.texture.pattern = photocraft_paint::Pattern::Tile(GrayTile::from_fn(3, 3, |x, y| (x + y) as f32 / 4.0));
}
"smoothing" => s.tools.brush.smoothing.amount = 0.65,
"smoothing_catch_up" => {
s.tools.brush.smoothing.amount = 0.65;
s.tools.brush.smoothing.catch_up_on_end = true;
}
_ => {}
}
let points = [
+8
View File
@@ -0,0 +1,8 @@
//! The command table's fragments, one directory per owner: the crate whose items the commands
//! call. Each directory moves whole into its crate; `SPECS` in `cmd.rs` fixes the order.
pub(crate) mod core;
pub(crate) mod image;
pub(crate) mod model;
pub(crate) mod paint;
pub(crate) mod store;
+5
View File
@@ -0,0 +1,5 @@
pub(crate) mod edit_menu;
pub(crate) mod file_menu;
pub(crate) mod queries;
pub(crate) mod select_menu;
pub(crate) mod tools;
@@ -0,0 +1,9 @@
use crate::cmd::{CommandSpec, can_redo, can_undo, json};
/// Edit menu: Undo and Redo.
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![
cmd!("edit.undo", "Undo", ["Edit"], Some("Cmd+Z"), "{}", can_undo, |s, _| Ok(json!(s.undo()))),
cmd!("edit.redo", "Redo", ["Edit"], Some("Cmd+Shift+Z"), "{}", can_redo, |s, _| Ok(json!(s.redo()))),
]
}
@@ -0,0 +1,28 @@
use crate::cmd::{CommandSpec, EngineError, Value, bad, has_doc};
/// File menu: Close.
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"file.close",
"Close",
["File"],
Some("Cmd+W"),
r##"{"document":index?,"save":"discard|ask"|false="discard"} (false means discard; ask refuses to close a changed document in headless playback)"##,
has_doc,
|s, p| {
let i = p.get("document").and_then(Value::as_u64).map(|v| v as usize).or(s.active_index()).ok_or(EngineError::NoDocument)?;
match p.get("save").filter(|v| !v.is_null()) {
Some(v) if v == "ask" && s.documents().get(i).ok_or(EngineError::NoDocument)?.is_dirty() => {
return Err(bad("file.close", "the document has unsaved changes; save it or explicitly discard them"));
}
Some(v) if v == "ask" => {}
// `false` (don't save) is the older spelling of discard.
Some(Value::Bool(false)) => {}
Some(v) if v != "discard" => return Err(bad("file.close", "`save` must be ask, discard or false")),
_ => {}
}
s.close(i).ok_or(EngineError::NoDocument)?;
Ok(Value::Null)
}
)]
}
+122
View File
@@ -0,0 +1,122 @@
use crate::cmd::{CommandSpec, EngineError, Rect, Value, always, bad, command_specs, has_doc, inspect, int, json, list_entry};
/// Commands that report session and document state or switch documents.
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec {
id: "session.inspect",
label: "Inspect Session",
menu: &[],
shortcut: None,
params: "{}",
enabled: always,
run: |s, _| Ok(inspect::session(s)),
journal: false,
},
CommandSpec {
id: "document.inspect",
label: "Inspect Document",
menu: &[],
shortcut: None,
params: r##"{"document":index?}"##,
enabled: has_doc,
run: |s, p| {
let d = match p.get("document") {
Some(v) => {
let i = v.as_u64().and_then(|v| usize::try_from(v).ok()).ok_or_else(|| bad("document.inspect", "`document` must be an index"))?;
s.documents().get(i).ok_or_else(|| EngineError::Other(format!("no document at index {i}")))?
}
None => s.active().ok_or(EngineError::NoDocument)?,
};
Ok(inspect::document(d))
},
journal: false,
},
CommandSpec {
id: "document.activate",
label: "Activate Document",
menu: &[],
shortcut: None,
params: r##"{"document":index|{"index":uint}} or {"offset":int} (numeric document: zero-based tab index; typed index: one-based opening order; offset: places after the active document in opening order, before it when negative) → {document}"##,
enabled: has_doc,
run: |s, p| {
// A null key counts as omitted.
let given = |k: &str| p.get(k).filter(|v| !v.is_null());
let idx = match (given("document"), given("offset")) {
(Some(_), Some(_)) => return Err(bad("document.activate", "give `document` or `offset`, not both")),
(None, None) => return Err(bad("document.activate", "needs `document` (a tab index) or `offset`")),
// Recorded offsets wrap in opening order, independently of dragged tabs.
(None, Some(o)) => {
let o = o.as_i64().ok_or_else(|| bad("document.activate", "`offset` must be an integer"))?;
s.document_at_offset(o)?
}
(Some(d), None) => {
if let Some(selector) = d.as_object() {
let index = selector
.get("index")
.filter(|_| selector.len() == 1)
.and_then(Value::as_u64)
.ok_or_else(|| bad("document.activate", "document reference needs one non-negative index"))?;
return s
.document_at_index(index)
.and_then(|idx| if s.set_active(idx) { Ok(json!({"document": idx})) } else { Err(EngineError::NoDocument) });
}
let i = d.as_u64().ok_or_else(|| bad("document.activate", "`document` must be a tab index"))?;
usize::try_from(i).map_err(|_| bad("document.activate", "`document` out of range"))?
}
};
if s.set_active(idx) { Ok(json!({"document": idx})) } else { Err(EngineError::Other(format!("no document at index {idx}"))) }
},
journal: true,
},
CommandSpec {
id: "document.move",
label: "Move Document",
menu: &[],
shortcut: None,
params: r##"{"document":index?,"to":index}"##,
enabled: has_doc,
run: |s, p| {
let index = |key: &str| {
p.get(key)
.map(|v| v.as_u64().and_then(|v| usize::try_from(v).ok()).ok_or_else(|| bad("document.move", format!("`{key}` must be a tab index"))))
};
let from = match index("document") {
Some(i) => i?,
None => s.active_index().ok_or(EngineError::NoDocument)?,
};
let to = index("to").ok_or_else(|| bad("document.move", "missing `to`"))??;
let to = s.move_document(from, to).ok_or(EngineError::NoDocument)?;
Ok(json!({"document": to}))
},
journal: false,
},
CommandSpec {
id: "command.list",
label: "List Commands",
menu: &[],
shortcut: None,
params: "{}",
enabled: always,
run: |s, _| Ok(Value::Array(command_specs().iter().map(|c| list_entry(s, c, (c.enabled)(s).err())).collect())),
journal: false,
},
CommandSpec {
id: "document.pixel",
label: "Read Composite Pixel",
menu: &[],
shortcut: None,
params: r##"{"x":i32,"y":i32}"##,
enabled: has_doc,
run: |s, p| {
let coord = |k: &str| i32::try_from(int(p, k).unwrap_or(0)).map_err(|_| bad("document.pixel", format!("{k} must fit in 32 bits")));
let (x, y) = (coord("x")?, coord("y")?);
let d = s.active().ok_or(EngineError::NoDocument)?;
// At i32::MAX the 1x1 rect saturates to empty: a pixel that far out is transparent.
let px = photocraft_compose::render(&d.doc, Rect::from_xywh(x, y, 1, 1)).px.first().copied().unwrap_or_default();
Ok(json!(px))
},
journal: false,
},
]
}
@@ -0,0 +1,120 @@
use crate::cmd::{CommandSpec, Rect, Surface, TILE_SIZE, Value, bad, has_doc, has_selection, int_i32, selection_cmds};
/// Select menu: All, Deselect, Inverse and rectangular selections.
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![
// Select
cmd!("select.all", "All", ["Select"], Some("Cmd+A"), "{}", has_doc, |s, _| {
// With the active layer on an artboard (the board itself or a layer inside it), Select
// All selects that board, as Photoshop does; otherwise the whole canvas (#10258).
let active = s.active().and_then(|d| d.active_layer);
s.edit("Select All", |doc, _| {
let board = active.and_then(|id| doc.artboard_of(id)).and_then(|id| doc.layer(id)).and_then(|l| l.artboard()).map(|a| a.rect);
// A board the canvas no longer reaches (cropped away) selects the canvas, never an
// empty selection that would block painting.
let area = board.map(|r| r.intersect(&doc.bounds())).filter(|r| !r.is_empty()).unwrap_or_else(|| doc.bounds());
let mut m = Surface::new(photocraft_color::PixelFormat::GRAY8);
m.fill_rect(area, &[1.0]);
doc.selection = Some(m);
Ok(())
})?;
Ok(Value::Null)
}),
cmd!("select.deselect", "Deselect", ["Select"], Some("Cmd+D"), "{}", has_selection, |s, _| {
// Nothing selected: nothing to do and no history step, as in Photoshop (#6744).
if s.active().is_none_or(|d| d.doc.selection.is_none()) {
return Ok(Value::Null);
}
s.edit("Deselect", |doc, _| {
doc.selection = None;
Ok(())
})?;
Ok(Value::Null)
}),
cmd!("select.inverse", "Inverse", ["Select"], Some("Cmd+Shift+I"), "{}", has_selection, |s, _| {
s.edit("Inverse", |doc, _| {
let old = doc.selection.take().unwrap_or_else(|| Surface::new(photocraft_color::PixelFormat::GRAY8));
doc.selection = Some(photocraft_algo::selection::inverse_surface(&old, doc.bounds()));
Ok(())
})?;
Ok(Value::Null)
}),
cmd!(
"select.rect",
"Rectangular Selection",
[],
None,
r##"{"x":i32,"y":i32,"width":u32,"height":u32,"mode":"replace|add|subtract|intersect"="replace","ellipse":bool=false,"line":"row|column"?,"antiAlias":bool=true,"feather":px=0}"##,
has_doc,
|s, p| {
let get = |k: &str| int_i32("select.rect", p, k).and_then(|v| v.ok_or_else(|| bad("select.rect", format!("missing `{k}`"))));
let r = Rect::from_xywh(get("x")?, get("y")?, get("width")?.max(0) as u32, get("height")?.max(0) as u32);
let mode = p.get("mode").and_then(Value::as_str).unwrap_or("replace").to_string();
let ellipse = p.get("ellipse").and_then(Value::as_bool).unwrap_or(false);
// The History step is named after the tool: the Single Row / Single Column
// Marquee send `line` (Photoshop).
let step = match p.get("line").and_then(Value::as_str) {
Some("row") => "Single Row Marquee",
Some("column") => "Single Column Marquee",
Some(other) => return Err(bad("select.rect", format!("unknown `line` {other:?} (row|column)"))),
None if ellipse => "Elliptical Marquee",
None => "Rectangular Marquee",
};
// Options bar: anti-aliased ellipse edges (4x4 supersampled) and Feather (applied to the new shape only).
let aa = p.get("antiAlias").and_then(Value::as_bool).unwrap_or(true);
let feather = p.get("feather").and_then(Value::as_f64).unwrap_or(0.0).clamp(0.0, 1000.0) as f32;
s.edit(step, |doc, _| {
let area = doc.bounds();
// A marquee dragged past the canvas stops at its edge (Photoshop); the ellipse
// keeps the dragged shape and is only cut there.
use photocraft_algo::selection as sel;
let shape = if ellipse {
sel::ellipse_surface(r, area, aa)
} else {
let mut s = Surface::new(photocraft_color::PixelFormat::GRAY8);
s.fill_rect(r.intersect(&area), &[1.0]);
s
};
if feather > 0.0 {
let window = selection_cmds::feather_window(r, area, feather);
let m = sel::feather(&sel::mask_from_surface(Some(&shape), window), window.width() as usize, window.height() as usize, feather);
doc.selection = selection_cmds::combine_band(doc.selection.as_ref(), &m, window, sel::SelectionMode::parse(&mode));
return Ok(());
}
let old = doc.selection.take();
let combined = match (mode.as_str(), old) {
("add", Some(o)) => sel::combine_sparse(&o, &shape, area, |a, b| a.max(b)),
("subtract", Some(o)) => sel::combine_sparse(&o, &shape, area, |a, b| a * (1.0 - b)),
("intersect", Some(o)) => sel::combine_surfaces(&o, &shape, area, |a, b| a.min(b)),
// With no existing selection, neither operation can select new pixels.
("subtract" | "intersect", None) => Surface::new(photocraft_color::PixelFormat::GRAY8),
_ => shape,
};
// Sparse Add/Subtract keeps untouched pixels outside the canvas. Only pixels
// inside the document count when deciding whether a selection remains.
let has_on_canvas_pixels = (combined.default_bytes().first().copied().unwrap_or(0) != 0 && {
let canvas_tiles = u64::from(area.width().div_ceil(TILE_SIZE as u32)) * u64::from(area.height().div_ceil(TILE_SIZE as u32));
let stored = combined.tiles().filter(|(coord, _)| !coord.rect().intersect(&area).is_empty()).count() as u64;
stored < canvas_tiles
}) || combined.tiles().any(|(coord, tile)| {
let tile_rect = coord.rect();
let overlap = tile_rect.intersect(&area);
if overlap.is_empty() {
return false;
}
let x0 = (overlap.x0 - tile_rect.x0) as usize;
let x1 = (overlap.x1 - tile_rect.x0) as usize;
(overlap.y0 - tile_rect.y0..overlap.y1 - tile_rect.y0).any(|y| {
let row_start = y as usize * TILE_SIZE as usize;
let start = row_start + x0;
tile.bytes().get(start..row_start + x1).is_some_and(|row| row.iter().any(|&v| v != 0))
})
});
doc.selection = has_on_canvas_pixels.then_some(combined);
Ok(())
})?;
Ok(Value::Null)
}
),
]
}
+46
View File
@@ -0,0 +1,46 @@
use crate::cmd::{CommandSpec, Value, always, cmyk_param, color_param};
/// Tool state: foreground and background colors.
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"tools.setColors",
"Set Colors",
[],
None,
r##"{"foreground":"#rrggbb"|[r,g,b,a?]?,"background":same?,"foregroundCmyk":[c,m,y,k]? (inks 0..1 the foreground was picked as: a CMYK document is filled with exactly these),"backgroundCmyk":same?}"##,
always,
|s, p| {
let cmyk = |key: &str| cmyk_param("tools.setColors", p, key);
let (fg_cmyk, bg_cmyk) = (cmyk("foregroundCmyk")?, cmyk("backgroundCmyk")?);
let foreground = color_param("tools.setColors", p, "foreground", s.tools.foreground)?;
let background = color_param("tools.setColors", p, "background", s.tools.background)?;
s.tools.foreground = foreground;
s.tools.background = background;
if let Some(k) = fg_cmyk {
let [r, g, b, _] = s.tools.foreground;
s.tools.remember_cmyk([r, g, b], k);
}
if let Some(k) = bg_cmyk {
let [r, g, b, _] = s.tools.background;
s.tools.remember_cmyk([r, g, b], k);
}
Ok(Value::Null)
}
),
cmd!("tools.swapColors", "Switch Foreground and Background Colors", [], Some("X"), "{}", always, |s, _| {
std::mem::swap(&mut s.tools.foreground, &mut s.tools.background);
Ok(Value::Null)
}),
cmd!("tools.defaultColors", "Default Foreground and Background Colors", [], Some("D"), "{}", always, |s, _| {
if s.tools.mask_targeted {
s.tools.foreground = crate::ToolState::MASK_COLORS[0];
s.tools.background = crate::ToolState::MASK_COLORS[1];
} else {
s.tools.foreground = [0.0, 0.0, 0.0, 1.0];
s.tools.background = [1.0, 1.0, 1.0, 1.0];
}
Ok(Value::Null)
}),
]
}
+2
View File
@@ -0,0 +1,2 @@
pub(crate) mod adjustments;
pub(crate) mod image_menu;
@@ -0,0 +1,147 @@
use crate::cmd::{CommandSpec, NEW_LAYER_PATH, Value, adjust_mode, destructive_adjust, doc_mode, has_doc, is_mask_target, new_adjustment};
/// The adjustment layers and the Image › Adjustments commands, generated from one table.
pub(crate) fn specs() -> Vec<CommandSpec> {
let mut v = Vec::new();
// Adjustment layers + destructive adjustments, generated from one list.
// Levels/Curves channel keys follow the document: red/green/blue (RGB), gray (Grayscale),
// cyan/magenta/yellow/black (CMYK), lightness/a/b (Lab); see `adjust_params`.
const ADJ: &[(&str, &str, &str)] = &[
("brightnessContrast", "Brightness/Contrast…", r##"{"brightness":-150..150=0,"contrast":-50..100=0,"legacy":bool=false}"##),
(
"levels",
"Levels…",
r##"{"inBlack":0..253=0,"gamma":0.01..9.99=1,"inWhite":2..255=255,"outBlack":0..255=0,"outWhite":0..255=255,"red":json,"green":json,"blue":json,"eyedropper":json} (top level = composite; per channel {"inBlack","gamma","inWhite","outBlack","outWhite"} under red/green/blue, gray, cyan/magenta/yellow/black or lightness/a/b; eyedropper = the dialog's Set Black/Neutral Gray/White Point picker {"point":"black|gray|white","at":[x,y],"size":1..101=1} or {"point",…,"color":[r,g,b] 0..1}: black/white set each channel's input black/white to the sample, gray each channel's gamma so the sample turns neutral at its luma; colour composites: RGB and Grayscale (no gray); Image adjustments targeting a mask, alpha or Quick Mask sample that gray plane in any document mode, applied over the given levels)"##,
),
(
"curves",
"Curves…",
r##"{"points":json,"red":json,"green":json,"blue":json,"pencil":bool=false,"smooth":0..10=0,"eyedropper":json} (curves as [[in,out],…] in 0..255, 2..19 points: points = composite; red/green/blue, gray, cyan/magenta/yellow/black or lightness/a/b per channel; pencil = drawn curves (Draw to modify the curve): each curve is 256 output levels in 0..255 (point curves given are drawn in, and turning pencil off fits points to the drawing); smooth = Smooth passes over the drawn curves; eyedropper = the dialog's Set Black/Neutral Gray/White Point picker {"point":"black|gray|white","at":[x,y],"size":1..101=1} or {"point",…,"color":[r,g,b] 0..1}, colour composites: RGB and Grayscale (no gray); Image adjustments targeting a mask, alpha or Quick Mask sample that gray plane in any document mode, applied over the given curves)"##,
),
("exposure", "Exposure…", r##"{"exposure":-20..20=0,"offset":-0.5..0.5=0,"gamma":0.01..9.99=1}"##),
("vibrance", "Vibrance…", r##"{"vibrance":-100..100=0,"saturation":-100..100=0}"##),
(
"hueSaturation",
"Hue/Saturation…",
r##"{"hue":-180..180=0,"saturation":-100..100=0,"lightness":-100..100=0,"colorize":bool=false,"reds":json,"yellows":json,"greens":json,"cyans":json,"blues":json,"magentas":json} (per range {"hue","saturation","lightness","range":[4 hue degrees]}; colorize: hue 0..360, saturation 0..100)"##,
),
(
"colorBalance",
"Color Balance…",
r##"{"shadows":json,"midtones":json,"highlights":json,"preserveLuminosity":bool=true} (each tone [cyan-red, magenta-green, yellow-blue] in -100..100)"##,
),
(
"blackWhite",
"Black & White…",
r##"{"reds":-200..300=40,"yellows":-200..300=60,"greens":-200..300=40,"cyans":-200..300=60,"blues":-200..300=20,"magentas":-200..300=80,"tint":bool=false,"tintColor":"#rrggbb"}"##,
),
(
"photoFilter",
"Photo Filter…",
r##"{"filter":"warming85|warmingLBA|warming81|cooling80|coolingLBB|cooling82|red|orange|yellow|green|cyan|blue|violet|magenta|sepia|deepRed|deepBlue|deepEmerald|deepYellow|underwater","color":"#rrggbb","density":0..100=25,"preserveLuminosity":bool=true}"##,
),
(
"channelMixer",
"Channel Mixer…",
r##"{"red":json,"green":json,"blue":json,"gray":json,"monochrome":bool=false} (per output channel [red %, green %, blue %, constant %] in -200..200; gray = the monochrome mix)"##,
),
("invert", "Invert", "{}"),
("posterize", "Posterize…", r##"{"levels":2..255=4}"##),
("threshold", "Threshold…", r##"{"level":1..255=128}"##),
("gradientMap", "Gradient Map…", r##"{"stops":json,"reverse":bool=false,"dither":bool=false} (stops [[location 0..1, "#rrggbb"], …], 2..64)"##),
(
"selectiveColor",
"Selective Color…",
r##"{"method":"relative|absolute"="relative","colors":"reds|yellows|greens|cyans|blues|magentas|whites|neutrals|blacks"="reds","cyan":-100..100=0,"magenta":-100..100=0,"yellow":-100..100=0,"black":-100..100=0,"reds":json} (per-range [c,m,y,k] arrays: reds yellows greens cyans blues magentas whites neutrals blacks)"##,
),
(
"colorLookup",
"Color Lookup…",
r##"{"lut":"none|warm|cool|tealOrange|bleachBypass|fadedFilm|dayForNight|monoContrast|crossProcess"="none","file":text,"interpolation":"trilinear|tetrahedral"="trilinear","dither":bool=false,"data":text,"dataEncoding":"text|base64"="text","fileName":text,"lutFormat":"auto|cube|3dl|look"="auto"} (file: LUT path; data: file text or encoded bytes; lutFormat overrides format detection, auto detects it)"##,
),
];
for &(kind, label, params) in ADJ {
let layer_id: &'static str = Box::leak(format!("layer.newAdjustmentLayer.{kind}").into_boxed_str());
let image_id: &'static str = Box::leak(format!("image.adjustments.{kind}").into_boxed_str());
v.push(CommandSpec {
id: layer_id,
label,
menu: &["Layer", "New Adjustment Layer"],
shortcut: None,
params: Box::leak(format!(r#"{params} + {{{NEW_LAYER_PATH},"opacity":0..1=1,"name":str?=the adjustment's name + number,"mode":blend mode name="normal" (not Pass Through),"clipToPrevious":bool=false}}"#).into_boxed_str()),
enabled: has_doc,
run: |s, p| {
let kind = p.get("__kind").and_then(Value::as_str).unwrap_or("invert").to_string();
let eyedropped = if matches!(kind.as_str(), "levels" | "curves") { crate::adjust_params::eyedropper_from_params(s, &kind, p)? } else { None };
let adj = match eyedropped {
Some(adj) => adj,
None => crate::adjust_params::from_params(&kind, p, None, doc_mode(s))?,
};
new_adjustment(s, adj, p, &format!("layer.newAdjustmentLayer.{kind}"))
},
journal: true,
});
v.push(CommandSpec {
id: image_id,
label,
menu: &["Image", "Adjustments"],
shortcut: match kind {
"levels" => Some("Cmd+L"),
"curves" => Some("Cmd+M"),
"hueSaturation" => Some("Cmd+U"),
"colorBalance" => Some("Cmd+B"),
"invert" => Some("Cmd+I"),
"blackWhite" => Some("Cmd+Alt+Shift+B"),
_ => None,
},
params,
enabled: crate::adjust_cmds::has_adjustable,
run: |s, p| {
let kind = p.get("__kind").and_then(Value::as_str).unwrap_or("invert").to_string();
if matches!(kind.as_str(), "levels" | "curves") {
crate::channel_cmds::resolve_tone_target(s, false, p)?;
}
let eyedropped = if matches!(kind.as_str(), "levels" | "curves") { crate::adjust_params::destructive_eyedropper(s, &kind, p)? } else { None };
// A smart filter re-runs its params, so it records what an eyedropper resolved
// to, not the sample (#3127).
let recorded = eyedropped.as_ref().map(|adj| {
let mut q = p.clone();
if let (Value::Object(q), Value::Object(resolved)) = (&mut q, crate::adjust_params::to_params(adj)) {
q.remove("eyedropper");
q.extend(resolved);
}
q
});
let adj = match eyedropped {
Some(adj) => adj,
None => {
// A gray plane target keeps the neutral tone space even over params
// carrying RGB, Lab or CMYK records (#5335).
let tone = if is_mask_target(p) || crate::channel_cmds::is_channel_target(p) {
if matches!(kind.as_str(), "levels" | "curves") { crate::adjust_params::gray_tone_params(p) } else { p.clone() }
} else {
p.clone()
};
crate::adjust_params::from_params(&kind, &tone, None, adjust_mode(s, p))?
}
};
let adj = if matches!(kind.as_str(), "levels" | "curves")
&& let Some(colors) = crate::color_channels::target(s, p)?
{
crate::color_channels::tone_adjustment(&kind, p, adj, doc_mode(s), colors)?
} else {
adj
};
let label = adj.label().to_string();
// A smart object records the adjustment as a smart filter (Photoshop), which
// re-runs from the source instead of baking into a copy of the pixels.
if crate::adjust_cmds::adjust_as_smart_filter(s, &kind, &label, recorded.as_ref().unwrap_or(p))? {
return Ok(Value::Null);
}
destructive_adjust(s, &label, adj, p)
},
journal: true,
});
}
v
}
@@ -0,0 +1,24 @@
use crate::cmd::{Adjustment, CommandSpec, Value, destructive_adjust};
/// Image › Adjustments › Desaturate: Hue/Saturation with saturation at -100.
pub(crate) fn desaturate_adjustment() -> Adjustment {
Adjustment::HueSaturation { hue: 0.0, saturation: -100.0, lightness: 0.0, colorize: false, ranges: photocraft_doc::adjust::HueRange::defaults() }
}
/// Image menu: Desaturate.
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"image.adjustments.desaturate",
"Desaturate",
["Image", "Adjustments"],
Some("Cmd+Shift+U"),
r##"{"target":"pixels"|"mask"|{"color":i}|{"colors":[i,…]}?=Channels panel target,"layer":id|name?=active}"##,
crate::adjust_cmds::has_adjustable,
|s, p| {
if crate::adjust_cmds::adjust_as_smart_filter(s, "desaturate", "Desaturate", p)? {
return Ok(Value::Null);
}
destructive_adjust(s, "Desaturate", desaturate_adjustment(), p)
}
)]
}
+3
View File
@@ -0,0 +1,3 @@
pub(crate) mod edit_menu;
pub(crate) mod image_menu;
pub(crate) mod layer_menu;
@@ -0,0 +1,49 @@
use crate::cmd::{CommandSpec, Value, has_pixel_or_channel, is_mask_target, layer_param};
/// Edit menu: Clear (channel and mask targets).
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"edit.clear",
"Clear",
["Edit"],
None,
r##"{"target":"mask"|{"color":i}|{"colors":[i,…]}?=Channels panel target,"layer":id|name?=active} (a targeted mask, channel or Quick Mask is cleared alone)"##,
has_pixel_or_channel,
|s, p| {
let bg = s.tools.background;
// A targeted alpha channel or Quick Mask is filled instead (#2734).
let channel = if crate::channel_cmds::is_channel_target(p) {
Some(p.clone())
} else if p.get("target").is_none() {
crate::channel_cmds::targeted_channel(s)
} else {
None
};
if let Some(t) = channel {
s.edit("Clear", |doc, _| crate::channel_cmds::clear_channel(doc, &t, bg))?;
return Ok(Value::Null);
}
let id = layer_param(s, p)?;
if is_mask_target(p) {
s.edit("Clear Mask", |doc, _| crate::edit_cmds::clear_mask(doc, id, bg, p))?;
return Ok(Value::Null);
}
// A targeted colour channel clears that channel only (#2720).
if let Some(colors) = crate::color_channels::target(s, p)? {
s.edit("Clear", |doc, _| {
for k in colors.indices() {
crate::channel_cmds::clear_color_channel(doc, id, k, bg)?;
}
Ok(())
})?;
return Ok(Value::Null);
}
s.edit("Clear", |doc, _| {
let sel = doc.selection.clone();
let area = sel.as_ref().map(|m| m.content_bounds()).unwrap_or(doc.bounds());
crate::edit_cmds::clear_area(doc, id, area, sel.as_ref(), bg)
})?;
Ok(Value::Null)
}
)]
}
@@ -0,0 +1,38 @@
use crate::cmd::{CommandSpec, Result, Session, Value, has_doc};
/// Image › Image Rotation by a right angle or a flip (pixels, vectors, guides, … all move).
fn turn(s: &mut Session, label: &str, t: crate::canvas_geom::Turn) -> Result<Value> {
if let Some(d) = s.active() {
let a = t.affine(f64::from(d.doc.size.width), f64::from(d.doc.size.height));
// Sampler points are pixel indices, not pixel edges: map the pixel's centre, so the point
// lands on the same pixel `Turn::pixel_map` moves the pixels to (`w - 1 - x`).
let half = photocraft_geom::Affine::translate(0.5, 0.5);
s.set_canvas_map(a, half.then(&a).then(&photocraft_geom::Affine::translate(-0.5, -0.5)));
}
s.edit(label, |doc, _| {
crate::canvas_geom::keeping_count_points(doc, |doc| crate::canvas_geom::turn_canvas(doc, t));
Ok(())
})?;
Ok(Value::Null)
}
/// Image menu: canvas rotations and flips.
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![
cmd!("image.imageRotation.flipCanvasHorizontal", "Flip Canvas Horizontal", ["Image", "Image Rotation"], None, "{}", has_doc, |s, _| {
turn(s, "Flip Canvas Horizontal", crate::canvas_geom::Turn::FlipHorizontal)
}),
cmd!("image.imageRotation.flipCanvasVertical", "Flip Canvas Vertical", ["Image", "Image Rotation"], None, "{}", has_doc, |s, _| {
turn(s, "Flip Canvas Vertical", crate::canvas_geom::Turn::FlipVertical)
}),
cmd!("image.imageRotation.180", "180°", ["Image", "Image Rotation"], None, "{}", has_doc, |s, _| {
turn(s, "Rotate Canvas", crate::canvas_geom::Turn::Rotate180)
}),
cmd!("image.imageRotation.90cw", "90° Clockwise", ["Image", "Image Rotation"], None, "{}", has_doc, |s, _| {
turn(s, "Rotate Canvas", crate::canvas_geom::Turn::Cw90)
}),
cmd!("image.imageRotation.90ccw", "90° Counter Clockwise", ["Image", "Image Rotation"], None, "{}", has_doc, |s, _| {
turn(s, "Rotate Canvas", crate::canvas_geom::Turn::Ccw90)
}),
]
}
@@ -0,0 +1,536 @@
use crate::cmd::{
Adjustment, Color, ColorMode, CommandSpec, EngineError, Fill, Layer, LayerContent, LayerId, LayerMask, Result, Session, Value, adjustment_kind, arrange,
bad, cmyk_param, color_param, has_doc, has_layer, has_selection, json, layer_copy, layer_panel_option, layer_param, mask_new_layer, merge_group, move_mask,
parse_blend, pixels, set_clipped, set_mask, set_mask_and_deselect,
};
use photocraft_color::BlendMode;
/// Layer menu, first run: new layers and groups to the solid color fill layer.
pub(crate) fn specs_before_gradient() -> Vec<CommandSpec> {
[creation(), duplication(), deletion_and_selection(), order_and_clipping(), masks(), merging(), solid_color_fill()].into_iter().flatten().collect()
}
/// Layer menu, last run: adjustment layers, move and translate.
pub(crate) fn specs_after_gradient() -> Vec<CommandSpec> {
[adjustments(), placement()].into_iter().flatten().collect()
}
/// New layers and groups, and grouping the selected layers.
fn creation() -> Vec<CommandSpec> {
vec![
cmd!(
"layer.new.layer",
"Layer…",
["Layer", "New"],
Some("Cmd+Shift+N"),
r##"{"name":str?,"clipToPrevious":bool=false (Use Previous Layer to Create Clipping Mask; inside a clip group the layer joins it anyway),"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":"Normal|Multiply|…"="Normal","opacity":0..1=1,"fillNeutral":bool=false (fill with the mode's neutral color: modes without one are an error),"position":"above|below"="above" (below: the Layers panel's Cmd/Ctrl-click; never under the Background)} (above the active layer, or the top layer inside it when it is an open group)"##,
has_doc,
crate::new_layer::run
),
cmd!(
"layer.new.group",
"Group…",
["Layer", "New"],
None,
r##"{"name":text?,"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":str="passThrough" (blend mode),"opacity":0..100=100 (percent),"position":"above|below"="above" (below: the Layers panel's Cmd/Ctrl-click; never under the Background)} (above the active layer, or inside it when it is an open group; clipped when it lands inside a clipping mask)"##,
has_doc,
|s, p| {
let opts = crate::group_options::GroupOptions::parse("layer.new.group", p)?;
let below = crate::group_options::below("layer.new.group", p)?;
let place = if below { crate::layer_place::Place::Below } else { crate::layer_place::Place::Auto };
let id = s.edit("New Group", |doc, active| {
let name = opts.name.clone().unwrap_or_else(|| doc.next_layer_name("Group"));
let mut group = Layer::group(name, vec![]);
opts.apply(&mut group);
let bg = crate::background_cmds::background_id(doc);
let id = crate::layer_place::insert_new(doc, *active, group, place);
crate::background_cmds::keep_background_at_bottom(bg, doc)?;
*active = Some(id);
Ok(id)
})?;
Ok(json!({ "layer": id.0 }))
}
),
cmd!(
"layer.groupLayers",
"Group Layers",
["Layer"],
Some("Cmd+G"),
r##"{"layer":id?,"name":text?,"color":"none|red|orange|yellow|green|seafoam|blue|indigo|magenta|fuchsia|violet|gray"="none","mode":str="passThrough" (blend mode),"opacity":0..100=100 (percent)} (no layer: every selected layer; the new group starts collapsed)"##,
has_layer,
crate::layer_multi_cmds::group_layers
),
]
}
/// Duplicate Layer, into the same document or a new one.
fn duplication() -> Vec<CommandSpec> {
vec![cmd!(
"layer.duplicate",
"Duplicate Layer…",
["Layer"],
None,
r##"{"layer":id?,"inPlace":bool=false (artboards: keep the copy on the original instead of beside it),"name":str? (one layer: the copy's name),"document":index|"new"=same document (Photoshop's Destination: "new" makes a new document the size of this canvas holding just the copies),"documentName":str? (the new document's name)} (no layer: every selected layer)"##,
has_layer,
|s, p| {
if let Some(d) = p.get("document") {
if d.as_str() == Some("new") {
return crate::layer_copy_cmds::duplicate_to_new_document(s, p);
}
let same = d.as_u64().is_some_and(|i| s.active_index().is_some_and(|a| i == a as u64));
if !same {
return Err(EngineError::BadParams {
cmd: "layer.duplicate".into(),
msg: if d.as_u64().is_some() {
"the destination is another open document (use layer.copyToDocument)".into()
} else {
"`document` must be a document index or \"new\"".into()
},
});
}
}
let in_place = p.get("inPlace").and_then(Value::as_bool).unwrap_or(false);
let name = p.get("name").and_then(Value::as_str).filter(|n| !n.is_empty()).map(str::to_string);
if crate::layer_multi_cmds::multi(s, p) {
return crate::layer_multi_cmds::duplicate_selected(s, in_place, "Duplicate Layers");
}
let id = layer_param(s, p)?;
let add_copy = layer_panel_option(s, "addCopyToCopiedLayersAndGroups", true);
// The dialog offers Duplicate Layer's own name: only a different one was typed (#9023).
let mut typed = None;
let mut shift = (0, 0);
let nid = s.edit("Duplicate Layer", |doc, active| {
let mut dup = layer_copy(doc, id, add_copy)?;
if let Some(name) = name.as_ref().filter(|n| **n != dup.name) {
dup.name.clone_from(name);
typed = Some(name.clone());
}
let nid = doc.insert_above(Some(id), dup);
// A lone copy joins its original's link group, as in the reference application (#11217).
crate::layer_multi_cmds::relink_copies(doc, &[nid])?;
if !in_place {
shift = crate::artboard_cmds::place_copy(doc, nid)?;
}
*active = Some(nid);
Ok(nid)
})?;
crate::artboard_cmds::follow_shift(s, shift);
if let Some(name) = typed {
crate::type_cmds::note_typed_name(s, nid, &name);
}
Ok(json!({ "layer": nid.0 }))
}
)]
}
/// Deleting and selecting layers, and setting their properties.
fn deletion_and_selection() -> Vec<CommandSpec> {
vec![
cmd!("layer.delete", "Delete Layer", ["Layer", "Delete"], None, r##"{"layer":id?} (no layer: every selected layer)"##, has_layer, |s, p| {
if crate::layer_multi_cmds::multi(s, p) {
return crate::layer_multi_cmds::delete_selected(s);
}
let id = layer_param(s, p)?;
s.edit("Delete Layer", |doc, active| {
let neighbours = crate::layer_multi_cmds::deletion_neighbours(doc, id);
let before = crate::clip_group::Before::read(doc, &[id]);
doc.remove(id).ok_or(EngineError::NoLayer(id))?;
crate::clip_group::settle(doc, &[], &before, false);
if doc.layers.is_empty() {
return Err(EngineError::Other("a document must keep at least one layer".into()));
}
if active.is_some_and(|current| doc.layer(current).is_none()) {
*active = neighbours.into_iter().find(|candidate| doc.layer(*candidate).is_some());
}
Ok(())
})?;
Ok(Value::Null)
}),
cmd!(
"layer.select",
"Select Layer",
[],
None,
r##"{"layer":id|str|{"index":uint}|{"ordinal":"Trgt|Frwr|Bckw|Frnt|Back"} | "name":str,"occurrence":index?,"mode":"replace|toggle|range|add|remove"="replace"} | {"layers":[id,…]} (layers: exactly these selected, the last active; typed references use the recorded full layer stack; name occurrence: zero-based document walk order; required for duplicate names; toggle = ⌘-click, range = ⇧-click, remove = deselect it, keeping at least one)"##,
has_doc,
crate::layer_multi_cmds::select
),
cmd!(
"layer.setProps",
"Layer Properties",
[],
None,
r##"{"layer":id?,"layers":[id,…]? (the same change to each, one step: the Layers panel's controls with several layers selected),"name":str? (one layer only),"visible":bool?,"opacity":0..1?,"fill":0..1?,"blend":"Multiply|…"?,"clipped":bool?,"locked":bool?,"locks":{"transparency","pixels","position","artboard","all":bool}?,"channels":[bool,…]? (Advanced Blending: which colour channels blend, R G B / C M Y K / L a b)}"##,
has_layer,
set_props
),
]
}
/// Arranging layers and clipping masks.
fn order_and_clipping() -> Vec<CommandSpec> {
vec![
cmd!("layer.arrange.bringForward", "Bring Forward", ["Layer", "Arrange"], Some("Cmd+]"), r##"{"layer":id?}"##, has_layer, |s, p| arrange(s, p, 1)),
cmd!("layer.arrange.sendBackward", "Send Backward", ["Layer", "Arrange"], Some("Cmd+["), r##"{"layer":id?}"##, has_layer, |s, p| arrange(s, p, -1)),
cmd!("layer.arrange.bringToFront", "Bring to Front", ["Layer", "Arrange"], Some("Cmd+Shift+]"), r##"{"layer":id?}"##, has_layer, |s, p| arrange(
s,
p,
i32::MAX
)),
cmd!("layer.arrange.sendToBack", "Send to Back", ["Layer", "Arrange"], Some("Cmd+Shift+["), r##"{"layer":id?}"##, has_layer, |s, p| arrange(
s,
p,
i32::MIN
)),
cmd!(
"layer.createClippingMask",
"Create Clipping Mask",
["Layer"],
Some("Cmd+Alt+G"),
r##"{"layer":id?} (no layer: every selected layer but the lowest clips to the layer below it)"##,
has_layer,
|s, p| set_clipped(s, p, true)
),
cmd!(
"layer.releaseClippingMask",
"Release Clipping Mask",
["Layer"],
None,
r##"{"layer":id?} (no layer: every selected layer)"##,
has_layer,
|s, p| set_clipped(s, p, false)
),
]
}
/// Layer mask commands.
fn masks() -> Vec<CommandSpec> {
vec![
cmd!(
"layer.layerMask.revealAll",
"Reveal All",
["Layer", "Layer Mask"],
None,
r##"{"layer":id?} (no layer: every selected layer that can take a mask)"##,
has_layer,
|s, p| set_mask(s, p, "Add Layer Mask", Some(LayerMask::reveal_all()))
),
cmd!(
"layer.layerMask.hideAll",
"Hide All",
["Layer", "Layer Mask"],
None,
r##"{"layer":id?} (no layer: every selected layer that can take a mask)"##,
has_layer,
|s, p| set_mask(s, p, "Add Layer Mask", Some(LayerMask::hide_all()))
),
cmd!(
"layer.layerMask.revealSelection",
"Reveal Selection",
["Layer", "Layer Mask"],
None,
r##"{"layer":id?} (no layer: every selected layer that can take a mask)"##,
has_selection,
|s, p| {
let sel = s.active().and_then(|d| d.doc.selection.clone()).ok_or(EngineError::Other("no selection".into()))?;
let mask = LayerMask { surface: sel, ..LayerMask::reveal_all() };
// The selection becomes the mask, so Photoshop drops it (as Hide Selection does): a
// following Invert (⌘I) on the targeted mask then inverts all of it, not just the
// part inside the old selection. Same undo step as the mask.
set_mask_and_deselect(s, p, "Add Layer Mask", mask)
}
),
cmd!("layer.layerMask.delete", "Delete", ["Layer", "Layer Mask"], None, r##"{"layer":id?}"##, has_layer, |s, p| set_mask(
s,
p,
"Delete Layer Mask",
None
)),
cmd!(
"layer.layerMask.moveTo",
"Move Layer Mask",
[],
None,
r##"{"layer":id? (the mask's layer, default active),"to":id|name (the layer or group it goes to; a recorded step names it),"toOccurrence":n? (which of several layers named `to`, in document order),"copy":bool=false (⌥-drag: a copy goes and the original stays),"replace":bool=false (replace a mask already there; otherwise refused)} → {layer,to,copy}"##,
has_layer,
move_mask
),
]
}
/// Merge Down, Merge Group and Flatten Image.
fn merging() -> Vec<CommandSpec> {
vec![
cmd!("layer.mergeDown", "Merge Down", ["Layer"], None, r##"{"layer":id?}"##, has_layer, |s, p| {
let id = layer_param(s, p)?;
s.edit("Merge Down", |doc, active| {
let path = doc.path_of(id).ok_or(EngineError::NoLayer(id))?;
let Some((&idx, parent)) = path.split_last() else { return Err(EngineError::NoLayer(id)) };
if idx == 0 {
return Err(EngineError::Other("no layer below to merge into".into()));
}
let mut below = parent.to_vec();
below.push(idx - 1);
let lower = doc.layer_at(&below).ok_or(EngineError::NoLayer(id))?.clone();
let upper = doc.layer(id).ok_or(EngineError::NoLayer(id))?.clone();
let merged = pixels::merge_down(doc, &lower, &upper);
doc.remove(id);
*doc.layer_at_mut(&below).ok_or(EngineError::NoLayer(lower.id))? = merged;
*active = Some(lower.id);
Ok(())
})?;
Ok(Value::Null)
}),
cmd!("layer.mergeGroup", "Merge Group", ["Layer"], None, r##"{"layer":id?}"##, has_layer, |s, p| {
let id = layer_param(s, p)?;
if !s.active().and_then(|d| d.doc.layer(id)).is_some_and(|l| matches!(l.content, LayerContent::Group(_))) {
return Err(EngineError::Other("Merge Group needs a group".into()));
}
merge_group(s, id)
}),
cmd!("layer.flattenImage", "Flatten Image", ["Layer"], None, "{}", has_doc, |s, _| {
s.edit("Flatten Image", |doc, active| {
let fmt = doc.pixel_format();
let mut bg = Layer::raster("Background", fmt);
bg.locks.transparency = true;
bg.locks.position = true;
*crate::pixels_mut(&mut bg)? = photocraft_compose::flatten_to_surface(doc, fmt, Some([1.0, 1.0, 1.0]));
*active = Some(bg.id);
doc.layers = vec![bg].into();
Ok(())
})?;
Ok(Value::Null)
}),
]
}
/// Solid color fill layer.
fn solid_color_fill() -> Vec<CommandSpec> {
vec![cmd!(
"layer.newFillLayer.solidColor",
"Solid Color…",
["Layer", "New Fill Layer"],
None,
r##"{"color":"#rrggbb"=foreground,"cmyk":[c,m,y,k]? (inks 0..1 the colour was picked as: a CMYK document's fill holds exactly these; default the foreground's CMYK pick),"path":"work"|saved path name|{…path}? (the active path: becomes the vector mask, making a shape; else the selection is the layer mask)}"##,
has_doc,
|s, p| {
let c = color_param("layer.newFillLayer.solidColor", p, "color", s.tools.foreground)?;
// The inks the colour was picked as, so CMYK 50/50/50/100 stays 50/50/50/100 instead
// of what its sRGB stand-in converts back to through the document profile (#8568).
let inks = match cmyk_param("layer.newFillLayer.solidColor", p, "cmyk")? {
Some(k) => Some(k),
None => s.tools.picked_cmyk([c[0], c[1], c[2]]),
};
let default_mask = layer_panel_option(s, "useDefaultMasksOnFillLayers", true);
let id = s.edit("New Color Fill Layer", |doc, active| {
let fill = match inks {
Some(k) if doc.mode == ColorMode::Cmyk => Fill::Solid(Color { mode: ColorMode::Cmyk, c: k, alpha: c[3] }),
_ => Fill::Solid(Color::rgba(c[0], c[1], c[2], c[3])).in_mode(doc.mode),
};
let mut l = Layer::new(doc.next_layer_name("Color Fill"), LayerContent::Fill(fill));
mask_new_layer(doc, &mut l, p, "layer.newFillLayer.solidColor", default_mask)?;
let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto);
*active = Some(id);
Ok(id)
})?;
Ok(json!({ "layer": id.0 }))
}
)]
}
/// Editing an adjustment layer's properties.
fn adjustments() -> Vec<CommandSpec> {
vec![cmd!(
"layer.setAdjustment",
"Adjustment Properties",
[],
None,
r##"{"layer":id?, …params of that adjustment kind} (Levels, Curves: "eyedropper":{"point":"black|gray|white","at":[x,y],"size":1..101=1} or {"point",…,"color":[r,g,b] 0..1} = the Properties panel's Set Black/Neutral Gray/White Point, sampling the image below the layer, RGB and Grayscale (no gray) only)"##,
has_layer,
|s, p| {
let id = layer_param(s, p)?;
let eyedropped = crate::adjust_params::layer_eyedropper(s, id, p)?;
s.edit("Modify Adjustment", |doc, _| {
let mode = doc.mode;
let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
let LayerContent::Adjustment(adj) = &mut l.content else { return Err(EngineError::Other("not an adjustment layer".into())) };
if matches!(adj, Adjustment::Unsupported { .. }) {
return Err(EngineError::Other("this adjustment can't be edited (kept as imported)".into()));
}
let kind = adjustment_kind(adj);
// No params resets to the defaults; otherwise params merge over the current values.
*adj = if let Some(eyedropped) = eyedropped {
eyedropped
} else if crate::adjust_params::user_keys(p).is_empty() {
crate::adjust_params::default_for(kind, mode)?
} else {
crate::adjust_params::from_params(kind, p, Some(adj), mode)?
};
Ok(())
})?;
Ok(Value::Null)
}
)]
}
/// Moving layers in the stack and on the canvas.
fn placement() -> Vec<CommandSpec> {
vec![
cmd!(
"layer.moveTo",
"Reorder Layer",
[],
None,
r##"{"layer":id|{"index":uint}|{"ordinal":"Trgt|Frwr|Bckw|Frnt|Back"}?| "layers":[id,…]?, "target":id|name|{"index":uint},"targetOccurrence":n? (which of several layers named `target`, in document order),"position":"above|below|into"="above","copy":bool=false} (typed target: pre-move recorded stack boundary, omit position; layers: one undoable move, document order preserved; copy: place duplicates there and leave the layers, as ⌥-dragging a Layers panel row; recorded typed references retain their form)"##,
has_layer,
crate::layer_multi_cmds::move_to
),
cmd!(
"layer.translate",
"Move Layer",
[],
None,
r##"{"layer":id?,"dx":i32,"dy":i32,"units":"px"|"pt"="px" (pt: points, whole pixels at the document's resolution),"target":"pixels"|"mask"="pixels","selection":bool=false,"wrap":bool=false,"nest":bool=false} → null | {nested:[id]} (no layer: every selected layer; linked layers follow; target mask: a layer whose mask is unlinked moves that mask alone, a linked mask moves with the layer; selection: the selection moves too, in the same step; wrap: View › Pattern Preview, pixels that leave the canvas come back on the opposite edge so the tile stays seamless; nest: auto-nesting as the Move tool does it, a layer whose bounds centre lands on another artboard joins it and one whose centre is off every artboard leaves for the top level; a clipping base takes the layers clipped to it along and a clipped layer goes only where its base goes; artboards, the Background, empty layers, layers whose board doesn't change, groups that would nest too deep and layers locked with Prevent Auto-Nesting (on the layer, a group around it or the destination board) stay put, with their whole clipping group; nested lists the layers that changed board)"##,
has_layer,
crate::layer_multi_cmds::translate
),
]
}
/// Applies layer.setProps to its target layers as one history step.
fn set_props(s: &mut Session, p: &Value) -> Result<Value> {
let ids = prop_targets(s, p)?;
if ids.len() > 1 && p.get("name").is_some() {
return Err(bad("layer.setProps", "`name` renames one layer, not several"));
}
let (opacity, fill) = (unit_prop(p, "opacity")?, unit_prop(p, "fill")?);
let label = props_label(p);
// The eye: a history state only with History Options › Make Layer Visibility
// Changes Undoable.
let record = label != "Layer Visibility" || s.visibility_undoable();
s.edit_with(label, record, |doc, _| {
// The Background has no opacity, fill or blend mode: like Photoshop, setting
// one that changes its look turns it into a normal layer ("Layer 0") first.
let num = |k: &str| p.get(k).and_then(Value::as_f64).is_some_and(|v| v < 1.0);
let blends = p.get("blend").and_then(Value::as_str).and_then(parse_blend).is_some_and(|b| b != photocraft_color::BlendMode::Normal);
for &id in &ids {
if num("opacity") || num("fill") || blends {
crate::extra_cmds::background_to_layer(doc, id);
}
let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
apply_props(l, p, opacity, fill)?;
}
Ok(())
})?;
// The Layers panel's in-place rename: a name the user typed (#9023).
if let (Some(name), [id]) = (p.get("name").and_then(Value::as_str), ids.as_slice()) {
crate::type_cmds::note_typed_name(s, *id, name);
}
Ok(Value::Null)
}
/// Several layers at once (the Layers panel with several selected, as in Photoshop),
/// else the given or active one.
fn prop_targets(s: &Session, p: &Value) -> Result<Vec<LayerId>> {
match p.get("layers") {
None | Some(Value::Null) => Ok(vec![layer_param(s, p)?]),
Some(Value::Array(a)) if !a.is_empty() && a.len() <= 10_000 => {
let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
let mut ids = Vec::with_capacity(a.len());
for v in a {
let id = v.as_u64().map(LayerId).ok_or_else(|| bad("layer.setProps", format!("`layers` holds layer ids, got {v}")))?;
if doc.layer(id).is_none() {
return Err(EngineError::NoLayer(id));
}
if !ids.contains(&id) {
ids.push(id);
}
}
Ok(ids)
}
Some(v) => Err(bad("layer.setProps", format!("`layers` is a non-empty list of layer ids, got {v}"))),
}
}
/// Opacity and Fill are fractions here, while the Layer Style commands take
/// percentages: a value outside 0..1 is refused, never clamped to 100 % (#5242).
fn unit_prop(p: &Value, key: &str) -> Result<Option<f32>> {
let Some(v) = p.get(key) else { return Ok(None) };
match v.as_f64() {
Some(x) if (0.0..=1.0).contains(&x) => Ok(Some(x as f32)),
_ => Err(bad("layer.setProps", format!("{key} must be a number in 0..1 (1 = 100 %), got {v}"))),
}
}
/// Photoshop's History names for a single kind of change; a mix is "Layer Properties".
fn props_label(p: &Value) -> &'static str {
let changed: Vec<&str> =
p.as_object().map(|o| o.keys().map(String::as_str).filter(|k| !matches!(*k, "layer" | "layers" | "coalesce")).collect()).unwrap_or_default();
match changed.as_slice() {
["visible"] => "Layer Visibility",
["opacity"] => "Opacity Change",
["fill"] => "Fill Opacity Change",
["blend"] => "Blending Change",
["name"] => "Rename Layer",
_ => "Layer Properties",
}
}
/// Sets the requested name, visibility, opacity, fill and blend mode on one layer.
fn apply_props(l: &mut Layer, p: &Value, opacity: Option<f32>, fill: Option<f32>) -> Result<()> {
if let Some(v) = p.get("name").and_then(Value::as_str) {
l.name = v.to_string();
}
if let Some(v) = p.get("visible").and_then(Value::as_bool) {
l.visible = v;
}
if let Some(v) = opacity {
l.opacity = v;
}
if let Some(v) = fill {
l.fill_opacity = v;
}
if let Some(v) = p.get("blend").and_then(Value::as_str) {
l.blend = blend_prop(l, v)?;
}
apply_clip_and_locks(l, p)
}
/// Sets the requested clipping, channel and lock flags on one layer.
fn apply_clip_and_locks(l: &mut Layer, p: &Value) -> Result<()> {
if let Some(v) = p.get("clipped").and_then(Value::as_bool) {
l.clipped = v;
}
if let Some(v) = p.get("locked").and_then(Value::as_bool) {
l.locks.all = v;
}
if let Some(Value::Array(ch)) = p.get("channels") {
// Blending Options › Advanced Blending › Channels: unchecked = left out.
l.excluded_channels = ch.iter().take(32).enumerate().filter(|(_, v)| v.as_bool() == Some(false)).fold(0, |m, (i, _)| m | 1 << i);
}
if let Some(Value::Object(m)) = p.get("locks") {
set_locks(l, m)?;
}
Ok(())
}
/// Parses a blend mode for the layer, refusing Pass Through on anything but a group.
fn blend_prop(l: &Layer, v: &str) -> Result<BlendMode> {
let b = parse_blend(v).ok_or_else(|| bad("layer.setProps", format!("unknown blend mode `{v}`")))?;
// Pass Through is a group's mode only, as in Photoshop.
if b == BlendMode::PassThrough && !l.is_group() {
return Err(bad("layer.setProps", format!("Pass Through applies to groups only; layer {} isn't one", l.id.0)));
}
Ok(b)
}
/// Sets each named lock, refusing an unknown name.
fn set_locks(l: &mut Layer, m: &serde_json::Map<String, Value>) -> Result<()> {
for (k, v) in m {
let v = v.as_bool().unwrap_or(false);
if !l.locks.set(k, v) {
return Err(bad("layer.setProps", format!("unknown lock `{k}`")));
}
}
Ok(())
}
+2
View File
@@ -0,0 +1,2 @@
pub(crate) mod edit_menu;
pub(crate) mod stroke;
@@ -0,0 +1,14 @@
use crate::cmd::{CommandSpec, has_pixel_or_channel};
/// Edit menu: Fill.
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"edit.fill",
"Fill…",
["Edit"],
Some("Shift+F5"),
r##"{"contents":"foreground|background|color|contentAware|pattern|history|black|gray|white"="color","color":"#rrggbb|[r,g,b,a]"=foreground (contents=color),"pattern":id|name (contents=pattern),"scale":%=100,"angle":deg,"state":row?,"snapshot":id? (contents=history: a History panel row as history.setSource, redo rows last, or a snapshot; default the History Brush source),"colorAdaptation":bool=true,"scaleAdaptation":bool=false,"mirror":bool=false,"rotationAdaptation":bool=false (contents=contentAware: enable quarter-turn source candidates within the sampling budget),"mode":"normal|multiply|…"="normal","opacity":0..100=100,"preserveTransparency":bool=false,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}?}"##,
has_pixel_or_channel,
crate::fill_cmds::fill
)]
}
@@ -0,0 +1,14 @@
use crate::cmd::{CommandSpec, has_paintable};
/// Painting: the stroke command.
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"paint.stroke",
"Brush Stroke",
[],
None,
r##"{"points":[[x,y,pressure?,tiltX?,tiltY?,rotation?,timeMs?,wheel?],…],"brush":{…BrushSettings}?,"preset":name?,"size":0.5..5000 px?,"hardness":0..1?,"opacity":0..1?,"flow":0..1?,"fill":bool=false (fill the region the closed `points` enclose with the brush colour, its edge anti-aliased and softened by hardness, instead of stamping the outline; a closed gesture paints a filled dab, not a ring),"spacing":0..10?,"color":"#rrggbb"?=foreground,"mode":"normal|multiply|screen|…|clear (erases with this brush)"="normal","erase":bool?,"smoothing":0..1?,"zoom":number=1,"seed":u64?,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}=Channels panel target}"##,
has_paintable,
crate::brush_cmds::paint_stroke
)]
}
+2
View File
@@ -0,0 +1,2 @@
pub(crate) mod file_menu;
pub(crate) mod layer_menu;
@@ -0,0 +1,76 @@
use crate::cmd::{Color, ColorMode, CommandSpec, Document, EngineError, Layer, SampleType, Size, Value, always, json, parse_hex};
/// File menu: New (new documents take their presets from the document preset store).
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![
// File
cmd!(
"file.new",
"New…",
["File"],
Some("Cmd+N"),
r##"{"width":1..300000=1920,"height":1..300000=1080 (pixel counts are rounded),"mode":"bitmap|rgb|gray|grayscale|cmyk|lab"="rgb","depth":8|16|32=8 (bitmap: 1, its only depth),"background":"white|black|backgroundColor|transparent|#rrggbb"="white" (bitmap: not transparent),"backgroundColor":[r,g,b]? (0..1; defaults to toolbox colour),"resolution":1..30000=72 (ppi),"name":str,"artboard":bool=false (one artboard over the canvas, its background the chosen one, holding an empty Layer 1; no Background layer),"profile":"working"|built-in id|path to an .icc file="working" (the colour profile it is tagged with; it must suit the mode)}"##,
always,
|s, p| {
use crate::document_preset_cmds::{MAX_DIMENSION, MAX_RESOLUTION, background_color, color_mode, sample_type};
crate::document_preset_cmds::validate_new_params(s, p)?;
// A size given as a float (`512.0`, as JSON from a UI field) is still that size (#254).
let px = |k: &str, d: u32| match p.get(k) {
Some(v) => v
.as_u64()
.map(|n| n.clamp(1, MAX_DIMENSION as u64) as u32)
.or_else(|| v.as_f64().filter(|f| f.is_finite()).map(|f| f.round().clamp(1.0, MAX_DIMENSION as f64) as u32))
.unwrap_or(d),
None => d,
};
let (w, h) = (px("width", 1920), px("height", 1080));
let mode = color_mode(p.get("mode").and_then(Value::as_str).unwrap_or("rgb")).unwrap_or(ColorMode::Rgb);
// A 1-bit Bitmap document is stored as 8-bit gray, like a converted Bitmap image.
let depth = sample_type(p.get("depth").and_then(Value::as_u64).unwrap_or(8)).filter(|_| mode != ColorMode::Bitmap).unwrap_or(SampleType::U8);
let name = p.get("name").and_then(Value::as_str).unwrap_or("Untitled").to_string();
let res = p.get("resolution").and_then(Value::as_f64).unwrap_or(72.0).clamp(1.0, MAX_RESOLUTION) as f32;
// The background colour; `None` for Transparent.
let background = match p.get("background").and_then(Value::as_str).unwrap_or("white") {
"backgroundColor" => {
let bgc = background_color(p, s.tools.background, "file.new")?;
Some(Color::rgba(bgc[0], bgc[1], bgc[2], 1.0))
}
"transparent" => None,
"black" => Some(Color::BLACK),
other => {
let c = parse_hex(other).unwrap_or([1.0; 4]);
Some(Color::rgba(c[0], c[1], c[2], c[3]))
}
};
let mut doc = if p.get("artboard").and_then(Value::as_bool).unwrap_or(false) {
crate::artboard_cmds::new_artboard_document(name, Size::new(w, h), mode, depth, background)
} else if let Some(c) = background {
Document::with_background(name, Size::new(w, h), mode, depth, c)
} else {
let mut d = Document::new(name, Size::new(w, h), mode, depth);
d.layers.push(Layer::raster("Layer 1", d.pixel_format()));
d
};
doc.resolution_dpi = res;
// Photoshop's New Document › Color Profile: tag the document with another profile
// than the working space (#321). Checked before the document opens.
if let Some(spec) = p.get("profile").and_then(Value::as_str).filter(|spec| !matches!(*spec, "working" | "none")) {
let prof = s.color.resolve(spec, Some(&doc), None)?;
if prof.color_space != crate::color_cmds::mode_space(doc.mode) {
return Err(EngineError::BadParams {
cmd: "file.new".into(),
msg: format!("profile `{}` is {:?}; the document is {:?}", prof.description, prof.color_space, doc.mode),
});
}
doc.icc_profile = Some(prof.to_bytes());
}
let i = s.add_document(doc, None);
// A new document's first History state is "New"; opened files keep "Open" (#14029).
if let Some(st) = s.active_mut() {
st.history.set_current_label("New");
}
Ok(json!({ "document": i }))
}
),
]
}
@@ -0,0 +1,43 @@
use crate::cmd::{Color, CommandSpec, Fill, Layer, LayerContent, Value, color_param, has_doc, json, layer_panel_option, mask_new_layer};
/// Layer menu: the gradient fill layer.
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"layer.newFillLayer.gradient",
"Gradient…",
["Layer", "New Fill Layer"],
None,
r##"{"from":"#rrggbb","to":"#rrggbb","angle":deg=90,"style":"linear|radial|angle|reflected|diamond","reverse":bool,"path":"work"|saved path name|{…path}? (the active path: becomes the vector mask; else the selection is the layer mask),"stops"?,"transparency"?,"midpoints"?,"scale"?,"offset"?,"dither"?,"align"? (as gradient.fill.set; stops replace from/to)}"##,
has_doc,
|s, p| {
let a = color_param("layer.newFillLayer.gradient", p, "from", s.tools.foreground)?;
let b = color_param("layer.newFillLayer.gradient", p, "to", s.tools.background)?;
let angle = crate::gradient_fill_cmds::angle_param("layer.newFillLayer.gradient", p, 90.0)?;
let style = crate::layer_style::gradient_style(p.get("style").and_then(Value::as_str).unwrap_or("linear"));
let reverse = p.get("reverse").and_then(Value::as_bool).unwrap_or(false);
let default_mask = layer_panel_option(s, "useDefaultMasksOnFillLayers", true);
// The rest of a recorded Gradient Fill (a loaded action's Make): applied as
// `gradient.fill.set` would, in the same step.
let rest: serde_json::Map<String, Value> = ["stops", "transparency", "midpoints", "scale", "offset", "dither", "align"]
.iter()
.filter_map(|k| p.get(*k).map(|v| ((*k).to_string(), v.clone())))
.collect();
let (fg, bg) = (s.tools.foreground, s.tools.background);
let id = s.edit("New Gradient Fill Layer", |doc, active| {
let mut fill =
Fill::gradient(vec![(0.0, Color::rgba(a[0], a[1], a[2], a[3])), (1.0, Color::rgba(b[0], b[1], b[2], b[3]))], angle, 1.0, style, reverse);
if !rest.is_empty() {
let l = Layer::new(String::new(), LayerContent::Fill(fill.clone()));
fill = crate::gradient_fill_cmds::apply_set(&l, &fill, doc.bounds(), &Value::Object(rest.clone()), fg, bg)?;
}
let fill = fill.in_mode(doc.mode);
let mut l = Layer::new(doc.next_layer_name("Gradient Fill"), LayerContent::Fill(fill));
mask_new_layer(doc, &mut l, p, "layer.newFillLayer.gradient", default_mask)?;
let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto);
*active = Some(id);
Ok(id)
})?;
Ok(json!({ "layer": id.0 }))
}
)]
}
+28 -1
View File
@@ -278,11 +278,35 @@ fn apply_data_set(s: &mut Session, p: &Value) -> Result<Value> {
let (set, idx) = resolve_set(s, p, "image.applyDataSet")?;
let vars = s.active().ok_or(EngineError::NoDocument)?.doc.variables.clone();
authorize_pixel_paths(s, &set)?;
s.edit("Apply Data Set", |doc, _| apply_to_doc(doc, &vars, &set))?;
// One history state named exactly "Apply Data Set", whatever the set is called (#14498).
let label = "Apply Data Set";
if replaces_locked_text(&s.active().ok_or(EngineError::NoDocument)?.doc, &vars, &set) {
// As in the reference application, nothing of the set is applied, but the attempt is
// still a history state (one that changes nothing), and the alert names no layer (#14499).
s.edit(label, |_, _| Ok(()))?;
return Err(EngineError::Other(DATA_SET_LAYER_LOCKED.into()));
}
s.edit(label, |doc, _| apply_to_doc(doc, &vars, &set))?;
set_vars(s, |v| v.active = Some(idx))?;
Ok(json!({"applied": set.name, "index": idx}))
}
/// The reference application's alert when Apply Data Set would replace the text of a layer
/// under Lock All.
pub const DATA_SET_LAYER_LOCKED: &str = "Could not apply data set because the layer is locked.";
/// Whether `set` has a Text value for a type layer with its own Lock All. Visibility and Pixel
/// Replacement values still apply to locked layers, as in the reference application; partial
/// locks and a locked group were not measured and keep applying (#14499).
fn replaces_locked_text(doc: &Document, vars: &Variables, set: &DataSet) -> bool {
set.values.iter().any(|dv| {
matches!(dv.value, VarValue::Text(_))
&& vars.def(&dv.variable).is_some_and(|def| {
matches!(def.kind, VarKind::TextReplacement) && doc.layer(def.layer).is_some_and(|l| l.locks.all && matches!(l.content, LayerContent::Text(_)))
})
})
}
/// Resolve a data set from `{name}` or `{index}`.
fn resolve_set(s: &Session, p: &Value, cmd: &str) -> Result<(DataSet, usize)> {
let vars = &s.active().ok_or(EngineError::NoDocument)?.doc.variables;
@@ -575,5 +599,8 @@ mod tests;
#[cfg(test)]
mod import_enabled_tests;
#[cfg(test)]
mod locked_text_layer_tests;
#[cfg(test)]
mod apply_history_name_tests;
@@ -0,0 +1,208 @@
//! #14499: Apply Data Set refuses with the reference application's alert when a Text value would
//! replace the text of a type layer under Lock All. Nothing of the set is applied, but one history
//! state that changes nothing is still added. Visibility and Pixel Replacement values keep
//! applying to locked layers; partial locks and Data Sets as Files keep today's behaviour.
use super::*;
use photocraft_doc::{Layer, Locks, TextLayer};
use photocraft_geom::Rect;
const APPLY: &str = "image.applyDataSet";
/// A document with a raster layer "photo", a red raster "badge" and a text layer "title", bound
/// to the variables `photo` (pixels), `showBadge`, `showTitle` (visibility) and `headline` (text).
fn session() -> (Session, LayerId, LayerId, LayerId) {
let mut s = Session::new();
s.execute("file.new", json!({"width": 64, "height": 48})).unwrap();
let (photo, badge, title) = s
.edit("setup", |doc, _| {
let fmt = doc.pixel_format();
let mut photo = Layer::raster("photo", fmt);
photo.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 64, 48), &photocraft_raster::from_rgba(&fmt, [0.5, 0.5, 0.5, 1.0]));
let mut badge = Layer::raster("badge", fmt);
badge.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 10, 10), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0]));
let title = Layer::new("title", LayerContent::Text(TextLayer { text: "Old".into(), ..Default::default() }));
let ids = (photo.id, badge.id, title.id);
doc.layers.extend([photo, badge, title]);
Ok(ids)
})
.unwrap();
s.execute(
"image.variables.define",
json!({"defs": [
{"name": "photo", "layer": photo.0, "type": "pixelReplacement", "method": "conform"},
{"name": "showBadge", "layer": badge.0, "type": "visibility"},
{"name": "showTitle", "layer": title.0, "type": "visibility"},
{"name": "headline", "layer": title.0, "type": "textReplacement"},
]}),
)
.unwrap();
(s, photo, badge, title)
}
/// A blue 8x8 PNG for the `photo` variable.
fn blue_png(name: &str) -> (String, String) {
let dir = std::env::temp_dir().join(format!("pc-vars-{}-locked-{name}", std::process::id()));
let _ = std::fs::create_dir_all(&dir);
let png = dir.join("blue.png");
let mut src = Session::new();
src.execute("file.new", json!({"width": 8, "height": 8, "background": "#0000ff"})).unwrap();
let bytes = photocraft_io::export(&src.active().unwrap().doc, "png", &photocraft_io::ExportOptions::default()).unwrap().bytes;
std::fs::write(&png, bytes).unwrap();
(dir.to_string_lossy().into_owned(), png.to_string_lossy().into_owned())
}
fn data_sets(s: &mut Session, sets: Value) {
s.execute("image.variables.dataSets", json!({ "dataSets": sets })).unwrap();
}
fn lock(s: &mut Session, id: LayerId, locks: Locks) {
s.edit("lock", |doc, _| {
doc.layer_mut(id).unwrap().locks = locks;
Ok(())
})
.unwrap();
}
fn all() -> Locks {
Locks { all: true, ..Locks::default() }
}
fn doc(s: &Session) -> &Document {
&s.active().unwrap().doc
}
fn text_of(s: &Session, id: LayerId) -> String {
match &doc(s).layer(id).unwrap().content {
LayerContent::Text(t) => t.text.clone(),
_ => panic!("not a text layer"),
}
}
fn visible(s: &Session, id: LayerId) -> bool {
doc(s).layer(id).unwrap().visible
}
fn pixel(s: &Session, id: LayerId) -> Vec<f32> {
doc(s).layer(id).unwrap().surface().unwrap().pixel(32, 24)
}
fn history(s: &Session) -> (usize, Option<String>) {
let h = &s.active().unwrap().history;
(h.past_len(), h.entries().last().map(|e| e.to_string()))
}
#[test]
fn a_text_value_for_a_locked_type_layer_applies_nothing_and_alerts() {
let (mut s, photo, badge, title) = session();
let (dir, png) = blue_png("refuse");
data_sets(
&mut s,
json!([{"name": "Zed", "values": [
{"variable": "photo", "kind": "pixels", "value": png},
{"variable": "showBadge", "kind": "visibility", "value": false},
{"variable": "showTitle", "kind": "visibility", "value": false},
{"variable": "headline", "kind": "text", "value": "Alpha\rLine2"},
]}]),
);
lock(&mut s, title, all());
let photo_before = pixel(&s, photo);
let (n, _) = history(&s);
let r = s.execute(APPLY, json!({"name": "Zed"}));
assert!(matches!(&r, Err(EngineError::Other(m)) if m == DATA_SET_LAYER_LOCKED), "{r:?}");
assert_eq!(DATA_SET_LAYER_LOCKED, "Could not apply data set because the layer is locked.");
// Nothing of the set: the text, both visibilities and the photo's pixels stay.
assert_eq!(text_of(&s, title), "Old");
assert!(visible(&s, title) && visible(&s, badge));
assert_eq!(pixel(&s, photo), photo_before);
assert_eq!(doc(&s).variables.active, None, "the set did not become the applied one");
// One history state for the attempt, which changes nothing.
let (after, label) = history(&s);
assert_eq!(after, n + 1);
assert!(label.as_deref().is_some_and(|l| l.starts_with("Apply Data Set")), "{label:?}");
let applied = doc(&s).clone();
assert!(s.undo());
assert_eq!(history(&s).0, n);
assert_eq!(text_of(&s, title), "Old");
assert!(s.redo());
assert_eq!(doc(&s).layers, applied.layers, "the state changes nothing");
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn the_same_set_applies_once_the_layer_is_unlocked() {
let (mut s, _photo, badge, title) = session();
data_sets(
&mut s,
json!([{"name": "Zed", "values": [
{"variable": "showBadge", "kind": "visibility", "value": false},
{"variable": "headline", "kind": "text", "value": "Alpha"},
]}]),
);
lock(&mut s, title, all());
assert!(s.execute(APPLY, json!({"name": "Zed"})).is_err());
lock(&mut s, title, Locks::default());
s.execute(APPLY, json!({"name": "Zed"})).unwrap();
assert_eq!(text_of(&s, title), "Alpha");
assert!(!visible(&s, badge));
assert_eq!(doc(&s).variables.active, Some(0));
}
#[test]
fn visibility_values_still_apply_to_locked_layers() {
let (mut s, _photo, badge, title) = session();
data_sets(
&mut s,
json!([{"name": "Hide", "values": [
{"variable": "showBadge", "kind": "visibility", "value": false},
{"variable": "showTitle", "kind": "visibility", "value": false},
]}]),
);
lock(&mut s, badge, all());
lock(&mut s, title, all());
s.execute(APPLY, json!({"name": "Hide"})).unwrap();
assert!(!visible(&s, badge) && !visible(&s, title));
}
#[test]
fn pixel_replacement_still_applies_to_a_locked_pixel_layer() {
let (mut s, photo, _badge, _title) = session();
let (dir, png) = blue_png("pixels");
data_sets(&mut s, json!([{"name": "Blue", "values": [{"variable": "photo", "kind": "pixels", "value": png}]}]));
lock(&mut s, photo, all());
s.execute(APPLY, json!({"name": "Blue"})).unwrap();
assert_eq!(pixel(&s, photo), vec![0.0, 0.0, 1.0, 1.0]);
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn partial_locks_keep_applying_text() {
let partial = [
Locks { transparency: true, ..Locks::default() },
Locks { pixels: true, ..Locks::default() },
Locks { position: true, ..Locks::default() },
Locks { transparency: true, pixels: true, position: true, artboard: true, all: false },
];
for locks in partial {
let (mut s, _photo, _badge, title) = session();
data_sets(&mut s, json!([{"name": "T", "values": [{"variable": "headline", "kind": "text", "value": "New"}]}]));
lock(&mut s, title, locks);
s.execute(APPLY, json!({"name": "T"})).unwrap_or_else(|e| panic!("{locks:?}: {e}"));
assert_eq!(text_of(&s, title), "New", "{locks:?}");
}
}
#[test]
fn data_sets_as_files_keeps_exporting_a_locked_type_layer() {
let (mut s, _photo, _badge, title) = session();
data_sets(&mut s, json!([{"name": "T", "values": [{"variable": "headline", "kind": "text", "value": "New"}]}]));
lock(&mut s, title, all());
let dir = std::env::temp_dir().join(format!("pc-vars-{}-locked-export", std::process::id()));
let out = s.execute("file.export.dataSetsAsFiles", json!({"dir": dir.to_string_lossy(), "format": "png"})).unwrap();
assert_eq!(out["files"].as_array().map(Vec::len), Some(1), "{out}");
assert_eq!(text_of(&s, title), "Old", "the export leaves the document alone");
let _ = std::fs::remove_dir_all(dir);
}
+7 -1
View File
@@ -11,6 +11,9 @@ use crate::Session;
/// Photoshop's alert text.
pub const HIDDEN: &str = "Could not complete your request because the target layer is hidden.";
/// The Art History Brush's own alert text (#12638).
pub const ART_HISTORY_HIDDEN: &str = "Could not use the art history brush because the target layer is hidden.";
/// Commands that paint on, or move, the target layer.
const GATED: &[&str] = &[
"paint.stroke",
@@ -53,7 +56,10 @@ pub fn refusal(s: &Session, id: &str, params: &Value) -> Option<&'static str> {
}
let st = s.active()?;
let layer = crate::commands::layer_param(s, &params).ok()?;
(st.doc.layer(layer).is_some() && !shown(&st.doc, layer)).then_some(HIDDEN)
// The Art History Brush's text was measured on a layer's pixels only.
let pixels = crate::channel_cmds::target_of(&params) == crate::channel_cmds::Target::Pixels;
let why = if id == "paint.artHistoryBrush" && pixels { ART_HISTORY_HIDDEN } else { HIDDEN };
(st.doc.layer(layer).is_some() && !shown(&st.doc, layer)).then_some(why)
}
#[cfg(test)]
+1 -1
View File
@@ -45,7 +45,7 @@ pub mod select_mask_edits;
pub mod shell_commands;
pub mod shortcut_sets;
pub mod snap;
pub use variables_cmds::{export_data_sets_with, import_data_sets_text};
pub use variables_cmds::{DATA_SET_LAYER_LOCKED, export_data_sets_with, import_data_sets_text};
pub use video_cmds::render_video_with;
use std::sync::Arc;
+3 -2
View File
@@ -1553,8 +1553,9 @@ fn bevel_part(p: vec2<i32>, depth: f32, region: f32) -> f32 {
let shade = (n.x * op.p0.x + n.y * op.p0.y + n.z * op.p0.z) / len;
let se = op.p0.w;
var k = shade - se;
// effects::bevel_maps: the gloss contour maps the shading, a flat face's as the neutral (#7360).
if (op.p1.w > 0.5) { k = lut(0, shade) - lut(0, se); }
// effects::bevel_maps: the gloss contour maps the shading; a flat face's unmapped shading
// stays the neutral (#7360).
if (op.p1.w > 0.5) { k = lut(0, shade) - se; }
var v = 0.0;
if (op.p1.z > 0.5) {
if (k <= 0.0) { v = clamp(-k / max(se, 1e-3), 0.0, 1.0) * region; }
+5
View File
@@ -1703,6 +1703,10 @@ fn effect_cases() -> Vec<(&'static str, Vec<Effect>)> {
points: vec![Cp { input: 0.0, output: 1.0 }, Cp { input: 0.4, output: 0.4 }, Cp { input: 1.0, output: 0.0 }],
corners: vec![],
};
// The same contour under a high light, deep (altitude 69, 358 %): the unmapped flat shading
// stays the neutral, so only the slope facing away glints, on both renderers.
let mut bevel_gloss_high_alt = bevel_gloss_high.clone();
(bevel_gloss_high_alt.use_global_light, bevel_gloss_high_alt.angle, bevel_gloss_high_alt.altitude, bevel_gloss_high_alt.depth) = (false, 146.0, 69.0, 3.58);
vec![
("drop shadow", vec![Effect::DropShadow(shadow(BlendMode::Multiply, 0.75, 120.0, 6.0, 8.0, 0.0))]),
("drop shadow spread contour", vec![Effect::DropShadow(ds_contour)]),
@@ -1795,6 +1799,7 @@ fn effect_cases() -> Vec<(&'static str, Vec<Effect>)> {
),
("bevel contour own light", vec![Effect::BevelEmboss(bevel_contour)]),
("bevel gloss starting high", vec![Effect::BevelEmboss(bevel_gloss_high)]),
("bevel gloss starting high, high light", vec![Effect::BevelEmboss(bevel_gloss_high_alt)]),
("satin", vec![Effect::Satin(satin)]),
("satin inverted contour", vec![Effect::Satin(satin_inv)]),
("stroke outside colour", vec![Effect::Stroke(stroke(4.0, StrokePosition::Outside, FxPaint::Color(Color::rgb(0.95, 0.85, 0.1))))]),
+2 -6
View File
@@ -9,14 +9,10 @@ use photocraft_geom::Affine;
/// `brst` (channel blending restrictions): a list of big-endian u32 channel indices left out of
/// blending → a bit mask (bit `i` = channel `i`; indices above 31 are ignored).
pub fn parse_brst(data: &[u8]) -> u32 {
data.as_chunks::<4>().0.iter().map(|c| u32::from_be_bytes([c[0], c[1], c[2], c[3]])).filter(|&i| i < 32).fold(0, |m, i| m | 1 << i)
}
pub use craft_psd::tagged::channel_restrictions as parse_brst;
/// Inverse of [`parse_brst`]; `None` when every channel blends (no block).
pub fn brst_data(mask: u32) -> Option<Vec<u8>> {
(mask != 0).then(|| (0..32u32).filter(|i| mask & 1 << i != 0).flat_map(u32::to_be_bytes).collect())
}
pub use craft_psd::tagged::channel_restrictions_data as brst_data;
/// The Advanced Blending blocks, as (key, value for `a`, Photoshop's default value): `knko`
/// (0 none, 1 shallow, 2 deep), `infx`, `clbl`, `tsly`, `lmgm`, `vmgm`. Each is stored as one
+1 -1
View File
@@ -609,7 +609,7 @@ impl Ex<'_> {
None => raw.retain(|(k, _)| k != b"fxrp"),
}
// Advanced Blending channel restrictions: written from the field (in place).
match crate::blocks::brst_data(l.excluded_channels) {
match craft_psd::tagged::channel_restrictions_data(l.excluded_channels) {
Some(data) => match raw.iter_mut().find(|(k, _)| k == b"brst") {
Some(e) => e.1 = data,
None => raw.push((*b"brst", data)),
+1 -1
View File
@@ -479,7 +479,7 @@ impl Ctx<'_> {
// Advanced Blending channel restrictions (`brst`: the u32 ids of channels left out);
// also kept in `psd_blocks`, where export rewrites it from the field.
if let Some(b) = rec.block(b"brst") {
l.excluded_channels = crate::blocks::parse_brst(&b.data);
l.excluded_channels = craft_psd::tagged::channel_restrictions(&b.data);
}
// Advanced Blending (`knko`, `infx`, `clbl`, `tsly`, `lmgm`, `vmgm`); the blocks stay in
// `psd_blocks`, where export rewrites them from the field in place.
+52
View File
@@ -474,6 +474,58 @@ fn channel_restrictions_round_trip_as_brst() {
assert!(f.layers().iter().find(|r| r.name() == "a").unwrap().block(b"brst").is_none());
}
fn channel_restrictions_psd(payload: Vec<u8>) -> Vec<u8> {
use craft_psd::{LayerSpec, PixelData, PsdBuilder, TaggedBlock};
let mut layer = LayerSpec::new("restricted", 0, 0, 1, 1, PixelData::Rgba8(vec![80, 120, 160, 255]));
layer.extra_blocks = vec![TaggedBlock::new(*b"zBef", vec![1, 2, 3, 4]), TaggedBlock::new(*b"brst", payload), TaggedBlock::new(*b"zAft", vec![5, 6, 7, 8])];
let mut builder = PsdBuilder::new(1, 1);
builder.push_layer(layer);
builder.composite(PixelData::Rgba8(vec![80, 120, 160, 255]));
builder.to_bytes().unwrap()
}
#[test]
fn channel_restrictions_partial_records_preserve_valid_indices_and_neighboring_blocks() {
for trailing in [vec![0xaa], vec![0xaa, 0xbb], vec![0xaa, 0xbb, 0xcc]] {
// The complete indices are 31, 32, 0, 31: 32 is ignored and 31 is a duplicate.
let mut payload = vec![0, 0, 0, 31, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 31];
payload.extend(trailing);
let bytes = channel_restrictions_psd(payload.clone());
let document = import("restrictions.psd", &bytes).unwrap().document;
let layer = document.layers.iter().find(|layer| layer.name == "restricted").unwrap();
assert_eq!(layer.excluded_channels, 0x8000_0001);
assert!(layer.psd_blocks.iter().any(|(key, data)| key == b"brst" && data.as_slice() == payload));
let saved = export(&document, "restrictions.psd", &ExportOptions::default()).unwrap().bytes;
let file = PsdFile::from_bytes(&saved).unwrap();
let record = file.layers().iter().find(|record| record.name() == "restricted").unwrap();
let preserved: Vec<_> = record.blocks.iter().filter(|block| [*b"zBef", *b"brst", *b"zAft"].contains(&block.key)).collect();
assert_eq!(preserved.iter().map(|block| block.key).collect::<Vec<_>>(), vec![*b"zBef", *b"brst", *b"zAft"]);
assert_eq!(preserved[0].data, vec![1, 2, 3, 4]);
assert_eq!(preserved[1].data, vec![0, 0, 0, 0, 0, 0, 0, 31]);
assert_eq!(preserved[2].data, vec![5, 6, 7, 8]);
let reopened = import("restrictions.psd", &saved).unwrap().document;
assert_eq!(reopened.layers.iter().find(|layer| layer.name == "restricted").unwrap().excluded_channels, 0x8000_0001);
}
}
#[test]
fn channel_restrictions_without_valid_records_are_omitted() {
for payload in [vec![], vec![0xaa], vec![0xaa, 0xbb], vec![0xaa, 0xbb, 0xcc], vec![0, 0, 0, 32, 255, 255, 255, 255]] {
let bytes = channel_restrictions_psd(payload);
let document = import("restrictions.psd", &bytes).unwrap().document;
assert_eq!(document.layers.iter().find(|layer| layer.name == "restricted").unwrap().excluded_channels, 0);
let saved = export(&document, "restrictions.psd", &ExportOptions::default()).unwrap().bytes;
let file = PsdFile::from_bytes(&saved).unwrap();
let record = file.layers().iter().find(|record| record.name() == "restricted").unwrap();
assert!(record.block(b"brst").is_none());
assert_eq!(record.block(b"zBef").unwrap().data, vec![1, 2, 3, 4]);
assert_eq!(record.block(b"zAft").unwrap().data, vec![5, 6, 7, 8]);
let reopened = import("restrictions.psd", &saved).unwrap().document;
assert_eq!(reopened.layers.iter().find(|layer| layer.name == "restricted").unwrap().excluded_channels, 0);
}
}
/// Advanced Blending maps to `knko` / `infx` / `clbl` / `tsly` / `lmgm` / `vmgm` (one byte +
/// three of padding), at every depth: non-default values are written, default layers gain no
/// blocks, and imported blocks are rewritten in place.
+4 -2
View File
@@ -531,11 +531,13 @@ pub struct Smoothing {
pub enabled: bool,
/// 0..1.
pub amount: f32,
/// Lazy-mouse: paint only when the pointer pulls a string of `amount × 100 px` taut.
/// Lazy-mouse: paint only when the pointer pulls a string of `amount × 300 px` taut
/// ([`crate::dynamics::MAX_STRING_PX`], screen pixels before Adjust for Zoom).
pub pulled_string: bool,
/// Keep catching up with the pointer while it pauses (uses point timestamps).
pub catch_up: bool,
/// Finish the stroke at the last pointer position.
/// Finish the stroke at the last pointer position. No effect in Pulled String Mode, where the
/// stroke ends the string's length behind the pointer (measured, #11888).
pub catch_up_on_end: bool,
/// Divide the string length by the view zoom (the command's `zoom` param).
pub adjust_for_zoom: bool,
+24 -15
View File
@@ -359,6 +359,10 @@ fn hard_round_presets_have_continuous_pressure_opacity_tapers() {
b.size = 150.0;
b.pressure_opacity = true;
b.smoothing.amount = smoothing;
// The measured lag (#11888) leaves a 49 % stroke ~150 px short of the pointer, so
// its end cap would fall inside the span checked below; catch-up on end paints it
// through to the last point.
b.smoothing.catch_up_on_end = true;
let mut s = Surface::new(fmt);
render_stroke(&mut s, &b, &points, None, false, 1.0);
assert!(s.rgba(200, 120)[3] > 0.7 && s.rgba(699, 120)[3] < 0.3, "{}: the stroke must still taper", preset.name);
@@ -882,26 +886,27 @@ fn smoothing_modes() {
// Pulled string: jitter smaller than the string moves nothing; the brush trails by the string.
let ps = Smoothing { amount: 0.2, pulled_string: true, catch_up_on_end: false, ..Default::default() };
let jitter: Vec<StrokePoint> = (0..20).map(|i| StrokePoint::new(if i % 2 == 0 { 0.0 } else { 5.0 }, 0.0, 1.0)).collect();
assert_eq!(smooth_points(&ps, 1.0, &jitter).len(), 1, "within the 20 px string: no motion");
assert_eq!(smooth_points(&ps, 1.0, &jitter).len(), 1, "within the 60 px string: no motion");
let far = smooth_points(&ps, 1.0, &[StrokePoint::new(0.0, 0.0, 1.0), StrokePoint::new(100.0, 0.0, 1.0)]);
assert!((far.last().unwrap().x - 80.0).abs() < 1e-4);
assert!((far.last().unwrap().x - 40.0).abs() < 1e-4);
// Adjust for zoom: at 200 % zoom the string is half as long in image pixels.
let far = smooth_points(&ps, 2.0, &[StrokePoint::new(0.0, 0.0, 1.0), StrokePoint::new(100.0, 0.0, 1.0)]);
assert!((far.last().unwrap().x - 90.0).abs() < 1e-4);
assert!((far.last().unwrap().x - 70.0).abs() < 1e-4);
// Stroke catch-up: a pause (timestamps) lets the brush converge on the pointer.
let mut a = StrokePoint::new(0.0, 0.0, 1.0);
a.time = 0.0;
let b = StrokePoint { x: 100.0, time: 16.0, ..a };
let c = StrokePoint { time: 500.0, ..b };
let c = StrokePoint { time: 1000.0, ..b };
let d = StrokePoint { time: 2000.0, ..b };
let mut s = Smoother::new(&Smoothing { amount: 0.8, catch_up: true, catch_up_on_end: false, ..Default::default() }, 1.0);
let mut out = Vec::new();
for p in [a, b, c] {
for p in [a, b, c, d] {
s.push(p, &mut out);
}
assert!(out.last().unwrap().x > 99.0, "{}", out.last().unwrap().x);
let mut s = Smoother::new(&Smoothing { amount: 0.8, catch_up: false, catch_up_on_end: false, ..Default::default() }, 1.0);
let mut out = Vec::new();
for p in [a, b, c] {
for p in [a, b, c, d] {
s.push(p, &mut out);
}
assert!(out.last().unwrap().x < 70.0, "{}", out.last().unwrap().x);
@@ -933,7 +938,10 @@ fn disabled_smoothing_keeps_its_settings_and_paints_unsmoothed_at_every_depth()
let mut back: Smoothing = serde_json::from_value(serde_json::to_value(&smoothing).unwrap()).unwrap();
assert_eq!(back, smoothing);
back.enabled = true;
assert!(smooth_points(&back, 1.0, &pts).iter().zip(&pts).any(|(a, b)| a.x != b.x || a.y != b.y));
// Re-enabled, it smooths again: different points, or fewer (a pulled string that hasn't
// been pulled taut leaves the brush where it started, #11888).
let again = smooth_points(&back, 1.0, &pts);
assert!(again.len() != pts.len() || again.iter().zip(&pts).any(|(a, b)| a.x != b.x || a.y != b.y));
}
// Existing brush JSON has no switch and must retain its old smoothing behavior.
let legacy: Smoothing = serde_json::from_str(r#"{"amount":0.8,"pulledString":true}"#).unwrap();
@@ -975,8 +983,9 @@ fn smoothing_pulls_by_time_not_by_how_often_the_device_reports() {
out.last().map_or(0.0, |p| p.x)
};
let (fast, slow) = (run(1.0), run(16.0));
// Two 16 ms steps of a 0.2 pull: 1 - 0.8² = 36 % of the way.
assert!((slow - 36.0).abs() < 1e-4, "{slow}");
// Two 16 ms steps of one step's pull `a`: 1 - (1 - a)² of the way.
let a = crate::dynamics::smoothing_pull(0.8);
assert!((slow - 100.0 * (1.0 - (1.0 - a).powi(2))).abs() < 1e-4, "{slow}");
assert!((fast - slow).abs() < 1e-4, "1000 Hz {fast} vs 60 Hz {slow}");
// Without timestamps each point is one step, as before.
let mut s = Smoother::new(&cfg, 1.0);
@@ -1024,13 +1033,13 @@ fn a_pulled_string_brush_takes_the_pose_along_the_string() {
let a = StrokePoint { rotation: 350.0, ..StrokePoint::new(0.0, 0.0, 1.0) };
let b = StrokePoint { rotation: 10.0, tilt_x: 40.0, ..StrokePoint::new(100.0, 0.0, 0.0) };
let out = smooth_points(&ps, 1.0, &[a, b]);
// The 20 px string leaves the brush 80 % of the way to the pointer.
// The 60 px string leaves the brush 40 % of the way to the pointer.
let p = out.last().unwrap();
assert!((p.x - 80.0).abs() < 1e-4, "{}", p.x);
assert!((p.pressure - 0.2).abs() < 1e-4, "{}", p.pressure);
assert!((p.tilt_x - 32.0).abs() < 1e-3, "{}", p.tilt_x);
// Rotation the short way round: 350° + 80 % of 20°.
assert!((p.rotation - 6.0).abs() < 1e-3, "{}", p.rotation);
assert!((p.x - 40.0).abs() < 1e-4, "{}", p.x);
assert!((p.pressure - 0.6).abs() < 1e-4, "{}", p.pressure);
assert!((p.tilt_x - 16.0).abs() < 1e-3, "{}", p.tilt_x);
// Rotation the short way round: 350° + 40 % of 20°.
assert!((p.rotation - 358.0).abs() < 1e-3, "{}", p.rotation);
}
#[test]
+37 -9
View File
@@ -10,10 +10,24 @@ use crate::brush::{BrushSettings, Control, Dynamic, Smoothing};
use crate::rng::{rand_signed, rand01, stream};
use crate::{Dab, StrokePoint};
/// Maximum pulled-string length at 100 % smoothing, in screen pixels.
pub const MAX_STRING_PX: f64 = 100.0;
/// Maximum pulled-string length at 100 % smoothing, in screen pixels: 150 px at 50 %, as measured
/// in the reference application (#11888).
pub const MAX_STRING_PX: f64 = 300.0;
/// Stroke time over which exponential smoothing moves its fraction of the way to the pointer.
pub const SMOOTHING_STEP_MS: f64 = 16.0;
/// Exponential smoothing's time constant at 100 % smoothing, in ms, and the power of the amount
/// it scales by: `tau = SMOOTHING_TAU_MS · amount^SMOOTHING_TAU_EXP`. Fitted to the reference
/// application's lag (#11888): a 200 px drag in 40 moves 10 ms apart ends 19 px short at 10 %
/// (tau 43 ms) and 78 px short at 50 % (tau 173 ms).
pub const SMOOTHING_TAU_MS: f64 = 314.0;
pub const SMOOTHING_TAU_EXP: f64 = 0.864;
/// The fraction of the way to the pointer exponential smoothing moves in one
/// [`SMOOTHING_STEP_MS`] at `amount`, clamped to 0..1. At 0 (or NaN) it is 1.0: no smoothing.
pub fn smoothing_pull(amount: f64) -> f64 {
let tau = SMOOTHING_TAU_MS * amount.clamp(0.0, 1.0).powf(SMOOTHING_TAU_EXP);
if tau > 0.0 { 1.0 - (-SMOOTHING_STEP_MS / tau).exp() } else { 1.0 }
}
/// With Spacing unchecked, one dab per this many milliseconds of stroke time, so faster strokes
/// space their dabs further apart (Photoshop: "the speed of the cursor determines the spacing").
@@ -103,12 +117,15 @@ pub struct Smoother {
zoom: f64,
pos: Option<StrokePoint>,
last_input: Option<StrokePoint>,
/// Has time passed between two input points? Then the stroke is timed, and a later point
/// with no time since the last one moves the brush no further (not by the untimed pull).
timed: bool,
}
impl Smoother {
/// `zoom` is the view zoom (only used with `adjust_for_zoom`).
pub fn new(cfg: &Smoothing, zoom: f32) -> Self {
Self { cfg: cfg.clone(), zoom: f64::from(zoom.max(0.01)), pos: None, last_input: None }
Self { cfg: cfg.clone(), zoom: f64::from(zoom.max(0.01)), pos: None, last_input: None, timed: false }
}
fn active(&self) -> bool {
@@ -149,21 +166,27 @@ impl Smoother {
}
// Exponential: every SMOOTHING_STEP_MS of stroke time moves `a` of the way towards the
// pointer, so the feel doesn't depend on how often the device reports. Input without
// timestamps takes one step per point.
let a = 1.0 - amount.min(0.95);
// timestamps was never measured: it takes one step per point with the pull it always had.
let a = smoothing_pull(amount);
let dt = prev_input.map_or(0.0, |q| p.time - q.time);
let still = prev_input.is_some_and(|q| q.x == p.x && q.y == p.y);
if still && !self.cfg.catch_up {
// Without Stroke Catch-Up the brush stops while the pointer pauses (Photoshop).
return;
}
let (iters, step) = if dt > 0.0 && dt.is_finite() {
let has_time = dt > 0.0 && dt.is_finite();
self.timed |= has_time;
if self.timed && !has_time {
// No time passed (two reports in one millisecond): the brush stays where it is.
return;
}
let (iters, step) = if has_time {
let steps = dt / SMOOTHING_STEP_MS;
let iters = steps.ceil().clamp(1.0, 64.0);
// Each of `iters` moves covers `steps / iters` steps' worth of pull.
(iters as usize, 1.0 - (1.0 - a).powf(steps.min(64.0) / iters))
} else {
(1, a)
(1, 1.0 - amount.min(0.95))
};
let mut cur = pos;
for _ in 0..iters {
@@ -191,9 +214,10 @@ impl Smoother {
}
/// End of stroke: with Catch-Up On Stroke End the brush finishes at the last pointer position
/// and pose.
/// and pose. Not in Pulled String Mode: the brush stays the string's length behind the pointer
/// (measured, #11888).
pub fn finish(&mut self, out: &mut Vec<StrokePoint>) {
if !self.active() || !self.cfg.catch_up_on_end {
if !self.active() || !self.cfg.catch_up_on_end || self.cfg.pulled_string {
return;
}
if let (Some(pos), Some(last)) = (self.pos, self.last_input)
@@ -1082,3 +1106,7 @@ mod streaming_tests {
assert_eq!(dabs.len(), 2_000_001);
}
}
#[cfg(test)]
#[path = "smoothing_lag_tests.rs"]
mod smoothing_lag_tests;
+87
View File
@@ -0,0 +1,87 @@
//! #11888: Smoothing trails the pointer as far as in the reference application, and Pulled String
//! Mode stops the string's length short of the release point, with or without Catch-up on Stroke
//! End. The drag is the issue's: (100, 199) to (300, 199) in 40 moves 10 ms apart, then released.
use super::*;
use crate::brush::Smoothing;
fn drag() -> Vec<StrokePoint> {
(0..=40).map(|i| StrokePoint { time: f64::from(i) * 10.0, ..StrokePoint::new(100.0 + f64::from(i) * 5.0, 199.0, 1.0) }).collect()
}
/// How far short of the release point (300) the smoothed stroke ends.
fn short(cfg: &Smoothing) -> f64 {
let out = smooth_points(cfg, 1.0, &drag());
300.0 - out.last().map_or(f64::NAN, |p| p.x)
}
fn within(got: f64, want: f64, tolerance: f64) -> bool {
(got - want).abs() <= want * tolerance
}
#[test]
fn ten_and_fifty_percent_lag_as_measured() {
let off_end = Smoothing { catch_up_on_end: false, ..Default::default() };
let ten = short(&Smoothing { amount: 0.1, ..off_end.clone() });
let fifty = short(&Smoothing { amount: 0.5, ..off_end });
assert!(within(ten, 19.0, 0.25), "10 %: {ten} px short (reference 19)");
assert!(within(fifty, 78.0, 0.25), "50 %: {fifty} px short (reference 78)");
}
#[test]
fn catch_up_on_stroke_end_still_reaches_the_release_point() {
let cfg = Smoothing { amount: 0.5, catch_up_on_end: true, ..Default::default() };
assert_eq!(short(&cfg), 0.0);
}
#[test]
fn the_pulled_string_stops_its_length_short_either_way() {
for catch_up_on_end in [false, true] {
let cfg = Smoothing { amount: 0.5, pulled_string: true, catch_up_on_end, ..Default::default() };
let s = short(&cfg);
assert!((s - 150.0).abs() < 1e-9, "catch-up on end {catch_up_on_end}: {s} px short (reference about 150)");
}
}
#[test]
fn zero_and_disabled_smoothing_paint_through_every_point() {
let pts = drag();
for cfg in [Smoothing { amount: 0.0, ..Default::default() }, Smoothing { enabled: false, amount: 0.5, ..Default::default() }] {
let out = smooth_points(&cfg, 1.0, &pts);
assert_eq!(out.len(), pts.len(), "{cfg:?}");
assert!(out.iter().zip(&pts).all(|(a, b)| (a.x, a.y, a.pressure) == (b.x, b.y, b.pressure)), "{cfg:?}");
}
}
#[test]
fn the_pull_grows_with_less_smoothing_and_stays_a_fraction() {
let pulls: Vec<f64> = [0.01, 0.1, 0.25, 0.5, 0.75, 1.0].iter().map(|a| smoothing_pull(*a)).collect();
assert!(pulls.windows(2).all(|w| w[0] > w[1]), "{pulls:?}");
assert!(pulls.iter().all(|p| *p > 0.0 && *p < 1.0), "{pulls:?}");
assert_eq!(smoothing_pull(0.0), 1.0, "no time constant: straight to the pointer");
assert_eq!(smoothing_pull(f64::NAN), 1.0, "a bad amount never makes a NaN position");
}
/// Input without timestamps (a control-client stroke, a script, an old file) was never measured,
/// so each point keeps the pull it always had: `1 - amount` of the way to the pointer. At the
/// default 10 % a two-point stroke still ends 90 % of the way, not a third of it.
#[test]
fn strokes_without_timestamps_keep_their_per_point_pull() {
let cfg = Smoothing { amount: 0.1, catch_up_on_end: false, ..Default::default() };
let out = smooth_points(&cfg, 1.0, &[StrokePoint::new(0.0, 0.0, 1.0), StrokePoint::new(100.0, 0.0, 1.0)]);
let x = out.last().map_or(f64::NAN, |p| p.x);
assert!((x - 90.0).abs() < 1e-4, "a 10 % untimed step reached {x}, want 90");
}
/// A timed stroke stays timed: a report with no time since the last one (two events in one
/// millisecond) leaves the brush where it is, instead of jumping it by the untimed per-point pull.
#[test]
fn a_report_with_no_time_passed_does_not_move_a_timed_brush() {
let cfg = Smoothing { amount: 0.1, catch_up: true, catch_up_on_end: false, ..Default::default() };
let at = |x: f64, time: f64| StrokePoint { time, ..StrokePoint::new(x, 0.0, 1.0) };
let timed = smooth_points(&cfg, 1.0, &[at(0.0, 0.0), at(100.0, 10.0)]);
let twice = smooth_points(&cfg, 1.0, &[at(0.0, 0.0), at(100.0, 10.0), at(100.0, 10.0)]);
let (before, after) = (timed.last().map_or(f64::NAN, |p| p.x), twice.last().map_or(f64::NAN, |p| p.x));
assert!(before > 0.0 && before < 90.0, "the timed move lags: {before}");
assert_eq!(after, before, "no time passed, so the brush stays");
}
+3
View File
@@ -333,3 +333,6 @@ impl eframe::App for Box<PhotocraftApp> {
#[cfg(test)]
mod clipboard_tests;
#[cfg(test)]
mod apply_data_set_alert_tests;
@@ -0,0 +1,44 @@
//! #14499: Apply Data Set on a type layer under Lock All shows the reference application's alert;
//! its other refusals stay status-bar messages.
use super::*;
use serde_json::json;
const LOCKED: &str = "Could not apply data set because the layer is locked.";
/// An app with a type layer bound to a `headline` text variable and one data set `Zed` for it,
/// the layer under Lock All when `locked`.
fn app(locked: bool) -> Box<PhotocraftApp> {
let mut app = PhotocraftApp::new(Session::new(), Services::default());
app.session.execute("file.new", json!({"width": 64, "height": 48})).unwrap();
let id = app.session.execute("type.create", json!({"x": 4, "y": 30, "text": "Old", "size": 12})).unwrap()["layer"].clone();
app.session.execute("image.variables.define", json!({"defs": [{"name": "headline", "layer": id, "type": "textReplacement"}]})).unwrap();
app.session
.execute("image.variables.dataSets", json!({"dataSets": [{"name": "Zed", "values": [{"variable": "headline", "kind": "text", "value": "New"}]}]}))
.unwrap();
if locked {
app.session.execute("layer.lockLayers", json!({"all": true})).unwrap();
}
app.sync_views();
app
}
/// The messages of the open framework alerts.
fn alerts(app: &PhotocraftApp) -> Vec<String> {
app.framework.dialogs.open_dialogs().iter().filter_map(|d| d.fields.as_ref()?.get("message")?.as_str().map(String::from)).collect()
}
#[test]
fn a_locked_type_layer_refuses_with_an_alert() {
let mut app = app(true);
assert_eq!(app.run("image.applyDataSet", json!({"name": "Zed"})), Err(LOCKED.to_string()));
assert_eq!(alerts(&app), [LOCKED]);
}
#[test]
fn other_refusals_and_an_unlocked_layer_show_no_alert() {
let mut app = app(false);
assert!(app.run("image.applyDataSet", json!({"name": "Missing"})).is_err());
app.run("image.applyDataSet", json!({"name": "Zed"})).unwrap();
assert!(alerts(&app).is_empty(), "{:?}", alerts(&app));
}
+4
View File
@@ -220,6 +220,10 @@ impl PhotocraftApp {
Err(e) => {
self.ui.status = e.clone();
self.ui.status_error = true;
if id == "image.applyDataSet" && e == photocraft_engine::DATA_SET_LAYER_LOCKED {
// The reference application refuses a locked type layer with an alert (#14499).
let _ = crate::dialogs::alerts::alert(self, tl!(photocraft_engine::DATA_SET_LAYER_LOCKED));
}
}
}
if suppress_events {
+150 -39
View File
@@ -89,14 +89,28 @@ pub struct Framework {
/// The runtime's keymap overrides. The runtime rebuilds its keymap when the `Arc` changes, so
/// it is replaced only when the bindings it carries change.
overrides: Arc<Overrides>,
/// The preferences revision `overrides` and `catalog` were last built at.
overrides_rev: Option<u64>,
/// The app's command catalog as of `overrides_rev`.
/// What `overrides` was built from: the preferences' catalog revision and the catalog's generation.
overrides_key: Option<(u64, u64)>,
/// Advances each time `overrides` is replaced.
overrides_generation: u64,
/// The app's command catalog, built from `catalog_rows`.
catalog: Option<AppCatalog>,
/// The rows `catalog` was built from, and its generation: the runtime rebuilds its keymap when the generation
/// changes, so it advances only when the rows differ.
/// The rows `catalog` was built from ([`command_rows`](crate::shortcut_dispatch::command_rows)), the action
/// names they were built from (their one input that changes at run time), the actions list's revision those names
/// were last read at, and the catalog's generation: the runtime rebuilds its keymap when the generation changes,
/// so it advances only when the names change. The revision is the fast check; it assumes the list is edited in
/// place or through `ActionList::replace`, which keep it moving forward.
catalog_rows: Vec<craft::keymap::CommandDef>,
catalog_actions: Vec<String>,
catalog_rows_rev: Option<u64>,
catalog_generation: u64,
/// How many times the rows and the overrides were built, for the count trials.
#[cfg(test)]
pub(crate) catalog_builds: usize,
#[cfg(test)]
pub(crate) overrides_builds: usize,
/// The states the keyed command sources last computed ([`command_states`]).
pub(crate) held_states: HeldStates,
/// The file services the host gives components (pickers, reads and writes); `None` keeps the
/// host's own default.
files: Option<Arc<dyn Files>>,
@@ -271,10 +285,18 @@ impl Framework {
dialogs: DialogHost::new(),
captured: Default::default(),
overrides: Arc::new(Overrides::new()),
overrides_rev: None,
overrides_key: None,
overrides_generation: 0,
catalog: None,
catalog_rows: Vec::new(),
catalog_actions: Vec::new(),
catalog_rows_rev: None,
catalog_generation: 0,
#[cfg(test)]
catalog_builds: 0,
#[cfg(test)]
overrides_builds: 0,
held_states: HeldStates::default(),
files,
fired: Vec::new(),
refused: false,
@@ -476,26 +498,49 @@ impl Framework {
.unwrap_or_else(|| id.as_str().to_owned())
}
/// What the runtime's keymap was last built from: the preferences revision of the overrides and the catalog's
/// generation. They change at the start of the frame whose keymap follows them, so a surface that shows the
/// keymap's chords (the menu model) hashes them to rebuild in that frame.
pub(crate) fn keymap_inputs(&self) -> (Option<u64>, u64) {
(self.overrides_rev, self.catalog_generation)
/// What the runtime's keymap was last built from: the generations of the overrides and of the catalog. They
/// change at the start of the frame whose keymap follows them, so a surface that shows the keymap's chords (the
/// menu model) hashes them to rebuild in that frame.
pub(crate) fn keymap_inputs(&self) -> (u64, u64) {
(self.overrides_generation, self.catalog_generation)
}
/// Rebuilds the catalog and the runtime's keymap overrides at preferences revision `rev`. The
/// pane moves are unbound in the overrides, because PhotoCraft's own table binds F6 and
/// Shift+F6 (Window › Color, Select › Modify › Feather) until those are a framework
/// `CommandSet`. The held `Arc` is replaced only when the bindings differ, so the runtime
/// rebuilds its keymap only on a change.
fn set_overrides(&mut self, rev: u64, catalog: Option<AppCatalog>, mut overrides: Overrides) {
self.overrides_rev = Some(rev);
self.catalog = catalog;
/// The catalog's rows when they were built at actions list revision `actions_rev`, else `None`.
pub(crate) fn catalog_rows_at(&self, actions_rev: u64) -> Option<&[craft::keymap::CommandDef]> {
(self.catalog_rows_rev == Some(actions_rev)).then_some(self.catalog_rows.as_slice())
}
/// Takes `rows`, built from the action names `actions` at actions list revision `actions_rev`, as the catalog's
/// rows: a new catalog generation.
fn set_catalog(&mut self, actions_rev: u64, actions: Vec<String>, rows: Vec<craft::keymap::CommandDef>) {
self.catalog_generation += 1;
self.catalog = crate::shortcut_dispatch::catalog(rows.clone(), self.catalog_generation);
self.catalog_rows = rows;
self.catalog_actions = actions;
self.catalog_rows_rev = Some(actions_rev);
#[cfg(test)]
{
self.catalog_builds += 1;
}
}
/// Takes the runtime's keymap overrides built from `key` ([`Self::overrides_key`]). The pane
/// moves are unbound in the overrides, because PhotoCraft's own table binds F6 and Shift+F6
/// (Window › Color, Select › Modify › Feather) until those are a framework `CommandSet`. The
/// held `Arc` is replaced only when the bindings differ, so the runtime rebuilds its keymap
/// only on a change.
fn set_overrides(&mut self, key: (u64, u64), mut overrides: Overrides) {
self.overrides_key = Some(key);
for command in [NavCommand::NextPane, NavCommand::PreviousPane] {
overrides.insert(CommandRef::from(command).key(), Vec::new());
}
if *self.overrides != overrides {
self.overrides = Arc::new(overrides);
self.overrides_generation += 1;
}
#[cfg(test)]
{
self.overrides_builds += 1;
}
}
}
@@ -505,6 +550,10 @@ impl Framework {
pub(crate) struct CommandSource {
/// The states of the source's commands for the coming frame.
states: fn(&PhotocraftApp) -> Vec<(CommandRef, CommandState)>,
/// What `states` reads, for a source whose every input is a plain value or a revision that moves exactly when
/// the data changes: the states are computed again only when the key changes. `None`: computed every frame,
/// because what the source reads has no such revision yet.
key: Option<fn(&PhotocraftApp) -> StatesKey>,
/// Runs `command` when it is this source's; whether it was.
run: fn(&mut PhotocraftApp, &egui::Context, &CommandRef) -> bool,
}
@@ -512,23 +561,76 @@ pub(crate) struct CommandSource {
/// Every command source, in the order [`run_command`] tries them. The theme has no entry: it has
/// no command state, and its picks run through `menus::invoke`.
pub(crate) const COMMAND_SOURCES: &[CommandSource] = &[
CommandSource { states: crate::panels::registry::states, run: crate::panels::registry::run_fired },
CommandSource { states: tool_states, run: run_tool },
CommandSource { states: crate::workspace_ui::states, run: crate::workspace_ui::run_fired },
CommandSource { states: crate::slice_ui::command_states, run: crate::slice_ui::run_fired },
CommandSource { states: crate::align_bar::command_states, run: crate::align_bar::run_fired },
CommandSource { states: crate::artboard_tool::command_states, run: crate::artboard_tool::run_fired },
CommandSource { states: crate::panels::registry::states, key: None, run: crate::panels::registry::run_fired },
CommandSource { states: tool_states, key: Some(tool_states_key), run: run_tool },
CommandSource { states: crate::workspace_ui::states, key: None, run: crate::workspace_ui::run_fired },
CommandSource { states: crate::slice_ui::command_states, key: Some(crate::slice_ui::command_states_key), run: crate::slice_ui::run_fired },
CommandSource { states: crate::align_bar::command_states, key: None, run: crate::align_bar::run_fired },
CommandSource { states: crate::artboard_tool::command_states, key: Some(crate::artboard_tool::command_states_key), run: crate::artboard_tool::run_fired },
// Space+F: the pasteboard colour keys of the held Hand.
CommandSource { states: |_| Vec::new(), run: crate::canvas_tool_menu::run_canvas_color },
CommandSource { states: |_| Vec::new(), key: Some(|_| StatesKey::default()), run: crate::canvas_tool_menu::run_canvas_color },
// The options bar's engine-command buttons: their commands run through `shortcuts::handle`.
CommandSource { states: crate::panels::options_bar::selection::command_states, run: |_, _, _| false },
CommandSource { states: crate::panels::options_bar::selection::command_states, key: None, run: |_, _, _| false },
];
/// The key of a [`CommandSource`]'s states: the plain values and exact revisions they are computed from, so equal
/// keys mean equal states.
pub(crate) type StatesKey = [u64; 4];
/// The states each keyed [`CommandSource`] last computed, by its place in [`COMMAND_SOURCES`], with their key.
#[derive(Default)]
pub(crate) struct HeldStates {
kept: Vec<Option<KeptStates>>,
/// How many times each source computed its states, for the count trials.
#[cfg(test)]
pub(crate) runs: Vec<usize>,
}
/// One keyed source's states and the key they were computed at.
#[derive(Clone)]
struct KeptStates {
key: StatesKey,
states: Vec<(CommandRef, CommandState)>,
}
/// The tool commands: the current tool's row is checked.
fn tool_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandState)> {
Tool::ALL.iter().map(|&tool| (CommandRef::from(crate::panels::tool_commands::command_of(tool)), CommandState::new().checked(app.ui.tool == tool))).collect()
}
/// What [`tool_states`] reads: the tool.
fn tool_states_key(app: &PhotocraftApp) -> StatesKey {
[app.ui.tool as u64, 0, 0, 0]
}
/// The states of every command source for the coming frame. A keyed source runs only when its key changed since it
/// last ran.
fn command_states(app: &PhotocraftApp, held: &mut HeldStates) -> Vec<(CommandRef, CommandState)> {
held.kept.resize(COMMAND_SOURCES.len(), None);
#[cfg(test)]
held.runs.resize(COMMAND_SOURCES.len(), 0);
let mut states = Vec::new();
for (at, source) in COMMAND_SOURCES.iter().enumerate() {
let key = source.key.map(|key| key(app));
match (&held.kept[at], key) {
(Some(kept), Some(key)) if kept.key == key => states.extend_from_slice(&kept.states),
_ => {
#[cfg(test)]
{
held.runs[at] += 1;
}
let computed = (source.states)(app);
states.extend_from_slice(&computed);
held.kept[at] = key.map(|key| KeptStates { key, states: computed });
}
}
}
states
}
#[cfg(test)]
mod catalog_tests;
/// Selects the tool a tool command names.
fn run_tool(app: &mut PhotocraftApp, _ctx: &egui::Context, command: &CommandRef) -> bool {
let Some(command) = crate::panels::tool_commands::ToolCommand::from_ref(command) else {
@@ -549,23 +651,32 @@ impl PhotocraftApp {
/// runs them), the commands the canvas ran (`record_view_commands`, in `logic`) and whether a
/// component refused its input.
pub(crate) fn framework_before_input(&mut self, ctx: &egui::Context) {
// The catalog and the bindings come from walking the whole command table: only after a
// preferences change.
let rev = self.session.prefs.rev();
if self.framework.overrides_rev != Some(rev) {
let rows = crate::shortcut_dispatch::command_rows(self);
if !crate::shortcut_dispatch::same_rows(&self.framework.catalog_rows, &rows) {
self.framework.catalog_generation += 1;
self.framework.catalog_rows = rows.clone();
// The catalog's rows change only with the action names; the bindings with the rows and the
// shortcut preferences.
let list = &self.session.actions.list;
let actions_rev = list.revision();
if self.framework.catalog_rows_rev != Some(actions_rev) {
let same = self.framework.catalog_rows_rev.is_some()
&& self.framework.catalog_actions.iter().map(String::as_str).eq(list.actions().iter().map(|action| action.name.as_str()));
if same {
self.framework.catalog_rows_rev = Some(actions_rev);
} else {
let actions = list.actions().iter().map(|action| action.name.clone()).collect();
let rows = crate::shortcut_dispatch::command_rows(self);
self.framework.set_catalog(actions_rev, actions, rows);
}
let catalog = crate::shortcut_dispatch::catalog(rows, self.framework.catalog_generation);
let overrides = crate::shortcut_dispatch::overrides(self);
self.framework.set_overrides(rev, catalog, overrides);
}
let overrides_key = (self.session.prefs.catalog_rev(), self.framework.catalog_generation);
if self.framework.overrides_key != Some(overrides_key) {
let overrides = crate::shortcut_dispatch::overrides(self, &self.framework.catalog_rows);
self.framework.set_overrides(overrides_key, overrides);
}
if self.framework.sync_theme(&mut self.session) {
crate::prefs_ui::show_selected_theme(self, ctx);
}
let states: Vec<(CommandRef, CommandState)> = COMMAND_SOURCES.iter().flat_map(|source| (source.states)(self)).collect();
let mut held = std::mem::take(&mut self.framework.held_states);
let states = command_states(self, &mut held);
self.framework.held_states = held;
let gate = crate::menus::command_gate(self);
let latched = self.ui.shell.latched;
embed::before_input(ctx, |output: FrameOutput| {
@@ -0,0 +1,130 @@
//! Count trials: the command catalog, the keymap overrides and the keyed command states are built only when what
//! they read changes.
use craft::automation::actions::ActionStep;
use serde_json::json;
use super::{COMMAND_SOURCES, PhotocraftApp};
use crate::canvas::testing;
use crate::state::Tool;
/// The places of the keyed sources in [`COMMAND_SOURCES`].
const TOOL_SOURCE: usize = 1;
const SLICE_SOURCE: usize = 3;
const ARTBOARD_SOURCE: usize = 5;
fn app() -> Box<PhotocraftApp> {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
testing::frame(&mut app);
app
}
/// How many times the rows and the overrides were built.
fn builds(app: &PhotocraftApp) -> (usize, usize) {
(app.framework.catalog_builds, app.framework.overrides_builds)
}
/// How many times each keyed command source computed its states, by its place in [`COMMAND_SOURCES`]; `None` for a
/// source that computes them every frame.
fn keyed_runs(app: &PhotocraftApp) -> Vec<Option<usize>> {
COMMAND_SOURCES.iter().zip(&app.framework.held_states.runs).map(|(source, &runs)| source.key.map(|_| runs)).collect()
}
/// The keyed sources that computed their states between `before` and `after`.
fn ran(before: &[Option<usize>], after: &[Option<usize>]) -> Vec<usize> {
before.iter().zip(after).enumerate().filter(|(_, (was, now))| was.is_some() && was != now).map(|(at, _)| at).collect()
}
fn frames(app: &mut PhotocraftApp, n: usize) {
for _ in 0..n {
testing::frame(app);
}
}
#[test]
fn the_catalog_is_built_only_when_its_inputs_change() {
let mut app = app();
assert_eq!(builds(&app), (1, 1), "the first frame builds the catalog and the overrides");
frames(&mut app, 100);
assert_eq!(builds(&app), (1, 1), "idle frames build nothing");
// The tool and the colours as the app saves them: preference edits outside the catalog's inputs.
let prefs = app.session.prefs.rev();
crate::tool_memory::select(&mut app, Tool::Brush);
app.run("tools.swapColors", json!({})).unwrap();
app.session.edit_prefs(|p| {
p.selected_tool = json!("Brush");
p.tool_colors = Default::default();
});
frames(&mut app, 2);
assert_ne!(app.session.prefs.rev(), prefs);
assert_eq!(builds(&app), (1, 1), "a tool or colour change builds nothing");
let generation = app.framework.keymap_inputs().1;
assert_eq!(app.framework.overrides.get("filter.blur.gaussian"), None);
app.session.edit_prefs(|p| {
p.shortcuts.insert("filter.blur.gaussian".into(), "Cmd+Alt+G".into());
});
frames(&mut app, 2);
assert_eq!(builds(&app), (1, 2), "a shortcut edit builds the overrides once and leaves the rows");
assert!(app.framework.overrides.get("filter.blur.gaussian").is_some_and(|keys| !keys.is_empty()), "the overrides carry the new key");
assert_eq!(app.framework.keymap_inputs().1, generation, "the catalog keeps its generation");
app.session.actions.list.new_action("Trial", None).unwrap();
frames(&mut app, 2);
assert_eq!(builds(&app), (2, 3), "a new action builds the rows and the overrides once");
assert_eq!(app.framework.keymap_inputs().1, generation + 1, "the catalog takes a new generation");
assert!(app.framework.catalog_rows.iter().any(|row| row.label == "Trial"), "the action has its row");
// Edits that keep every action's name leave the rows.
let list = &mut app.session.actions.list;
let at = list.actions().iter().position(|action| action.name == "Trial").unwrap();
list.insert_step(at, 0, ActionStep::new("layer.new", json!({}))).unwrap();
list.toggle_step(at, 0).unwrap();
frames(&mut app, 2);
assert_eq!(builds(&app), (2, 3), "a step edit builds nothing");
assert_eq!(app.framework.keymap_inputs().1, generation + 1, "the catalog keeps its generation");
}
#[test]
fn keyed_command_states_run_only_when_their_key_changes() {
let mut app = app();
assert_eq!((COMMAND_SOURCES[TOOL_SOURCE].states)(&app).len(), Tool::ALL.len(), "TOOL_SOURCE names the tool commands");
let before = keyed_runs(&app);
assert!(before.iter().flatten().all(|&runs| runs == 1), "the first frame computes every keyed source once");
frames(&mut app, 100);
assert_eq!(keyed_runs(&app), before, "idle frames compute no keyed source");
let other = if app.ui.tool == Tool::Brush { Tool::Move } else { Tool::Brush };
crate::tool_memory::select(&mut app, other);
frames(&mut app, 2);
let after = keyed_runs(&app);
for (at, (was, now)) in before.iter().zip(&after).enumerate() {
let moved = usize::from(at == TOOL_SOURCE);
assert_eq!(now.map(|n| n - was.unwrap_or_default()), was.map(|_| moved), "source {at} after a tool change");
}
let before = keyed_runs(&app);
app.ui.artboard_tool.adding = true;
frames(&mut app, 2);
assert_eq!(ran(&before, &keyed_runs(&app)), [ARTBOARD_SOURCE], "the placing mode");
let before = keyed_runs(&app);
app.run("file.new", json!({"width": 64, "height": 64})).unwrap();
frames(&mut app, 2);
let after = keyed_runs(&app);
assert!(ran(&before, &after).contains(&SLICE_SOURCE) && ran(&before, &after).contains(&ARTBOARD_SOURCE), "a document opens");
let has_doc = |app: &PhotocraftApp| (COMMAND_SOURCES[ARTBOARD_SOURCE].states)(app)[0].1.is_enabled();
assert!(has_doc(&app));
let before = keyed_runs(&app);
app.ui.slices.selected = Some(1);
frames(&mut app, 2);
let selected = keyed_runs(&app);
assert_eq!(ran(&before, &selected), [SLICE_SOURCE], "the selected slice");
app.session.file_menu.slices_locked = true;
frames(&mut app, 2);
assert_eq!(ran(&selected, &keyed_runs(&app)), [SLICE_SOURCE], "the slice lock");
}
@@ -0,0 +1,87 @@
//! #13629: the Artboards to Files dialog has the radio pair Include Overlapping Areas (selected
//! by default) / Artboard Content Only right below the prefix, and OK passes the choice to
//! `file.export.artboardsToFiles` as `content`. Layer Comps to Files has no such choice.
use crate::PhotocraftApp;
use craft::ui::dialog::DialogId;
use craft::ui::patterns::form_dialogs::HostedParamDialog;
use egui::accesskit::{Role, Toggled};
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::{Value, json};
const ARTBOARDS: &str = "file.export.artboardsToFiles";
const OVERLAPPING: &str = "Include Overlapping Areas";
const CONTENT_ONLY: &str = "Artboard Content Only";
type H = Harness<'static, Box<PhotocraftApp>>;
fn harness() -> H {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 64, "height": 64})).unwrap();
app.run("layer.new.artboard", json!({"rect": [0, 0, 64, 64]})).unwrap();
app.run("layerComp.new", json!({"name": "Comp"})).unwrap();
app.sync_views();
let h = Harness::builder()
.with_size(egui::vec2(1440.0, 900.0))
.with_max_steps(64)
.with_context(app.ctx().clone())
.build_ui_state(|ui, app: &mut Box<PhotocraftApp>| crate::dialogs::run(app, ui), app);
PhotocraftApp::setup_context(&h.ctx, Default::default());
h
}
fn open(h: &mut H, command: &str) -> DialogId {
let ctx = h.ctx.clone();
let reply = crate::menus::invoke(h.state_mut(), &ctx, command, json!({})).unwrap();
let want = reply["dialog"].as_str().unwrap().to_owned();
let dialog = h.state().framework.dialogs.open_dialogs().into_iter().map(|d| d.id).find(|d| d.value().to_string() == want).unwrap();
h.run_steps(4);
dialog
}
fn field(h: &H, dialog: DialogId, key: &str) -> Option<Value> {
let form = h.state().framework.dialogs.get_by_id::<HostedParamDialog>(dialog)?;
serde_json::to_value(form.fields()).ok()?.get(key).cloned()
}
fn selected(h: &H, label: &str) -> bool {
h.get_by_role_and_label(Role::RadioButton, label).accesskit_node().toggled() == Some(Toggled::True)
}
/// The top edge of the first node labelled `label`.
fn top(h: &H, label: &str) -> f32 {
h.query_all_by_label(label).next().unwrap_or_else(|| panic!("{label} is shown")).rect().top()
}
#[test]
fn the_dialog_offers_the_two_radios_below_the_prefix_overlapping_first_and_selected() {
let mut h = harness();
let dialog = open(&mut h, ARTBOARDS);
let radios: Vec<String> = h.query_all_by_role(Role::RadioButton).filter_map(|n| n.accesskit_node().label()).collect();
assert_eq!(radios, [OVERLAPPING, CONTENT_ONLY]);
assert!(selected(&h, OVERLAPPING) && !selected(&h, CONTENT_ONLY));
let radio = top(&h, OVERLAPPING);
assert!(top(&h, "File Name Prefix") < radio && radio < top(&h, "File Type"), "the radios sit between the prefix and the file type");
assert_eq!(field(&h, dialog, "content"), Some(json!("overlapping")));
}
#[test]
fn clicking_artboard_content_only_passes_it_to_the_command() {
let mut h = harness();
let dialog = open(&mut h, ARTBOARDS);
h.get_by_role_and_label(Role::RadioButton, CONTENT_ONLY).click();
h.run_steps(4);
assert!(selected(&h, CONTENT_ONLY) && !selected(&h, OVERLAPPING));
assert_eq!(field(&h, dialog, "content"), Some(json!("artboard")));
h.get_by_role_and_label(Role::RadioButton, OVERLAPPING).click();
h.run_steps(4);
assert_eq!(field(&h, dialog, "content"), Some(json!("overlapping")));
}
#[test]
fn layer_comps_to_files_has_no_overlap_choice() {
let mut h = harness();
let dialog = open(&mut h, "file.export.layerCompsToFiles");
assert_eq!(h.query_all_by_role(Role::RadioButton).count(), 0);
assert_eq!(field(&h, dialog, "content"), None);
}
+16 -6
View File
@@ -45,14 +45,18 @@ pub fn sync_tool_brush(app: &mut PhotocraftApp) {
// A tool seen for the first time takes what the brush has, at Photoshop's smoothing, but
// in Normal mode: each tool's Mode starts at Normal, so a Multiply Brush doesn't make the
// first Pattern Stamp stroke multiply (or give Healing a mode its menu doesn't have).
// The Art History Brush also starts at full opacity (#10263), and the Pattern Stamp at full
// opacity and flow (#12616): those fields are their own.
// The Pattern Stamp also starts at full opacity and flow (#12616): those fields are its own.
// The Background Eraser, the Healing Brush, the Burn, Dodge and Sponge tools, the Clone
// Stamp and the Smudge tool start with their own measured tips instead, as the whole brush
// Reset Tool gives them (#11911, #12099, #12671, #12684, #13029, #12601, #12964).
// Stamp, the Smudge tool and the Art History Brush start with their own measured tips
// instead, as the whole brush Reset Tool gives them (#11911, #12099, #12671, #12684,
// #13029, #12601, #12964, #12631); the Art History Brush's is at full opacity (#10263).
None if matches!(tool, Tool::BackgroundEraser | Tool::Healing | Tool::Burn | Tool::Dodge | Tool::Sponge | Tool::CloneStamp | Tool::Smudge) => {
fresh_brush(tool, &current)
}
// Its pressure toggles are not measured, so its first use keeps the outgoing ones (#12631).
None if tool == Tool::ArtHistoryBrush => {
BrushSettings { pressure_size: current.pressure_size, pressure_opacity: current.pressure_opacity, ..fresh_brush(tool, &current) }
}
// The Pencil starts with its own 1 px hard round (#12200) regardless of the Brush, keeping
// the outgoing opacity.
None if tool == Tool::Pencil => BrushSettings { opacity: current.opacity, ..fresh_brush(tool, &current) },
@@ -62,7 +66,6 @@ pub fn sync_tool_brush(app: &mut PhotocraftApp) {
None => {
let fresh = BrushSettings::default();
let (opacity, flow) = match tool {
Tool::ArtHistoryBrush => (fresh.opacity, current.flow),
Tool::PatternStamp => (fresh.opacity, fresh.flow),
_ => (current.opacity, current.flow),
};
@@ -110,6 +113,8 @@ const PENCIL_TOOL_TIP: (f32, f32, f32) = (1.0, 1.0, 0.25);
const TONING_TOOL_TIP: (f32, f32, f32) = (65.0, 0.0, 0.25);
/// The Clone Stamp's tip after Reset Tool (#12601): a 21 px soft round at 25 % spacing.
const CLONE_STAMP_TIP: (f32, f32, f32) = (21.0, 0.0, 0.25);
/// The Art History Brush's tip after Reset Tool (#12631): a 21 px soft round at 25 % spacing.
const ART_HISTORY_BRUSH_TIP: (f32, f32, f32) = (21.0, 0.0, 0.25);
/// The Remove tool's size after Reset Tool (#12548): 19 px. Its hardness and spacing are not
/// measured, so they stay the default brush's.
const REMOVE_TOOL_SIZE: f32 = 19.0;
@@ -120,7 +125,8 @@ const SMUDGE_TOOL_TIP: (f32, f32, f32) = (13.0, 0.0, 0.25);
/// smoothing, with the session's own fields of `current`. The Brush tool's tip is
/// [`BRUSH_TOOL_TIP`], the Eraser's [`ERASER_TOOL_TIP`] with no smoothing, the Background Eraser's [`BACKGROUND_ERASER_TIP`], the Healing Brush's
/// [`HEALING_BRUSH_TIP`], the Burn, Dodge and Sponge tools' [`TONING_TOOL_TIP`], the Clone Stamp's
/// [`CLONE_STAMP_TIP`] with no smoothing, the Remove tool's size [`REMOVE_TOOL_SIZE`], the Smudge
/// [`CLONE_STAMP_TIP`] and the Art History Brush's [`ART_HISTORY_BRUSH_TIP`], both with no
/// smoothing, the Remove tool's size [`REMOVE_TOOL_SIZE`], the Smudge
/// tool's [`SMUDGE_TOOL_TIP`] and the Pencil's [`PENCIL_TOOL_TIP`]; the other tools keep the
/// default tip.
pub(crate) fn fresh_brush(tool: Tool, current: &BrushSettings) -> BrushSettings {
@@ -140,6 +146,10 @@ pub(crate) fn fresh_brush(tool: Tool, current: &BrushSettings) -> BrushSettings
(brush.size, brush.hardness, brush.spacing) = CLONE_STAMP_TIP;
brush.smoothing.amount = 0.0;
}
Tool::ArtHistoryBrush => {
(brush.size, brush.hardness, brush.spacing) = ART_HISTORY_BRUSH_TIP;
brush.smoothing.amount = 0.0;
}
Tool::Remove => brush.size = REMOVE_TOOL_SIZE,
_ => {}
}
@@ -372,8 +372,8 @@ fn the_brush_is_a_per_tool_option_that_presets_keep() {
tool_event(&mut app, ToolEvent::Up { x: 30.0, y: 5.0 }, Modifiers::NONE);
}
/// #10263: the Art History Brush starts at full opacity the first time it is picked, though it
/// keeps the rest of the brush the old tool left (other tools still take its opacity).
/// #10263: the Art History Brush starts at full opacity the first time it is picked, with its own
/// tip rather than the old tool's (#12631; other tools still take its opacity).
#[test]
fn art_history_brush_starts_at_full_opacity() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
@@ -384,7 +384,7 @@ fn art_history_brush_starts_at_full_opacity() {
app.ui.tool = Tool::ArtHistoryBrush;
sync_tool_brush(&mut app);
assert_eq!(app.session.tools.brush.opacity, 1.0, "Art History starts at 100%");
assert_eq!(app.session.tools.brush.size, 40.0, "and inherits the size");
assert_eq!(app.session.tools.brush.size, 21.0, "with its own 21 px tip");
app.ui.tool = Tool::HistoryBrush;
sync_tool_brush(&mut app);
assert_eq!(app.session.tools.brush.opacity, 1.0, "the History Brush takes the Art History brush's opacity");
+48 -40
View File
@@ -10,7 +10,7 @@
//! shortcut whose command is disabled in the current state reports why on the status bar instead
//! of doing nothing silently, as the greyed menu item shows.
use std::collections::HashSet;
use std::collections::HashMap;
use craft::color_ui::ui::SwatchesCommand;
use craft::keymap::{Binding, Chord, CommandDef, CommandKind, Overrides, Scope};
@@ -208,17 +208,31 @@ fn binding(text: &str) -> Option<Binding> {
/// The menu path of command `id`: its menu, then its label.
fn menu_path(id: &str) -> Option<Vec<String>> {
let (menu, label): (&[&str], &str) = crate::menu_catalog::CATALOG
.iter()
.find(|c| c.3 == id)
.map(|c| (c.0, c.1))
.or_else(|| crate::menus::UI_COMMANDS.iter().find(|c| c.0 == id && !c.2.is_empty()).map(|c| (c.2, c.1)))?;
Some(menu.iter().chain([&label]).map(|part| (*part).to_string()).collect())
let (menu, label) = menu_paths().get(id)?;
Some(menu.iter().chain([label]).map(|part| (*part).to_string()).collect())
}
/// Adds `def` unless an earlier source gave its id or the runtime defines it.
fn push_row(rows: &mut Vec<CommandDef>, seen: &mut HashSet<String>, def: CommandDef) {
if !is_bridged(&def.command.id) && seen.insert(def.command.id.clone()) {
/// Each command's menu and label: the catalogue's first row of the command, else the first shell command of that id
/// that has a menu.
fn menu_paths() -> &'static HashMap<&'static str, (&'static [&'static str], &'static str)> {
static PATHS: std::sync::OnceLock<HashMap<&'static str, (&'static [&'static str], &'static str)>> = std::sync::OnceLock::new();
PATHS.get_or_init(|| {
let mut paths = HashMap::new();
for &(menu, label, _, id) in crate::menu_catalog::CATALOG {
paths.entry(id).or_insert((menu, label));
}
for &(id, label, menu, _) in crate::menus::UI_COMMANDS.iter().filter(|c| !c.2.is_empty()) {
paths.entry(id).or_insert((menu, label));
}
paths
})
}
/// Adds `def` unless an earlier source gave its id or the runtime defines it. `index` holds each row's place in
/// `rows` by its id.
fn push_row(rows: &mut Vec<CommandDef>, index: &mut HashMap<String, usize>, def: CommandDef) {
if !is_bridged(&def.command.id) && !index.contains_key(&def.command.id) {
index.insert(def.command.id.clone(), rows.len());
rows.push(def);
}
}
@@ -229,18 +243,18 @@ fn push_row(rows: &mut Vec<CommandDef>, seen: &mut HashSet<String>, def: Command
/// ([`RUNTIME_COMMANDS`]) are not rows. The Keyboard Shortcuts dialog lists exactly these rows.
pub(crate) fn command_rows(app: &PhotocraftApp) -> Vec<CommandDef> {
let mut rows: Vec<CommandDef> = Vec::new();
let mut seen: HashSet<String> = HashSet::new();
let mut index: HashMap<String, usize> = HashMap::new();
let app_row = |id: &str, label: &str| CommandDef::new(CommandRef::new(id), label, Scope::app());
// The tool letters, and the Shift+letter step of each group.
for def in crate::tool_shortcuts::defs(app) {
push_row(&mut rows, &mut seen, def);
push_row(&mut rows, &mut index, def);
}
for (letter, first) in crate::tool_shortcuts::group_letters() {
let label = format!("Next {}", first.label());
let mut def = app_row(&next_in_group_id(letter), &label).with_path(vec!["Tools".into(), label.clone()]);
def.defaults.extend(binding(&format!("Shift+{}", letter.to_ascii_uppercase())));
push_row(&mut rows, &mut seen, def);
push_row(&mut rows, &mut index, def);
}
// The held erase key is momentary; the hand and zoom keys are the runtime's.
for &(id, label, key) in photocraft_engine::prefs::TEMPORARY_TOOLS {
@@ -249,7 +263,7 @@ pub(crate) fn command_rows(app: &PhotocraftApp) -> Vec<CommandDef> {
}
let mut def = app_row(id, label).with_kind(CommandKind::Momentary).with_path(vec!["Tools".into(), "Temporary".into(), label.into()]);
def.defaults.extend(binding(key));
push_row(&mut rows, &mut seen, def);
push_row(&mut rows, &mut index, def);
}
// Alt+1 … Alt+0 set the brush smoothing (press only). The opacity and blend digits are command sets of the
// framework (`OpacityDigit`, `BlendStep`, `BlendShortcut`), so they are no rows here.
@@ -258,7 +272,7 @@ pub(crate) fn command_rows(app: &PhotocraftApp) -> Vec<CommandDef> {
let label = format!("Brush Smoothing {}%", digit * 10);
let mut def = app_row(&format!("tools.smoothing.{key}"), &label).with_path(vec!["Tools".into(), "Smoothing".into(), label.clone()]);
def.defaults.extend(binding(&format!("Alt+{key}")));
push_row(&mut rows, &mut seen, def);
push_row(&mut rows, &mut index, def);
}
// The engine's and the shell's commands, with the menu paths the shell knows.
@@ -267,43 +281,43 @@ pub(crate) fn command_rows(app: &PhotocraftApp) -> Vec<CommandDef> {
if def.paths.is_empty() {
def.paths.extend(menu_path(&def.command.id));
}
push_row(&mut rows, &mut seen, def);
push_row(&mut rows, &mut index, def);
}
// Live menu items whose command has no row yet carry the catalogue's key.
for &(_, label, shortcut, id) in crate::menu_catalog::CATALOG {
// A Window panel item runs its shell command (`menus::panel_alias`), which has the row.
let owner = crate::menus::panel_alias(id).filter(|alias| seen.contains(*alias)).unwrap_or(id);
let owner = crate::menus::panel_alias(id).filter(|alias| index.contains_key(*alias)).unwrap_or(id);
if label == "---" || !crate::menus::is_live(id) {
continue;
}
if seen.contains(owner) {
if let Some(&at) = index.get(owner) {
// An engine row that names no key takes the catalogue's.
if let Some(key) = shortcut.and_then(binding)
&& let Some(row) = rows.iter_mut().find(|row| row.command.id == owner && row.defaults.is_empty())
&& rows[at].defaults.is_empty()
{
row.defaults.push(key);
rows[at].defaults.push(key);
}
continue;
}
let mut def = app_row(id, label.trim_end_matches('…'));
def.paths.extend(menu_path(id));
def.defaults.extend(shortcut.and_then(binding));
push_row(&mut rows, &mut seen, def);
push_row(&mut rows, &mut index, def);
}
// Recorded actions run on their own key (the user's assignment is an override).
for action in app.session.actions.list.actions() {
let id = crate::actions::shortcut_id(&action.name);
push_row(&mut rows, &mut seen, app_row(&id, &action.name).with_path(vec!["Actions".into(), action.name.clone()]));
push_row(&mut rows, &mut index, app_row(&id, &action.name).with_path(vec!["Actions".into(), action.name.clone()]));
}
// A command's alternate keys (#3665: F3 is Copy as well as ⌘C), after every main key.
for &(id, key) in photocraft_engine::prefs::ALTERNATE_SHORTCUTS {
let Some(alternate) = binding(key) else { continue };
if let Some(def) = rows.iter_mut().find(|d| d.command.id == id)
&& !def.defaults.contains(&alternate)
if let Some(&at) = index.get(id)
&& !rows[at].defaults.contains(&alternate)
{
def.defaults.push(alternate);
rows[at].defaults.push(alternate);
}
}
// Photoshop: ⌥ added to an adjustment's own key opens it at its last settings (⌥⌘L, ⌥⌘M, #8900); Layer › New › Layer's
@@ -314,12 +328,12 @@ pub(crate) fn command_rows(app: &PhotocraftApp) -> Vec<CommandDef> {
}
}
// Edit in Quick Mask Mode is a button in the tool rail's footer, which shows its command's icon.
if let Some(def) = rows.iter_mut().find(|d| d.command.id == crate::panels::QUICK_MASK) {
def.icon = Some("square-dashed".into());
if let Some(&at) = index.get(crate::panels::QUICK_MASK) {
rows[at].icon = Some("square-dashed".into());
}
// Smart Objects › Reveal in Finder names this platform's file manager, in the list as in the menu.
if let Some(def) = rows.iter_mut().find(|d| d.command.id == "layer.smartObjects.revealInFinder") {
def.label = crate::menus::reveal_label().into();
if let Some(&at) = index.get("layer.smartObjects.revealInFinder") {
rows[at].label = crate::menus::reveal_label().into();
}
rows
}
@@ -350,25 +364,19 @@ pub(crate) fn bridged_rows() -> Vec<CommandDef> {
}
/// The app's command catalog over `rows` ([`command_rows`]). The runtime rebuilds its keymap when `generation`
/// changes, so the holder takes a new one only when [`same_rows`] says the rows differ from the held ones. It
/// compares where the menu model rebuilds, which covers a new action and a tool list change.
// PLAN: hub-w1's `framework_before_input` holds the rows and the generation, and calls this in place of `catalog(app)`.
/// changes, so the holder (`framework_before_input`) takes a new one only when it rebuilds the rows: when the actions
/// list's revision moved.
pub(crate) fn catalog(rows: Vec<CommandDef>, generation: u64) -> Option<AppCatalog> {
// `command_rows` gives each id once and every row the app scope, the two things `new` refuses; a refusal leaves the
// runtime with no app catalog.
AppCatalog::new(rows, generation).ok()
}
/// Whether two row lists describe the same commands, labels, paths and keys.
pub(crate) fn same_rows(a: &[CommandDef], b: &[CommandDef]) -> bool {
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| serde_json::to_value(x).ok() == serde_json::to_value(y).ok())
}
/// The user's bindings for the runtime's keymap: Edit › Keyboard Shortcuts changes (`prefs.shortcuts`,
/// `prefs.alternate_shortcuts`), the panel alias rule (#1272), and each row of [`RUNTIME_COMMANDS`] with its
/// effective keys, so the framework command carries PhotoCraft's keys. The pane moves stay unbound
/// (`app::framework`: PhotoCraft binds F6 and Shift+F6).
pub(crate) fn overrides(app: &PhotocraftApp) -> Overrides {
/// (`app::framework`: PhotoCraft binds F6 and Shift+F6). `rows` are the app's catalog rows ([`command_rows`]).
pub(crate) fn overrides(app: &PhotocraftApp, rows: &[CommandDef]) -> Overrides {
let prefs = app.session.prefs();
// PLAN: `keymap_defs::prefs_overrides` is top-w20's tp.PT25 row, assumed as `prefs_overrides(&Preferences) -> Overrides`.
let mut overrides = photocraft_engine::keymap_defs::prefs_overrides(prefs);
@@ -409,7 +417,7 @@ pub(crate) fn overrides(app: &PhotocraftApp) -> Overrides {
// A key an action holds is the action's alone (it is checked before every command's key, as in Photoshop): the
// command that has it by default keeps its other keys.
if !taken.is_empty() {
for row in command_rows(app) {
for row in rows {
let id = row.command.id.as_str();
if id.starts_with(crate::actions::SHORTCUT_PREFIX) || is_bridged(id) {
continue;
@@ -1,6 +1,9 @@
//! #127: every shortcut the UI displays (menu items, shell commands, tool tooltips) dispatches its
//! command, or the item is visibly disabled with a reason — through the whole app, with a
//! realistic layered document, from the places focus usually is.
//! command, or the item is visibly disabled with a reason, in the whole app with a realistic layered
//! document. Every shortcut's command is fired into the dispatcher directly; one shortcut of each kind
//! of key and route is pressed from the places focus usually is (#15678).
use std::collections::HashSet;
use craft::keymap::Chord;
use craft::ui::runtime::focus;
@@ -204,11 +207,146 @@ fn displayed(app: &PhotocraftApp) -> Vec<(String, String, bool)> {
v
}
/// Press every displayed shortcut from each place focus usually is: each dispatches its command,
/// or the menu shows it disabled and the press reports why. (Dry run: File › Exit, Open, Help
/// The way [`super::run_fired`] takes a fired command `id`: a row of [`super::RUNTIME_COMMANDS`] by its kind, a tool
/// letter, a Shift+letter group step, a recorded action, else an app command through [`super::dispatch_as`].
fn route(id: &str) -> String {
if let Some((_, bridged)) = super::RUNTIME_COMMANDS.iter().find(|(row, _)| *row == id) {
let kind = format!("{bridged:?}");
return kind.split('(').next().unwrap_or(&kind).to_string();
}
if crate::tool_shortcuts::tool(id).is_some() {
"tool".into()
} else if super::next_in_group_letter(id).is_some() {
"group".into()
} else if id.starts_with(crate::actions::SHORTCUT_PREFIX) {
"action".into()
} else {
"app".into()
}
}
/// What a press of `chord` shares with every other chord of its group: the keyboard path (the runtime's key stage,
/// a focused field's typing rule, a focused component's held keys) depends on the kind of key and the modifiers,
/// not on the command. Letters, digits and function keys are one kind each; every other key is its own kind.
fn key_kind(chord: &Chord) -> String {
let key = chord.key;
let kind = if key.is_letter() {
"letter".to_string()
} else if key.is_digit() {
"digit".to_string()
} else if key.is_function_key() {
"function".to_string()
} else {
format!("{key:?}")
};
let m = chord.mods;
format!("{kind} cmd={} ctrl={} alt={} shift={}", m.cmd, m.ctrl, m.alt, m.shift)
}
/// Every live displayed shortcut (id, text) and its chord.
fn live_chords(app: &PhotocraftApp) -> Vec<(String, String, Chord)> {
displayed(app)
.into_iter()
.filter(|(_, _, live)| *live)
.map(|(id, sc, _)| {
let chord = Chord::parse(&sc).unwrap_or_else(|_| panic!("{id}: unparsable {sc}"));
(id, sc, chord)
})
.collect()
}
/// One displayed shortcut per (route, kind of key, modifiers): the shortcuts whose press goes the same way.
fn representatives(app: &PhotocraftApp) -> Vec<(String, String, Chord)> {
let mut seen = HashSet::new();
live_chords(app).into_iter().filter(|(id, _, chord)| seen.insert((route(id), key_kind(chord)))).collect()
}
/// The command the runtime fires for `chord`, shown for menu row `id`: the row's own command when the keymap shows
/// the chord for it (no other command wins it where the binding applies), else the key's holder.
fn fired_by(ctx: &egui::Context, id: &str, chord: &Chord) -> Option<craft::ui::runtime::commands::CommandRef> {
let own = super::keymap_command(id);
if craft::ui::runtime::commands::chord(ctx, &own) == Some(*chord) {
return Some(own);
}
// `holder` answers with no panel active; it falls back to a panel's binding when no unscoped command holds the key.
craft::ui::runtime::commands::holder(ctx, chord)
}
/// Every displayed shortcut runs its menu item's command, or the menu shows the item disabled and the shortcut
/// says why: the keymap's command for each chord is fired into [`super::run_fired`] as a key press, with no key
/// events and no frames between them. The keyboard's way to the keymap is the same for every chord of a kind, and
/// [`every_kind_of_shortcut_dispatches_from_where_focus_usually_is`] presses one of each. The view, screen-mode,
/// momentary, Swatches and Workspace rows run in the runtime, the canvas or the shell instead of `run_fired`; that
/// test presses one of each kind of key for them. Every tool letter picks a tool of that letter.
#[test]
fn every_displayed_shortcut_runs_its_menu_item() {
use craft::ui::runtime::commands::{FirePhase, FireSource, Fired};
let mut h = harness();
set_dry_run(&h.ctx, true);
put_focus(&mut h, Place::Canvas);
let ctx = h.ctx.clone();
let items = crate::menus::menu_rows(h.state());
let chords = live_chords(h.state());
assert!(chords.len() > 100, "the menus show their shortcuts: {}", chords.len());
let fire = |h: &mut Harness<'_, Box<PhotocraftApp>>, command| {
super::run_fired(h.state_mut(), &ctx, &[Fired::new(command, FireSource::Key, FirePhase::Press, 0.0)]);
take_log(&ctx)
};
let mut failures = Vec::new();
let mut fired = 0;
for (id, sc, chord) in &chords {
let Some(command) = fired_by(&ctx, id, chord) else {
failures.push(format!("{sc} ({id}) runs nothing"));
continue;
};
match route(id).as_str() {
"View" | "Momentary" | "ScreenMode" | "Swatches" | "Workspace" => {
if command != super::keymap_command(id) {
failures.push(format!("{sc} ({id}) fires {command:?}"));
}
continue;
}
"tool" | "group" => {
let want = crate::tool_shortcuts::tool(id).map(Tool::key).or_else(|| super::next_in_group_letter(id));
fire(&mut h, command);
if Some(h.state().ui.tool.key()) != want {
failures.push(format!("{sc} ({id}) left {:?}", h.state().ui.tool));
}
continue;
}
_ => {}
}
let enabled = items.iter().find(|i| i.command.id == *id).map_or_else(|| crate::menus::is_enabled(h.state(), id), |i| i.enabled);
fired += 1;
match fire(&mut h, command).as_slice() {
[(bound, Outcome::Ran)] if same(id, bound) && enabled => {}
[(bound, Outcome::Disabled(why))] if same(id, bound) && !enabled && !why.is_empty() => {}
other => failures.push(format!("{sc} ({id}, menu enabled: {enabled}) -> {other:?}")),
}
}
assert!(fired > 80, "most displayed shortcuts go through run_fired: {fired}");
for t in Tool::ALL.into_iter().filter(|t| t.key() != '\0') {
let chord = Chord::parse(&t.key().to_string()).unwrap_or_else(|_| panic!("tool key {}", t.key()));
let Some(command) = craft::ui::runtime::commands::holder(&ctx, &chord) else {
failures.push(format!("tool key {} runs nothing", t.key()));
continue;
};
h.state_mut().ui.tool = if t.key() == 'H' { Tool::Move } else { Tool::Hand };
fire(&mut h, command);
if h.state().ui.tool.key() != t.key() {
failures.push(format!("tool key {} left {:?}", t.key(), h.state().ui.tool));
}
}
assert!(failures.is_empty(), "{} shortcut failures:\n{}", failures.len(), failures.join("\n"));
}
/// Press one displayed shortcut of each (route, kind of key, modifiers) from each place focus usually is: each
/// dispatches its command, or the menu shows it disabled and the press reports why; a focused field keeps its typing
/// keys and a focused component the keys it holds. The other shortcuts of a group take the same path to a different
/// row of the table [`every_displayed_shortcut_runs_its_menu_item`] checks. (Dry run: File › Exit, Open, Help
/// links… resolve and check enablement without running.)
#[test]
fn every_displayed_shortcut_dispatches_from_where_focus_usually_is() {
fn every_kind_of_shortcut_dispatches_from_where_focus_usually_is() {
let mut failures = Vec::new();
for place in [Place::Canvas, Place::LayersRow, Place::FocusedWidget, Place::OpacityField] {
let mut h = harness();
@@ -216,11 +354,7 @@ fn every_displayed_shortcut_dispatches_from_where_focus_usually_is() {
put_focus(&mut h, place);
let typing = WindowHost::of(&h.ctx).typing();
let items = crate::menus::menu_rows(h.state());
for (id, sc, live) in displayed(h.state()) {
if !live {
continue;
}
let chord = Chord::parse(&sc).unwrap_or_else(|_| panic!("{id}: unparsable {sc}"));
for (id, sc, chord) in representatives(h.state()) {
// A press the focused component holds (the Layers rows' stacking and visibility keys)
// is the component's and reaches no app command.
let held = focus_holds(&h.ctx, chord);
@@ -241,14 +375,19 @@ fn every_displayed_shortcut_dispatches_from_where_focus_usually_is() {
other => failures.push(format!("{place:?}: {sc} ({id}, menu enabled: {enabled}) -> {other:?}")),
}
}
// Tool letters from the tools panel tooltips ("Brush Tool (B)").
if !typing {
for t in Tool::ALL.into_iter().filter(|t| t.key() != '\0') {
h.state_mut().ui.tool = if t.key() == 'H' { Tool::Move } else { Tool::Hand };
press_in_one_frame(&mut h, &t.key().to_string());
if h.state().ui.tool.key() != t.key() {
failures.push(format!("{place:?}: tool key {} left {:?}", t.key(), h.state().ui.tool));
}
// Tool letters from the tools panel tooltips ("Brush Tool (B)"): a letter of one tool and a letter its group
// shares take different picks (`pick_tool`); the table checks every letter's tool. In a focused text field the
// letter is typed and the tool stays.
let shared = |t: &Tool| Tool::ALL.iter().filter(|o| o.key() == t.key()).count() > 1;
let one = Tool::ALL.into_iter().find(|t| t.key() != '\0' && !shared(t));
let many = Tool::ALL.into_iter().find(|t| t.key() != '\0' && shared(t));
for t in one.into_iter().chain(many) {
let start = if t.key() == 'H' { Tool::Move } else { Tool::Hand };
h.state_mut().ui.tool = start;
press_in_one_frame(&mut h, &t.key().to_string());
let want = if typing { start } else { t };
if h.state().ui.tool.key() != want.key() {
failures.push(format!("{place:?}: tool key {} left {:?}, expected a {} tool", t.key(), h.state().ui.tool, want.key()));
}
}
}
+2
View File
@@ -993,6 +993,8 @@ mod polygon_lasso_tests;
#[cfg(test)]
mod window_frame_tests;
#[cfg(test)]
mod artboards_overlap_dialog_tests;
#[cfg(test)]
mod browse_field_tests;
#[cfg(test)]
+7 -2
View File
@@ -76,7 +76,7 @@ pub fn sync(app: &mut PhotocraftApp, ctx: &egui::Context) {
/// What the menus' rows depend on, cheaply: commands run, the documents (their names, in tab
/// order, for the Window menu) and the active one's revision, selection, recent files, panels and
/// view state, the language. `input` forces a change on frames with a click or key press, which
/// view state, the keymap, and the preferences the rows show. `input` forces a change on frames with a click or key press, which
/// covers state the hash doesn't list.
pub(crate) fn state_hash(app: &PhotocraftApp, input: Option<u64>) -> u64 {
let mut h = DefaultHasher::new();
@@ -119,7 +119,12 @@ pub(crate) fn state_hash(app: &PhotocraftApp, input: Option<u64>) -> u64 {
crate::panel_docking::is_checked(app, panel.id).hash(&mut h);
}
serde_json::to_string(&(&ui.extras, &ui.view, ui.theme.id().as_str(), ui.theme.is_dark(), ui.tool)).unwrap_or_default().hash(&mut h);
s.prefs().interface.language.hash(&mut h);
// The preferences the rows show: the language, Edit › Menus (hidden rows, colours), the Quick Export label and
// the Font Preview Size tick.
let prefs = s.prefs();
prefs.interface.language.hash(&mut h);
(&prefs.menus.hidden, &prefs.menus.colors, prefs.interface.show_menu_colors).hash(&mut h);
(prefs.export.quick_export_format, prefs.type_.font_preview).hash(&mut h);
h.finish()
}
@@ -237,3 +237,22 @@ fn the_task_bar_tick_follows_the_bar_hidden_without_a_menu_click() {
h.run_steps(2);
assert_eq!(ticked(&synced), Some(true), "ticked again once it shows");
}
/// The menus follow the preferences they show, even when they change without input (settings merged from another
/// instance), and not the tool and colour preferences the app saves on every change.
#[test]
fn the_menu_state_follows_the_preferences_the_rows_show() {
let mut app = app(false);
let shown = state_hash(&app, None);
app.session.edit_prefs(|p| {
p.selected_tool = json!("Brush");
p.tool_colors = Default::default();
});
assert_eq!(state_hash(&app, None), shown, "the saved tool and colours are not in the menus");
app.session.edit_prefs(|p| p.menus.hidden.push("filter.blur.gaussian".into()));
let hidden = state_hash(&app, None);
assert_ne!(hidden, shown, "Edit › Menus hides a row");
app.session.edit_prefs(|p| p.export.quick_export_format = photocraft_engine::prefs::QuickExportFormat::Jpg);
assert_ne!(state_hash(&app, None), hidden, "the Quick Export label names the format");
}
@@ -262,6 +262,15 @@ pub(super) fn params_for(app: &mut PhotocraftApp, id: &str) -> Option<(Vec<Param
plain(vec![
folder("dir", tl!("Destination"), dir),
Param::new("prefix", tl!("File Name Prefix"), ParamKind::text(stem(&name))),
// Include Overlapping Areas / Artboard Content Only, right below the prefix, with no caption (#13629).
Param::new(
"content",
"",
ParamKind::radio(
opts(&[("overlapping", tl!("Include Overlapping Areas")), ("artboard", tl!("Artboard Content Only"))]),
Some("overlapping".to_owned()),
),
),
choice("format", tl!("File Type"), export_formats(), "png"),
export_quality(),
])
+16 -1
View File
@@ -240,10 +240,16 @@ fn stamp_members(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) {
edit_brush(app, &flow, |b, v| b.flow = v);
return;
}
if matches!(tool, Tool::CloneStamp | Tool::HistoryBrush | Tool::ArtHistoryBrush) {
if matches!(tool, Tool::CloneStamp | Tool::HistoryBrush) {
let opacity = percent_field(ui, tl!("Opacity"), brush.opacity, 1.0..=100.0);
edit_brush(app, &opacity, |b, v| b.opacity = v);
}
// The Art History Brush's Opacity carries the reference's tooltip (#12630).
if tool == Tool::ArtHistoryBrush {
let opacity = number_field_with_tip(ui, tl!("Opacity"), brush.opacity * 100.0, 1.0..=100.0, "%", Some(tl!("Set opacity for stroke")))
.map(|percent| percent / 100.0);
edit_brush(app, &opacity, |b, v| b.opacity = v);
}
if matches!(tool, Tool::CloneStamp | Tool::HistoryBrush) {
let flow = percent_field(ui, tl!("Flow"), brush.flow, 1.0..=100.0);
edit_brush(app, &flow, |b, v| b.flow = v);
@@ -276,9 +282,18 @@ pub(super) fn check(ui: &mut egui::Ui, label: &str, value: &mut bool) {
/// A number field named `label` over `value` (in `unit` when it is not empty), limited to `range`. The events of this
/// pass carry the edited value; an emptied field gives none.
pub(super) fn number_field(ui: &mut egui::Ui, label: &str, value: f32, range: RangeInclusive<f64>, unit: &'static str) -> EditEvents<f32> {
number_field_with_tip(ui, label, value, range, unit, None)
}
/// [`number_field`] with `tip` as the field's tooltip when there is one.
fn number_field_with_tip(ui: &mut egui::Ui, label: &str, value: f32, range: RangeInclusive<f64>, unit: &'static str, tip: Option<&str>) -> EditEvents<f32> {
let events = labelled(ui, label, |ui| {
let field = NumberField::new(label.to_owned(), Bind::given(Some(f64::from(value)))).range(range.clone()).scrub_by_label();
let field = if unit.is_empty() { field } else { field.unit(unit) };
let field = match tip {
Some(tip) => field.tooltip(tip.to_owned()),
None => field,
};
field.show(ui).events.clone()
});
events.unwrap_or_default().filter_map(|v| v.map(|v| v as f32))
+6 -6
View File
@@ -338,14 +338,14 @@ pub(crate) fn slots(toolbar: &ToolbarCustomization) -> Vec<ToolSlot<Tool>> {
slots
}
/// The rail's [`slots`] for the stored layout, built once per preferences revision ([`PrefsStore::rev`]): the toolbar, its
/// measure and the dock's grid read them several times a frame, and the layout changes only with the preferences.
/// The rail's [`slots`] for the stored layout, built once per catalog revision ([`PrefsStore::catalog_rev`], which moves
/// with the toolbar layout): the toolbar, its measure and the dock's grid read them several times a frame.
///
/// [`PrefsStore::rev`]: photocraft_engine::prefs::PrefsStore::rev
/// [`PrefsStore::catalog_rev`]: photocraft_engine::prefs::PrefsStore::catalog_rev
#[derive(Default)]
pub(crate) struct ToolbarSlots(std::cell::RefCell<Option<(u64, RailSlots)>>);
/// The rail's slots, shared by the readers of one preferences revision.
/// The rail's slots, shared by the readers of one catalog revision.
type RailSlots = std::sync::Arc<[ToolSlot<Tool>]>;
impl ToolbarSlots {
@@ -353,10 +353,10 @@ impl ToolbarSlots {
pub(crate) fn get(&self, prefs: &photocraft_engine::prefs::PrefsStore) -> RailSlots {
let mut held = self.0.borrow_mut();
match &*held {
Some((rev, slots)) if *rev == prefs.rev() => slots.clone(),
Some((rev, slots)) if *rev == prefs.catalog_rev() => slots.clone(),
_ => {
let built: RailSlots = slots(&prefs.get().toolbar).into();
*held = Some((prefs.rev(), built.clone()));
*held = Some((prefs.catalog_rev(), built.clone()));
built
}
}
@@ -4,7 +4,7 @@
//! The session holds everything the dialog edits: the draft keymap, the shortcut sets, the Menus
//! draft and the text of a set waiting to be reviewed. Cancel drops it and the runtime never saw
//! a change; OK writes the preferences once ([`save_keys`], then the menus), and the runtime's
//! keymap follows the new preferences revision (`shortcut_dispatch::overrides`).
//! keymap follows the new shortcut preferences (`shortcut_dispatch::overrides`).
//!
//! The Toolbar tab is not here: Edit › Toolbar opens the toolbar drawer.
@@ -79,7 +79,12 @@ pub(crate) fn profiles_of(prefs: &Preferences) -> Profiles {
/// runtime's keymap is built for, and the preferences' bindings as overrides.
pub(crate) fn draft_keymap(app: &PhotocraftApp) -> Keymap {
let platform = windows::os_of(app.ctx());
Keymap::new(crate::shortcut_dispatch::command_rows(app).into_iter().chain(crate::shortcut_dispatch::bridged_rows()).collect(), Scopes::new(), platform)
// The runtime catalog's held rows while they are current; built here before the first frame holds them.
let rows = match app.framework.catalog_rows_at(app.session.actions.list.revision()) {
Some(rows) => rows.to_vec(),
None => crate::shortcut_dispatch::command_rows(app),
};
Keymap::new(rows.into_iter().chain(crate::shortcut_dispatch::bridged_rows()).collect(), Scopes::new(), platform)
.with_reserved(reserved::system(platform))
.with_overrides(keymap_defs::prefs_overrides(app.session.prefs()))
}
+6
View File
@@ -51,6 +51,9 @@ pub mod type_tool;
pub(super) mod type_transform;
pub mod vector_ui;
#[cfg(test)]
mod art_history_fields_tests;
#[cfg(test)]
mod art_history_default_style_tests;
#[cfg(test)]
@@ -70,3 +73,6 @@ mod object_selection_mode_tests;
mod path_selection_ctrl_direct_tests;
#[cfg(test)]
mod path_selection_shape_over_saved_path_tests;
#[cfg(test)]
mod art_history_reset_tip_tests;
@@ -0,0 +1,125 @@
//! #12630: the Art History Brush's Area takes whole pixels 0..500 and Tolerance whole percents
//! 0..100; a value typed past either range becomes the closest one with the reference's "Closest
//! value inserted" alert. Opacity, Area and Tolerance carry the reference's tooltips, and the bar
//! has no hint text.
use egui::accesskit::Role;
use egui::vec2;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::json;
use super::retouch_ui::bar::history::{ART_HISTORY_AREA_ALERT, ART_HISTORY_TOLERANCE_ALERT};
use crate::PhotocraftApp;
use crate::state::Tool;
type H = Harness<'static, Box<PhotocraftApp>>;
/// The options bar with the Art History Brush active, and the dialog host its alerts open on.
fn bar() -> H {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 80, "height": 80})).unwrap();
app.ui.tool = Tool::ArtHistoryBrush;
crate::theme::install_fonts(app.ctx());
crate::theme::apply(app.ctx(), &crate::theme::AppTheme::pro());
let mut h = Harness::builder().with_context(app.ctx().clone()).with_size(vec2(1800.0, 300.0)).with_step_dt(1.0 / 60.0).build_ui_state(
move |ui, app: &mut Box<PhotocraftApp>| {
crate::panels::options_bar(app, ui);
crate::dialogs::run(app, ui);
},
app,
);
h.run_steps(4);
h
}
/// The number field named `label`, with or without its caption's colon.
fn field<'a>(h: &'a H, label: &str) -> Option<egui_kittest::Node<'a>> {
h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().is_some_and(|l| l.trim_end_matches(':') == label))
}
/// Types `text` into the field named `label` and commits it with Enter.
fn type_into(h: &mut H, label: &str, text: &str) {
field(h, label).unwrap_or_else(|| panic!("the {label} field")).click();
h.run_steps(1);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.event(egui::Event::Text(text.into()));
h.run_steps(1);
h.key_press(egui::Key::Enter);
h.run_steps(3);
}
/// The messages of the open framework alerts.
fn alerts(h: &H) -> Vec<String> {
h.state().framework.dialogs.open_dialogs().iter().filter_map(|d| d.fields.as_ref()?.get("message")?.as_str().map(str::to_string)).collect()
}
/// The description (tooltip) of the number field named `label`.
fn tip(h: &H, label: &str) -> Option<String> {
field(h, label)?.accesskit_node().description().map(|d| d.to_string())
}
#[test]
fn area_past_0_500_takes_the_closest_value_and_alerts() {
for (typed, want) in [("600", 500.0), ("-5", 0.0)] {
let mut h = bar();
type_into(&mut h, "Area", typed);
assert_eq!(h.state().ui.tool_options.art_history_area, want, "{typed}");
assert_eq!(alerts(&h), vec![ART_HISTORY_AREA_ALERT.to_string()], "{typed}: one alert");
}
}
#[test]
fn area_in_range_is_a_whole_number_without_an_alert() {
for (typed, want) in [("500", 500.0), ("250", 250.0), ("0", 0.0), ("37.6", 38.0)] {
let mut h = bar();
type_into(&mut h, "Area", typed);
assert_eq!(h.state().ui.tool_options.art_history_area, want, "{typed}");
assert!(alerts(&h).is_empty(), "{typed} is in range: {:?}", alerts(&h));
}
}
#[test]
fn tolerance_past_0_100_takes_the_closest_value_and_alerts() {
for (typed, want) in [("150", 100.0), ("-3", 0.0)] {
let mut h = bar();
type_into(&mut h, "Tolerance", typed);
assert_eq!(h.state().ui.tool_options.art_history_tolerance, want, "{typed}");
assert_eq!(alerts(&h), vec![ART_HISTORY_TOLERANCE_ALERT.to_string()], "{typed}: one alert");
}
}
#[test]
fn tolerance_in_range_is_a_whole_number_without_an_alert() {
for (typed, want) in [("100", 100.0), ("12.4", 12.0)] {
let mut h = bar();
type_into(&mut h, "Tolerance", typed);
assert_eq!(h.state().ui.tool_options.art_history_tolerance, want, "{typed}");
assert!(alerts(&h).is_empty(), "{typed} is in range");
}
}
#[test]
fn opacity_area_and_tolerance_have_the_reference_tooltips() {
let h = bar();
assert_eq!(tip(&h, "Opacity").as_deref(), Some("Set opacity for stroke"));
assert_eq!(tip(&h, "Area").as_deref(), Some("Painting area diameter"));
assert_eq!(tip(&h, "Tolerance").as_deref(), Some("Painting tolerance"));
}
#[test]
fn the_bar_has_no_hint_text() {
let h = bar();
assert!(h.query_by_label("Stylized dabs from a history state").is_none());
}
#[test]
fn the_command_takes_an_area_up_to_500() {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 80, "height": 80})).unwrap();
let stroke = |area: f64| json!({"points": [[10, 40], [70, 40]], "size": 8, "area": area});
assert!(app.run("paint.artHistoryBrush", stroke(500.0)).is_ok());
assert!(app.run("paint.artHistoryBrush", stroke(250.0)).is_ok());
assert!(app.run("paint.artHistoryBrush", stroke(500.5)).is_err());
assert!(app.run("paint.artHistoryBrush", stroke(-1.0)).is_err());
}
@@ -0,0 +1,87 @@
//! #12638: when the Art History Brush can't paint, a stroke opens the reference application's
//! alert with OK and paints nothing: at the press for a hidden target layer, Lock All, Lock Image
//! Pixels or a group's pixels; at the release for the source refusals (another canvas size, no
//! source, a target layer the source state lacks). The History Brush keeps today's status bar.
use serde_json::json;
use super::brush_refusal_alert_tests::{active, alerts, app, refused, steps, stroke};
use super::*;
/// The fixture's history: 0 Open, 1 New Layer, 2 Fill; the source is the Open state, which holds
/// only the Background, so a stroke paints from row 1, which holds the active layer.
fn art_history() -> Box<PhotocraftApp> {
let mut app = app(Tool::ArtHistoryBrush);
app.run("history.setSource", json!({"state": 1})).unwrap();
app
}
#[test]
fn a_hidden_target_layer() {
let mut app = art_history();
let id = active(&app);
app.run("layer.setProps", json!({"layer": id, "visible": false})).unwrap();
refused(&mut app, "Could not use the art history brush because the target layer is hidden.");
assert!(app.ui.status.is_empty() || !app.ui.status_error, "no status-bar error as well: {:?}", app.ui.status);
}
#[test]
fn lock_all_and_lock_image_pixels() {
for lock in ["all", "pixels"] {
let mut app = art_history();
app.run("layer.lockLayers", json!({ lock: true })).unwrap();
refused(&mut app, "Could not use the art history brush because the layer is locked.");
}
}
#[test]
fn a_group_is_active() {
let mut app = art_history();
app.run("layer.new.group", json!({})).unwrap();
refused(&mut app, "Could not use the art history brush because the pixels in a group cannot be edited without merging the group.");
}
#[test]
fn the_canvas_size_changed() {
let mut app = art_history();
app.run("image.canvasSize", json!({"width": 80, "height": 64, "anchor": "topLeft"})).unwrap();
refused(&mut app, "Could not use the art history brush because the current canvas size does not match that of the history state.");
assert!(app.ui.status.is_empty() || !app.ui.status_error, "no status-bar error as well: {:?}", app.ui.status);
}
#[test]
fn no_source_is_set() {
let mut app = app(Tool::ArtHistoryBrush);
let snap = app.run("history.newSnapshot", json!({})).unwrap()["snapshot"].clone();
app.run("history.setSource", json!({"snapshot": snap})).unwrap();
app.run("history.deleteSnapshot", json!({"snapshot": snap})).unwrap();
refused(&mut app, "Could not use the art history brush because no history state has been designated as the source for painting.");
}
#[test]
fn the_source_state_lacks_the_target_layer() {
let mut app = art_history();
app.run("layer.new.layer", json!({})).unwrap();
refused(&mut app, "Could not use the art history brush because the history state lacks a corresponding layer.");
}
#[test]
fn a_stroke_from_a_valid_source_paints() {
let mut app = art_history();
app.run("history.setSource", json!({"state": 2})).unwrap();
app.run("edit.fill", json!({"color": "#1e1edc"})).unwrap();
let before = steps(&app);
stroke(&mut app);
assert!(alerts(&app).is_empty(), "{:?}", alerts(&app));
assert_eq!(steps(&app), before + 1);
}
/// The History Brush keeps its status-bar texts.
#[test]
fn the_history_brush_keeps_the_status_bar() {
let mut app = app(Tool::HistoryBrush);
app.run("image.canvasSize", json!({"width": 80, "height": 64, "anchor": "topLeft"})).unwrap();
stroke(&mut app);
assert!(alerts(&app).is_empty(), "{:?}", alerts(&app));
assert!(!app.ui.status.contains("art history"), "{}", app.ui.status);
}
@@ -0,0 +1,116 @@
//! #12631: the Art History Brush starts, and comes back after Reset Tool, with the reference
//! application's tip: a 21 px soft round (hardness 0 %, angle 0°, roundness 100 %) at 25 %
//! spacing and full opacity, with no smoothing. Other tools' starting tips are checked by `reset_tip_tests`.
use serde_json::json;
use crate::PhotocraftApp;
use crate::control::{ControlRequest, handle};
use crate::state::Tool;
fn app() -> Box<PhotocraftApp> {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.sync_views();
app
}
/// Run a menu command as the control channel does, then the frame's sync.
fn invoke(app: &mut PhotocraftApp, id: &str, params: serde_json::Value) {
let ctx = app.ctx().clone();
let (req, _rx) = ControlRequest::new("ui.menu.invoke", json!({"id": id, "params": params}));
handle(app, &ctx, &req);
app.sync_views();
}
/// Pick `tool`, and swap its brush in as a frame does.
fn pick(app: &mut PhotocraftApp, tool: Tool) {
app.ui.tool = tool;
crate::paint_mouse::sync_tool_brush(app);
app.sync_views();
}
/// Size, hardness, spacing, angle, roundness, opacity and smoothing of the live brush, as
/// `brush.get` reports the tip.
fn tip(app: &mut PhotocraftApp) -> [f64; 7] {
let b = app.run("brush.get", json!({})).unwrap();
let [size, hardness, spacing, angle, roundness] = ["size", "hardness", "spacing", "angle", "roundness"].map(|k| b[k].as_f64().unwrap());
let brush = &app.session.tools.brush;
let (opacity, smoothing) = (f64::from(brush.opacity), f64::from(brush.smoothing.amount));
[size, hardness, spacing, angle, roundness, opacity, smoothing].map(|v| (v * 1e4).round() / 1e4)
}
/// A tip that is no tool's starting tip, so a reset has something to undo.
fn scramble(app: &mut PhotocraftApp) {
let b = &mut app.session.tools.brush;
(b.size, b.hardness, b.spacing, b.angle, b.roundness, b.opacity, b.smoothing.amount) = (57.0, 0.4, 0.6, 30.0, 0.5, 0.3, 0.3);
}
const ART_HISTORY_TIP: [f64; 7] = [21.0, 0.0, 0.25, 0.0, 1.0, 1.0, 0.0];
#[test]
fn reset_tool_gives_the_art_history_brush_a_21_px_soft_tip() {
let mut app = app();
pick(&mut app, Tool::ArtHistoryBrush);
scramble(&mut app);
invoke(&mut app, "tool.reset", json!({}));
assert_eq!(tip(&mut app), ART_HISTORY_TIP);
// The options-bar brush chip reads the live brush's rounded size.
assert_eq!(app.session.tools.brush.size.round(), 21.0);
}
#[test]
fn a_first_use_starts_with_the_tip() {
// No stored tool brushes, as on a fresh install: the Art History Brush's first pick, after
// another tool's tip.
let mut app = app();
pick(&mut app, Tool::Brush);
scramble(&mut app);
pick(&mut app, Tool::ArtHistoryBrush);
assert_eq!(tip(&mut app), ART_HISTORY_TIP);
// Its own tip is then kept across tool switches.
app.session.tools.brush.size = 42.0;
pick(&mut app, Tool::Brush);
pick(&mut app, Tool::ArtHistoryBrush);
assert_eq!(tip(&mut app)[0], 42.0);
}
#[test]
fn a_first_use_keeps_the_outgoing_pressure_toggles() {
// The pressure settings of the tip are not measured, so they stay what the first pick gave
// before: the outgoing brush's.
let mut app = app();
pick(&mut app, Tool::Brush);
(app.session.tools.brush.pressure_size, app.session.tools.brush.pressure_opacity) = (true, true);
pick(&mut app, Tool::ArtHistoryBrush);
let b = &app.session.tools.brush;
assert_eq!((b.pressure_size, b.pressure_opacity), (true, true));
assert_eq!(tip(&mut app), ART_HISTORY_TIP);
}
#[test]
fn reset_all_tools_gives_it_the_tip_active_or_picked_later() {
let mut app = app();
pick(&mut app, Tool::ArtHistoryBrush);
scramble(&mut app);
invoke(&mut app, "tool.resetAll", json!({"confirmed": true}));
assert_eq!(tip(&mut app), ART_HISTORY_TIP, "active");
let mut app = self::app();
pick(&mut app, Tool::ArtHistoryBrush);
scramble(&mut app);
pick(&mut app, Tool::Pencil);
invoke(&mut app, "tool.resetAll", json!({"confirmed": true}));
pick(&mut app, Tool::ArtHistoryBrush);
assert_eq!(tip(&mut app), ART_HISTORY_TIP, "picked after the reset");
}
/// The other tools' starting tips are checked by `reset_tip_tests`; the History Brush's first use
/// still takes the current tip, as before.
#[test]
fn the_history_brush_first_use_keeps_the_current_tip() {
let mut a = app();
pick(&mut a, Tool::Pencil);
scramble(&mut a);
pick(&mut a, Tool::HistoryBrush);
assert_eq!(tip(&mut a)[0], 57.0, "History Brush, first use");
}
@@ -287,6 +287,11 @@ pub(crate) fn command_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandSta
vec![(ArtboardCommand::AddNew.into(), state)]
}
/// What [`command_states`] reads: whether a document is open, and the placing mode.
pub(crate) fn command_states_key(app: &PhotocraftApp) -> crate::app::framework::StatesKey {
[u64::from(app.session.active().is_some()), u64::from(app.ui.artboard_tool.adding), 0, 0]
}
/// Runs a fired Artboard command: Add New Artboard flips the placing mode and adds no board. `ctx` is the shape every
/// command source takes.
pub(crate) fn run_fired(app: &mut PhotocraftApp, _ctx: &egui::Context, command: &CommandRef) -> bool {
+11 -5
View File
@@ -38,14 +38,15 @@ fn mode_tool_name(tool: Tool) -> Option<&'static str> {
}
/// The tool's name in the alerts, for the tools whose wording was measured: the Brush, the
/// Sharpen tool (#12952), the Sponge (#13030), the Smudge tool (#12965) and the Classic gradient
/// (the live Gradient makes a fill layer and isn't measured, #12017).
/// Sharpen tool (#12952), the Sponge (#13030), the Smudge tool (#12965), the Art History Brush
/// (#12638) and the Classic gradient (the live Gradient makes a fill layer and isn't measured, #12017).
pub fn tool_name(app: &PhotocraftApp, tool: Tool) -> Option<&'static str> {
match tool {
Tool::Brush => Some(tl!("brush tool")),
Tool::Sharpen => Some(tl!("sharpen tool")),
Tool::Sponge => Some(tl!("sponge tool")),
Tool::Smudge => Some(tl!("smudge tool")),
Tool::ArtHistoryBrush => Some(tl!("art history brush")),
Tool::Gradient if app.ui.tool_options.gradient_classic => Some(tl!("gradient tool")),
_ => None,
}
@@ -99,10 +100,11 @@ fn layer_refusal(app: &PhotocraftApp, tool: Tool) -> Option<&'static str> {
}
}
/// Whether `locks` refuse `tool`: Lock All, and for the Sharpen, Sponge and Smudge tools Lock Image
/// Pixels as well (measured for them; the Brush keeps today's behaviour there).
/// Whether `locks` refuse `tool`: Lock All, and for the Sharpen, Sponge and Smudge tools and the
/// Art History Brush Lock Image Pixels as well (measured for them; the Brush keeps today's
/// behaviour there).
fn locked(locks: photocraft_doc::Locks, tool: Tool) -> bool {
locks.all || (matches!(tool, Tool::Sharpen | Tool::Sponge | Tool::Smudge) && locks.pixels)
locks.all || (matches!(tool, Tool::Sharpen | Tool::Sponge | Tool::Smudge | Tool::ArtHistoryBrush) && locks.pixels)
}
#[cfg(test)]
@@ -120,3 +122,7 @@ mod smudge_refusal_alert_tests;
#[cfg(test)]
#[path = "remove_hidden_layer_tests.rs"]
mod remove_hidden_layer_tests;
#[cfg(test)]
#[path = "art_history_refusal_alert_tests.rs"]
mod art_history_refusal_alert_tests;
+174 -1
View File
@@ -8,6 +8,9 @@
//! - ↵ (or ✓) applies: `image.perspectiveCrop` maps the quad onto an upright rectangle, the whole document in one
//! undo step. Its size comes from the options bar's W × H and resolution (`CropSizeFields`), or with them empty
//! from the rectangle the quad shows in perspective. Esc (or ⊘) cancels.
//! - a document holding a type layer or a smart object, and a Bitmap document, refuse the press with the reference's
//! alert (message + OK) and start nothing: no box, no corner, no session (#11799). `image.perspectiveCrop` answers
//! with the same text, so ↵ is refused the same way.
//!
//! The quad lives in the tool, not in the document: its edits are no history steps. A pending quad belongs to the
//! document it was drawn on, like the Crop tool's frame.
@@ -19,6 +22,7 @@ use craft::ui::bars::BarOutput;
use craft::ui::canvas::{CropShield, ToolHostResponse};
use craft::ui::contract::Bind;
use craft::ui::runtime::edit::cancel_all;
use photocraft_engine::perspective_crop_cmds::{BITMAP_MODE_ERROR, UNSUPPORTED_LAYERS_ERROR};
use serde_json::json;
use crate::PhotocraftApp;
@@ -65,6 +69,36 @@ fn input<'a>(app: &PhotocraftApp) -> PerspectiveInput<'a> {
input
}
/// The alert this document gets instead of a perspective crop (#11799): `Some(text)` means the tool
/// refuses the press. The check is the engine's, so the press and `image.perspectiveCrop` can never
/// disagree about what is cropped.
fn document_alert(app: &PhotocraftApp) -> Option<&'static str> {
app.session.active().and_then(|st| photocraft_engine::perspective_crop_cmds::refusal(&st.doc))
}
/// The alert as `image.perspectiveCrop`'s error text (#11799), so ↵ shows what the press shows
/// rather than only the status bar.
fn error_alert(error: &str) -> Option<&'static str> {
[UNSUPPORTED_LAYERS_ERROR, BITMAP_MODE_ERROR].into_iter().find(|text| *text == error)
}
/// Opens the alert: the message and an OK button, as a refused Move does (`move_lock::prompt`).
fn refuse(app: &mut PhotocraftApp, message: &str) {
crate::dialogs::alerts::alert(app, alert_text(message));
}
/// The alert in the UI language. Literal keys, so `cargo xtask i18n-coverage` lists both alerts for
/// the translators; `alert_keys_match_the_engine_texts` keeps them equal to the engine's texts.
fn alert_text(message: &str) -> &str {
match message {
UNSUPPORTED_LAYERS_ERROR => tl!("Could not use the perspective crop tool because the image contains unsupported layers types."),
BITMAP_MODE_ERROR => {
tl!("Could not use the perspective crop tool because it does not work with Bitmap images (convert image to Grayscale mode to edit).")
}
other => tl!(other),
}
}
/// What the app does with a finished pass: a new quad's first press drops an active selection as its own "Deselect"
/// step, as in Photoshop (#11975), so it is gone after the commit and after Esc too. The pass reports the session's
/// first press as `Started`; refused (a job locks the document, the reason in the status bar), the press is cancelled
@@ -80,6 +114,15 @@ pub(crate) fn drain(app: &mut PhotocraftApp, state: &mut PerspectiveCrop, _respo
if !events.iter().any(|event| matches!(event, PerspectiveCropEvent::Started)) {
return;
}
// A document the tool can't crop (#11799): the press shows the reference's alert and starts
// nothing - cancelled and cleared like a refused Deselect, so no box, no clicked corner and no
// session are left. It runs no Deselect either: the press never gets that far.
if let Some(message) = document_alert(app) {
refuse(app, message);
cancel_all(app.ctx(), CancelReason::HostChanged);
state.tool.clear();
return;
}
let selected = app.session.active().is_some_and(|st| st.doc.selection.is_some());
if selected && app.run("select.deselect", json!({})).is_err() {
cancel_all(app.ctx(), CancelReason::HostChanged);
@@ -132,6 +175,11 @@ pub fn apply(app: &mut PhotocraftApp) {
match app.run("image.perspectiveCrop", params) {
Ok(_) => cancel(app),
Err(err) => {
// A document the crop refuses (#11799) gets the alert the press gets, not just the status
// bar; the quad stays for fixing or cancelling after the document can be cropped.
if let Some(message) = error_alert(&err) {
refuse(app, message);
}
app.ui.status = err.to_string();
app.ui.status_error = true;
}
@@ -185,7 +233,7 @@ mod tests {
use craft::draw::ui::CropLength;
use craft::ui::runtime::env::UnitKind;
use egui::Modifiers;
use photocraft_doc::{Color, ColorMode, Document, SampleType, Size as DocSize};
use photocraft_doc::{Color, ColorMode, Document, Layer, LayerContent, SampleType, ShapeLayer, Size as DocSize, SmartObject, SmartSource, TextLayer};
use super::*;
use crate::canvas::testing::{ToolEvent, tool_event};
@@ -213,6 +261,131 @@ mod tests {
(size.width, size.height)
}
/// #11799: a document holding a type layer or a smart object (hidden or not), and a Bitmap
/// document, refuse the press with the reference's alert - the message and an OK button - and
/// start nothing: no quad, no clicked corner, no drag, and the document is untouched.
#[test]
fn a_press_on_a_refused_document_shows_the_alert_and_starts_nothing() {
/// The reference's two alerts, as measured.
const UNSUPPORTED: &str = "Could not use the perspective crop tool because the image contains unsupported layers types.";
const NOT_BITMAP: &str =
"Could not use the perspective crop tool because it does not work with Bitmap images (convert image to Grayscale mode to edit).";
/// A 200 x 150 RGB document with `extra` on the Background.
fn doc(mode: ColorMode, extra: Option<Layer>) -> Document {
let mut d = Document::with_background("p", DocSize::new(200, 150), mode, SampleType::U8, Color::WHITE);
if let Some(l) = extra {
d.insert_above(None, l);
}
d
}
fn text(visible: bool) -> Layer {
let mut l = Layer::new("Hello", LayerContent::Text(TextLayer { text: "Hello".into(), ..Default::default() }));
l.visible = visible;
l
}
fn smart(visible: bool) -> Layer {
let mut l = Layer::new(
"Photo",
LayerContent::Smart(SmartObject::new(SmartSource::Linked { path: "photo.psd".into() }, photocraft_geom::Affine::IDENTITY, None)),
);
l.visible = visible;
l
}
let cases = [
("visible type layer", doc(ColorMode::Rgb, Some(text(true))), UNSUPPORTED),
("hidden type layer", doc(ColorMode::Rgb, Some(text(false))), UNSUPPORTED),
("visible smart object", doc(ColorMode::Rgb, Some(smart(true))), UNSUPPORTED),
("hidden smart object", doc(ColorMode::Rgb, Some(smart(false))), UNSUPPORTED),
("Bitmap", doc(ColorMode::Bitmap, None), NOT_BITMAP),
];
for (case, document, want) in cases {
let mut s = photocraft_engine::Session::new();
s.add_document(document, None);
s.set_active(0);
let mut app = PhotocraftApp::new(s, crate::Services::default());
app.sync_views();
app.ui.tool = Tool::PerspectiveCrop;
let st = app.session.active().unwrap();
let (size, layer_kinds, steps) = (st.doc.size, kinds(&st.doc), st.history.past_len());
// The first press-and-drag: one alert with the reference's text (message and an OK
// button), and nothing started: no box, no drag, no session.
drag(&mut app, [10.0, 10.0], [120.0, 90.0]);
assert_eq!(alert_message(&app).as_deref(), Some(want), "{case}: the alert, with its text");
assert_eq!(quad(&app), None, "{case}: no quad");
assert!(!pending(&app), "{case}: no session");
// OK closes the alert: it answers with nothing but closing.
close_alerts(&mut app);
// A press after that is refused the same way: it places no corner.
drag(&mut app, [30.0, 30.0], [30.0, 30.0]);
assert_eq!(alert_message(&app).as_deref(), Some(want), "{case}: the click is refused too");
assert_eq!(app.canvas_tools.perspective.tool.placing(), 0, "{case}: no clicked corner");
let st = app.session.active().unwrap();
assert_eq!(st.doc.size, size, "{case}: canvas untouched");
assert_eq!(kinds(&st.doc), layer_kinds, "{case}: layers untouched");
assert_eq!(st.history.past_len(), steps, "{case}: no history step");
}
}
/// Every layer's kind, bottom to top.
fn kinds(doc: &Document) -> Vec<&'static str> {
doc.walk().iter().map(|(_, _, l)| l.content.kind_name()).collect()
}
/// #11874: the literal translation keys are the engine's alert texts, so an English UI shows
/// exactly what `image.perspectiveCrop` answers and the catalogs translate the right string.
#[test]
fn alert_keys_match_the_engine_texts() {
crate::i18n::with_language(crate::i18n::Lang::EN, || {
for text in [UNSUPPORTED_LAYERS_ERROR, BITMAP_MODE_ERROR] {
assert_eq!(alert_text(text), text);
}
});
}
/// The message of the open alert, if any (the host keeps one alert at a time).
fn alert_message(app: &PhotocraftApp) -> Option<String> {
use craft::ui::dialog::StackDialog;
app.framework
.dialogs
.get::<craft::ui::dialog::HostedAlert>()
.and_then(|alert| alert.json_fields())
.and_then(|fields| fields.get("message").and_then(|m| m.as_str()).map(str::to_owned))
}
/// Closes every open dialog: OK closes the alert.
fn close_alerts(app: &mut PhotocraftApp) {
let ctx = app.ctx().clone();
let ids: Vec<_> = app.framework.dialogs.stack().ids().collect();
for id in ids {
app.framework.dialogs.cancel_by_id(&ctx, id);
}
}
/// #11799: a document of only pixel, shape and fill layers takes the press as before, and a
/// commit on such a document keeps working (the refusal is about type and smart object layers
/// and the Bitmap mode alone).
#[test]
fn a_press_on_a_cropable_document_still_draws_the_quad() {
let mut d = Document::with_background("p", DocSize::new(200, 150), ColorMode::Rgb, SampleType::U8, Color::WHITE);
let path = photocraft_vector::shapes::rect(20.0, 20.0, 40.0, 30.0);
d.insert_above(None, Layer::new("Rectangle 1", LayerContent::Shape(ShapeLayer { path, ..Default::default() })));
let mut s = photocraft_engine::Session::new();
s.add_document(d, None);
s.set_active(0);
let mut app = PhotocraftApp::new(s, crate::Services::default());
app.sync_views();
app.ui.tool = Tool::PerspectiveCrop;
drag(&mut app, [20.0, 10.0], [120.0, 90.0]);
assert_eq!(quad(&app), Some([[20.0, 10.0], [120.0, 10.0], [120.0, 90.0], [20.0, 90.0]]));
assert_eq!(alert_message(&app), None, "no alert");
apply(&mut app);
assert_eq!(size(&app), (100, 80), "the quad's mean side lengths");
}
/// Apply sends `image.perspectiveCrop` with the quad drawn on the canvas and the size from the fields: typed
/// lengths at the typed resolution, empty W and H the perspective size; one undo step, and the tool is cleared.
#[test]
+7
View File
@@ -276,6 +276,13 @@ pub(crate) fn finish_stroke_with(app: &mut PhotocraftApp, tool: Tool, points: &[
app.ui.pattern_stamp_phase = r.get("phase").and_then(|v| serde_json::from_value(v.clone()).ok()).filter(|_| o.pattern_stamp_aligned);
}
Ok(_) => {}
// The Art History Brush's source refusals are alerts with OK, as the press-time ones, and
// not in the status bar as well (#12638).
Err(e) if tool == Tool::ArtHistoryBrush && e.starts_with("Could not use the art history brush because") => {
app.ui.status.clear();
app.ui.status_error = false;
let _ = crate::dialogs::alerts::alert(app, tl!(&e).to_owned());
}
Err(e) => {
app.ui.status = e;
app.ui.status_error = true;
@@ -50,7 +50,7 @@ pub(super) fn history_brush(ui: &mut egui::Ui, app: &mut PhotocraftApp) -> Optio
None
}
/// Art History Brush: Style, Area, Tolerance.
/// Art History Brush: Style, Area, Tolerance. Its alerts carry the reference's words, so it opens them itself.
pub(super) fn art_history(ui: &mut egui::Ui, app: &mut PhotocraftApp) -> Option<RangeAlert> {
let styles: Vec<Entry<String>> = [
("tightShort", tl!("Tight Short")),
@@ -69,13 +69,30 @@ pub(super) fn art_history(ui: &mut egui::Ui, app: &mut PhotocraftApp) -> Option<
Field::new(tl!("Style")).side(SideLabel::new().scrub(true)).sizing(Sizing::Content).show(ui, |ui, _| {
Select::new(tl!("Style"), Bind::bound(&mut o.art_history_style), &styles).show(ui);
});
let area = number(tl!("Area"), &mut o.art_history_area, 0.0..=100.0).show(ui).out_of_range;
let tolerance = number(tl!("Tolerance"), &mut o.art_history_tolerance, 0.0..=100.0).show(ui).out_of_range;
Divider::vertical().show(ui);
hint(ui, tl!("Stylized dabs from a history state"));
area.or(tolerance)
// Area: whole pixels 0..500, no slider; Tolerance: whole percents 0..100 with a slider. A value
// typed past either range becomes the closest one with the reference's own alert (#12630).
let area = number(tl!("Area"), &mut o.art_history_area, 0.0..=500.0).whole().unit("px").tooltip(tl!("Painting area diameter")).show(ui).out_of_range;
let tolerance = number(tl!("Tolerance"), &mut o.art_history_tolerance, 0.0..=100.0)
.whole()
.unit("%")
.popup_slider()
.tooltip(tl!("Painting tolerance"))
.show(ui)
.out_of_range;
if area.is_some() {
let _ = crate::dialogs::alerts::alert(app, tl!(ART_HISTORY_AREA_ALERT));
} else if tolerance.is_some() {
let _ = crate::dialogs::alerts::alert(app, tl!(ART_HISTORY_TOLERANCE_ALERT));
}
None
}
/// The reference's alert for an Art History Brush Area typed past 0..500 px (#12630).
pub(crate) const ART_HISTORY_AREA_ALERT: &str = "An integer between 0 pixel and 500 Pixels is required. Closest value inserted.";
/// The reference's alert for an Art History Brush Tolerance typed past 0..100 (#12630).
pub(crate) const ART_HISTORY_TOLERANCE_ALERT: &str = "An integer between 0 and 100 is required. Closest value inserted.";
/// Pattern Stamp: Aligned, Impressionist, Pattern, Scale, Angle.
pub(super) fn pattern_stamp(ui: &mut egui::Ui, app: &mut PhotocraftApp) -> Option<RangeAlert> {
let patterns: Vec<Entry<String>> = app.session.patterns.items.iter().map(|p| Entry::new(p.id.clone(), p.display_name().to_string())).collect();
+8
View File
@@ -317,6 +317,14 @@ pub(crate) fn command_states(app: &PhotocraftApp) -> Vec<(CommandRef, CommandSta
.collect()
}
/// What [`command_states`] reads: the active document and its revision (the selected slice resolves from its
/// slices), the selected slice's number and the lock.
pub(crate) fn command_states_key(app: &PhotocraftApp) -> crate::app::framework::StatesKey {
let revision = app.session.active().map_or(u64::MAX, |st| st.revision);
let selected = app.ui.slices.selected.map_or(u64::MAX, |n| n as u64);
[app.session.active_generation(), revision, selected, u64::from(app.session.file_menu.slices_locked)]
}
/// Runs a fired slice command; whether it was one.
pub(crate) fn run_fired(app: &mut PhotocraftApp, _ctx: &egui::Context, command: &CommandRef) -> bool {
let Some(command) = SliceCommand::from_ref(command) else { return false };
+332
View File
@@ -0,0 +1,332 @@
#!/usr/bin/env python3
"""Move a branch's edits of the old inline command table into the table fragments.
Before the table was split, `crates/engine/src/cmd.rs` held every core command in one `vec![...]`
inside `fn build()`. The entries now live in `crates/engine/src/cmd/table/<owner>/<menu>.rs`, and
`cmd/command_ids.txt` pins the registry order. A branch that edited the old table carries its
edits in `cmd.rs`. This script applies them to the fragments:
python3 scripts/engine_split/table_fragments.py --base <merge-base> --head <branch>
Run it in a checkout of the new main (or of the branch rebased onto it, with its `cmd.rs` hunks
for the old table dropped). Per command id, compared between BASE and HEAD:
changed the entry in its fragment is replaced by HEAD's text (if the fragment still has
BASE's text; otherwise it is reported as a CONFLICT and left alone);
added the entry goes after its predecessor's entry, in the predecessor's fragment, and its id
goes after the predecessor's id in command_ids.txt;
removed the entry and its id are deleted (if the fragment still has BASE's text).
The adjustment table and its loop (`ADJ`, between the `vec![...]` and the `v.extend(...)` list) are
three-way merged into table/image/adjustments.rs. Any other change inside `build()` (the module
table list, the test-only command) is reported as UNHANDLED: edit `SPECS` in cmd.rs by hand.
Entries are compared without comments and whitespace, so rustfmt does not matter. Names a new
entry uses from cmd.rs are added to its fragment's `use crate::cmd::{..}` list. Run
`cargo fmt --all` afterwards. Running the script twice gives the same result. CONFLICT, UNHANDLED,
UNPLACED, MISSING and DUPLICATE lines mean exit status 1; resolve those by hand.
Edits outside `build()` (imports in cmd.rs, helper fns, test modules) are not touched.
"""
import argparse, os, re, subprocess, sys, tempfile
CMD = "crates/engine/src/cmd.rs"
TABLE = "crates/engine/src/cmd/table"
IDS = "crates/engine/src/cmd/command_ids.txt"
ID_RE = re.compile(r'"([a-zA-Z]+\.[A-Za-z0-9.]+)"')
def skip(text, i):
"""Index after the comment, string or char literal starting at i, or None."""
if text.startswith("//", i):
j = text.find("\n", i)
return len(text) if j < 0 else j
m = re.match(r'r(#*)"', text[i:])
if m and (i == 0 or not (text[i - 1].isalnum() or text[i - 1] == "_")):
end = text.index('"' + m.group(1), i + len(m.group(0)))
return end + 1 + len(m.group(1))
if text[i] == '"':
i += 1
while text[i] != '"':
i += 2 if text[i] == "\\" else 1
return i + 1
if text[i] == "'":
m = re.match(r"'(\\.[^']*|[^\\'])'", text[i:])
if m:
return i + len(m.group(0))
return None
def split_entries(body):
"""The top-level comma-separated entries of a `vec![...]` body."""
entries, depth, start, i = [], 0, 0, 0
while i < len(body):
j = skip(body, i)
if j is not None:
i = j
continue
c = body[i]
if c in "([{":
depth += 1
elif c in ")]}":
depth -= 1
elif c == "," and depth == 0:
entries.append(body[start : i + 1])
start = i + 1
i += 1
if body[start:].strip():
entries.append(body[start:])
return entries
def entry_id(entry):
code = "\n".join(l for l in entry.splitlines() if not l.strip().startswith("//"))
m = ID_RE.search(code)
return m.group(1) if m else None
def git_show(ref, path):
return subprocess.run(["git", "show", f"{ref}:{path}"], capture_output=True, text=True, check=True).stdout
class Fragments:
"""Every `vec![...]` of the fragment files, with its entries."""
def __init__(self):
self.files = {}
for d, _, names in os.walk(TABLE):
for n in names:
if n.endswith(".rs") and os.path.dirname(os.path.join(d, n)) != TABLE:
p = os.path.join(d, n)
if "vec![" in open(p).read():
self.files[p] = open(p).read()
def find(self, cid):
"""(path, entry text) of the entry for a command id, or None."""
for p, t in self.files.items():
for e in self.entries(t):
if entry_id(e) == cid:
return p, e
return None
@staticmethod
def spans(t):
"""(start, end) of each vec! body in a fragment file."""
out, pos = [], 0
while True:
k = t.find("vec![", pos)
if k < 0:
return out
s, depth, i = k + 5, 1, k + 5
while depth:
j = skip(t, i)
if j is not None:
i = j
continue
depth += t[i] == "["
depth -= t[i] == "]"
i += 1
out.append((s, i - 1))
pos = i
def entries(self, t):
return [e for s, f in self.spans(t) for e in split_entries(t[s:f])]
def replace(self, path, old, new):
t = self.files[path]
assert t.count(old) == 1, (path, "entry not unique")
self.files[path] = t.replace(old, new)
def insert_after(self, path, old, new):
self.replace(path, old, old + new)
def delete(self, path, old):
self.replace(path, old, "")
def save(self):
for p, t in self.files.items():
open(p, "w").write(t)
def tidy(e):
"""Entry text as a fragment stores it: starts at its own line, ends with a comma."""
e = e.strip("\n")
return e if e.rstrip().endswith(",") else e.rstrip() + ","
def norm(e):
"""Entry text without comments and whitespace, and without trailing commas, for comparing."""
out, i = [], 0
while i < len(e):
j = skip(e, i)
if j is None:
out.append(e[i])
i += 1
elif e.startswith("//", i):
i = j
else:
out.append(e[i:j])
i = j
s = re.sub(r"\s+", "", "".join(out))
return re.sub(r",(?=[)\]}])", "", s).rstrip(",")
def words(e):
"""Identifiers an entry uses as bare names (not paths, fields or inside literals)."""
out, i = [], 0
while i < len(e):
j = skip(e, i)
if j is None:
out.append(e[i])
i += 1
else:
out.append(" ")
i = j
return set(re.findall(r"(?<![:\w.])([A-Za-z_]\w*)(?![\w:])", "".join(out)))
def cmd_imports(source):
"""Names the top-level `use` items of cmd.rs bring in (visible to its descendants)."""
names = set()
for m in re.finditer(r"^(?:pub(?:\([a-z]+\))? )?use ([^;]*);", source, re.M | re.S):
item = m.group(1)
inner = re.search(r"\{(.*)\}", item, re.S)
for n in (inner.group(1).split(",") if inner else [item]):
n = n.strip().split("::")[-1].split(" as ")[-1].strip()
if n and n != "self":
names.add(n)
return names
def build_parts(source):
"""(entries, adj_region, tail) of the old `fn build()`: the table vec, what the adjustment
table adds, and the module table list with the rest of the function."""
start = source.index("vec![", source.index("fn build()")) + len("vec![")
depth, i = 1, start
while depth:
j = skip(source, i)
if j is not None:
i = j
continue
depth += source[i] == "["
depth -= source[i] == "]"
i += 1
rest = source[i:]
rest = rest[rest.index("\n") + 1 :] # after `];`
k = rest.index(" v.extend(")
return split_entries(source[start : i - 1]), rest[:k].strip("\n") + "\n", rest[k:]
def merge_region(cur, base, head):
"""Three-way merge of text; (merged, ok)."""
with tempfile.TemporaryDirectory() as d:
paths = []
for name, text in (("cur", cur), ("base", base), ("head", head)):
p = os.path.join(d, name)
open(p, "w").write(text)
paths.append(p)
r = subprocess.run(["git", "merge-file", "-p", *paths], capture_output=True, text=True)
return r.stdout, r.returncode == 0
ADJ_FILE = os.path.join(TABLE, "image", "adjustments.rs")
ADJ_START = " let mut v = Vec::new();\n"
ADJ_END = "\n v\n}"
def add_imports(fr, path, entry, known):
"""Add names the entry uses from cmd.rs to the fragment's `use crate::cmd::{..}` list."""
t = fr.files[path]
m = re.match(r"use crate::cmd::\{(.*?)\};\n", t, re.S)
if not m:
return []
have = {x.strip() for x in m.group(1).split(",") if x.strip()}
need = sorted(n for n in words(entry) if n in known and n not in have)
if not need:
return []
allu = sorted(have | set(need), key=lambda s: (s[0].islower(), s))
fr.files[path] = "use crate::cmd::{%s};\n" % ", ".join(allu) + t[m.end() :]
return need
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--base", required=True, help="the branch's merge-base with the old main")
ap.add_argument("--head", required=True, help="the branch")
a = ap.parse_args()
base_src, head_src = git_show(a.base, CMD), git_show(a.head, CMD)
b_entries, b_adj, b_tail = build_parts(base_src)
h_entries, h_adj, h_tail = build_parts(head_src)
base = {entry_id(e): e for e in b_entries if entry_id(e)}
head_list = [e for e in h_entries if entry_id(e)]
head_ids = {entry_id(e) for e in head_list}
known = cmd_imports(head_src)
fr = Fragments()
ids = open(IDS).read().split("\n")
if ids and ids[-1] == "":
ids.pop()
report = []
for pos, e in enumerate(head_list):
cid = entry_id(e)
text = tidy(e)
here = fr.find(cid)
if here:
path, cur = here
if norm(cur) == norm(text) or (cid in base and norm(base[cid]) == norm(text)):
continue # already applied, or the branch did not touch it
if cid not in base:
report.append(f"DUPLICATE {cid}: the branch adds it, but {path} already has a different one")
elif norm(cur) != norm(base[cid]):
report.append(f"CONFLICT {cid} in {path}: the fragment differs from BASE too; merge by hand")
else:
fr.replace(path, cur, ("\n" if cur.startswith("\n") else "") + text)
report.append(f"changed {cid} in {path}")
added = add_imports(fr, path, text, known)
if added:
report.append(f"imports added to {path}: {', '.join(added)}")
continue
if cid in base:
report.append(f"MISSING {cid}: edited by the branch, but no fragment holds it")
continue
if cid in ids:
report.append(f"DUPLICATE {cid}: the branch adds it, but the registry already has that id (a module table?)")
continue
pred = next((entry_id(head_list[k]) for k in range(pos - 1, -1, -1) if fr.find(entry_id(head_list[k]))), None)
if pred is None:
report.append(f"UNPLACED {cid}: no predecessor in the fragments")
continue
path, pe = fr.find(pred)
comma = "" if pe.rstrip().endswith(",") else ","
fr.replace(path, pe, pe.rstrip() + comma + pe[len(pe.rstrip()) :] + "\n" + text)
ids.insert(ids.index(pred) + 1, cid)
report.append(f"added {cid} after {pred} in {path}")
added = add_imports(fr, path, text, known)
if added:
report.append(f"imports added to {path}: {', '.join(added)}")
for cid, e in base.items():
if cid in head_ids or not (here := fr.find(cid)):
continue
if norm(here[1]) == norm(e):
fr.delete(*here)
ids = [i for i in ids if i != cid]
report.append(f"removed {cid} from {here[0]}")
else:
report.append(f"CONFLICT {cid} in {here[0]}: the branch removes it, but the fragment differs from BASE")
# the adjustment table and its loop
if norm(h_adj) != norm(b_adj):
cur = open(ADJ_FILE).read()
i, j = cur.index(ADJ_START) + len(ADJ_START), cur.rindex(ADJ_END)
merged, ok = merge_region(cur[i:j] + "\n", b_adj, h_adj)
if not ok:
report.append(f"CONFLICT ADJ table: {ADJ_FILE} differs from BASE where the branch edits it; merge by hand")
elif merged != cur[i:j] + "\n":
open(ADJ_FILE, "w").write(cur[:i] + merged.rstrip("\n") + cur[j:])
report.append(f"changed ADJ table in {ADJ_FILE}")
if norm(h_tail) != norm(b_tail):
report.append("UNHANDLED the branch edits the end of build() (module table list or test-only command): edit SPECS in cmd.rs by hand")
fr.save()
open(IDS, "w").write("\n".join(ids) + "\n")
print("\n".join(report) or "nothing to do")
if any(r.startswith(("changed", "added", "removed")) for r in report):
print("run `cargo fmt --all` next")
return 1 if any(r.split()[0] in ("MISSING", "UNPLACED", "CONFLICT", "UNHANDLED", "DUPLICATE") for r in report) else 0
if __name__ == "__main__":
sys.exit(main())