Merge pull request #18013 from davidmann4/fix/17428-fill-script-brick-fill

Fill: Script option with Brick Fill (#17428)
This commit is contained in:
David Mann authored and GitHub committed 2026-11-30 18:25:44 +01:00
commit 3dedcc6dad
9 files changed
+1015 -6

No files matched your search

+1
View File
@@ -32,6 +32,7 @@ pub mod native_lab;
pub mod pattern;
pub mod proxy;
pub mod psblend;
pub mod scripted_pattern;
pub mod shape_split;
pub mod smart_mix;
mod uniform;
+230
View File
@@ -0,0 +1,230 @@
//! Scripted patterns: Edit › Fill › Pattern with Script on lays the chosen pattern out as separate tiles instead of a
//! plain repeat. Brick Fill is the first script; the others extend [`SCRIPTS`] and [`controls`] with their own layout.
//!
//! Every script shares the per-tile Color and Brightness randomness ([`Jitter`]): at 0 a tile keeps the pattern's
//! exact colours, above 0 each placed tile drifts by its own random amount. Areas no tile covers stay transparent.
use photocraft_geom::Rect;
use crate::pattern::{Placement, Tile};
/// The scripts in the Script list's order: (parameter value, name). The name is also the script dialog's title.
pub const SCRIPTS: [(&str, &str); 6] = [
("brickFill", "Brick Fill"),
("crossWeave", "Cross Weave"),
("placeAlongPath", "Place Along Path"),
("randomFill", "Random Fill"),
("spiral", "Spiral"),
("symmetryFill", "Symmetry Fill"),
];
/// The scripts that paint today; the rest are listed but answer "not supported yet".
pub const SUPPORTED: [&str; 1] = ["brickFill"];
/// The parameter value of a script name, matched without regard to case.
pub fn script_key(name: &str) -> Option<&'static str> {
SCRIPTS.iter().map(|(k, _)| *k).find(|k| k.eq_ignore_ascii_case(name))
}
/// One value of a script dialog: its parameter key, factory value and range.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Control {
pub key: &'static str,
pub default: f64,
pub min: f64,
pub max: f64,
/// The most digits shown after the decimal mark.
pub decimals: u32,
}
impl Control {
const fn new(key: &'static str, default: f64, min: f64, max: f64, decimals: u32) -> Control {
Control { key, default, min, max, decimals }
}
/// `v` inside the range; a non-finite value takes the factory value.
pub fn clamp(&self, v: f64) -> f64 {
if v.is_finite() { v.clamp(self.min, self.max) } else { self.default }
}
}
/// The Spacing range for a `width` x `height` pattern tile, in pixels: up to three tile widths apart, and overlapping
/// by up to the shorter side less 2 px (the measured -28 to 120 for a 40 x 30 tile). It does not change with the scale.
pub fn spacing_range(width: u32, height: u32) -> (f64, f64) {
let min = -f64::from(width.min(height).saturating_sub(2));
(min, 3.0 * f64::from(width))
}
/// The values of `script` in its dialog's order, for a `width` x `height` pattern; `None` for an unknown script or one
/// that does not paint yet.
pub fn controls(script: &str, width: u32, height: u32) -> Option<Vec<Control>> {
match script {
"brickFill" => {
let (lo, hi) = spacing_range(width, height);
Some(vec![
Control::new("patternScale", 1.0, 0.1, 1.25, 2),
Control::new("spacing", 0.0, lo, hi, 0),
Control::new("offsetBetweenRows", 50.0, -100.0, 100.0, 0),
Control::new("colorRandomness", 0.05, 0.0, 1.0, 2),
Control::new("brightnessRandomness", 0.1, 0.0, 1.0, 2),
Control::new("patternRotateAngle", 0.0, -180.0, 180.0, 0),
])
}
_ => None,
}
}
/// Per-tile colour and brightness drift, both 0..1, repeatable for one `seed`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Jitter {
pub color: f32,
pub brightness: f32,
pub seed: u64,
}
/// How far each channel moves at randomness 1: a quarter of the range, so the default 0.05 / 0.1 shift a channel by a
/// few levels (one measured tile: blue 245 instead of 255).
const JITTER_REACH: f32 = 0.25;
impl Jitter {
/// The change added to each channel of tile `(row, col)`: its own colour offsets plus one shared brightness offset.
fn offsets(&self, row: i64, col: i64) -> [f32; 3] {
if self.color <= 0.0 && self.brightness <= 0.0 {
return [0.0; 3];
}
let mut state = self.seed ^ (row as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ (col as u64).wrapping_mul(0xC2B2_AE3D_27D4_EB4F);
let mut next = || {
// splitmix64: a well-mixed value per call, in -1..1.
state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = state;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^= z >> 31;
((z >> 40) as f32 / (1u64 << 24) as f32) * 2.0 - 1.0
};
let light = next() * self.brightness * JITTER_REACH;
let mut out = [0.0; 3];
for o in &mut out {
*o = next() * self.color * JITTER_REACH + light;
}
out
}
}
/// Brick Fill: rows of whole tiles from the canvas origin, every second row shifted by a share of the tile width.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BrickFill {
/// Tile size as a fraction (0.1..1.25).
pub scale: f64,
/// Pixels between neighbouring tiles, across and down; negative overlaps them.
pub spacing: f64,
/// Shift of every second row to the left, in percent of the tile width (negative shifts right).
pub offset: f64,
/// Rotation of each tile about its centre, degrees counter-clockwise.
pub angle: f64,
pub jitter: Jitter,
}
/// Most tiles composited into one pixel, front to back: bounds the work of extreme overlaps. Only a pixel whose
/// frontmost tiles all let some of it through ever reaches it; an opaque tile ends the pixel at once.
const MAX_LAYERS: usize = 1024;
/// The x range where the convex polygon `corners` (in order) meets the line at height `y`, if it does.
fn span(corners: &[(f64, f64); 4], y: f64) -> Option<(f64, f64)> {
let mut range: Option<(f64, f64)> = None;
for i in 0..4 {
let (a, b) = (corners[i], corners[(i + 1) % 4]);
if (a.1 - y) * (b.1 - y) > 0.0 {
continue;
}
let x = if a.1 == b.1 { [a.0, b.0] } else { [a.0 + (b.0 - a.0) * (y - a.1) / (b.1 - a.1); 2] };
for x in x {
range = Some(range.map_or((x, x), |(lo, hi)| (lo.min(x), hi.max(x))));
}
}
range
}
impl BrickFill {
/// The tiles of a `width` x `height` pattern laid out over `rect` (row-major straight RGBA, transparent where no
/// tile lies). Later tiles (down, then right) lie over earlier ones where they overlap.
pub fn render(&self, tile: &Tile, width: u32, height: u32, rect: Rect) -> Vec<[f32; 4]> {
let len = rect.width() as usize * rect.height() as usize;
let mut out = vec![[0.0f32; 4]; len];
// At the f32 precision the placement maps with, so the tile bounds here are the ones it samples.
let scale = if self.scale.is_finite() && self.scale > 0.0 { f64::from(self.scale as f32) } else { 1.0 };
let (tw, th) = (f64::from(width) * scale, f64::from(height) * scale);
if len == 0 || tw <= 0.0 || th <= 0.0 {
return out;
}
let spacing = if self.spacing.is_finite() { self.spacing } else { 0.0 };
// At least a pixel between tile origins, so every layout ends.
let (pitch_x, pitch_y) = ((tw + spacing).max(1.0), (th + spacing).max(1.0));
let shift = if self.offset.is_finite() { self.offset / 100.0 * tw } else { 0.0 };
let angle = if self.angle.is_finite() { self.angle } else { 0.0 };
let (c, s) = (angle.to_radians().cos(), angle.to_radians().sin());
// The tile centres that put a pixel inside their tile form the turned tile rectangle around the pixel: its
// corners, relative to the pixel, and how far it reaches down.
let (a, b) = (tw / 2.0, th / 2.0);
let corners = [(a, b), (a, -b), (-a, -b), (-a, b)].map(|(hx, hy)| (hx * c + hy * s, -hx * s + hy * c));
let reach_y = s.abs() * a + c.abs() * b;
let placement = |row: i64, col: i64| {
let x0 = col as f64 * pitch_x - if row.rem_euclid(2) == 1 { shift } else { 0.0 };
let y0 = row as f64 * pitch_y;
let (cx, cy) = (x0 + tw / 2.0, y0 + th / 2.0);
// The corner the tile's (0, 0) lands on once it is turned about its centre (y down, counter-clockwise).
let (hx, hy) = (-tw / 2.0, -th / 2.0);
let origin = (cx + hx * c + hy * s, cy - hx * s + hy * c);
Placement::anchored(origin, true, (0.0, 0.0), scale as f32, angle as f32)
};
let mut i = 0;
for y in rect.y0..rect.y1 {
let py = f64::from(y) + 0.5;
// Rows whose tiles can reach this line, the last drawn (topmost) first.
let top_row = ((py + reach_y - th / 2.0) / pitch_y).floor() as i64;
let low_row = ((py - reach_y - th / 2.0) / pitch_y).ceil() as i64;
for x in rect.x0..rect.x1 {
let px = f64::from(x) + 0.5;
let mut acc = [0.0f32; 4];
let mut layers = 0;
'rows: for row in (low_row..=top_row).rev() {
// Only the tiles of this row whose centre lies in the turned rectangle around the pixel cover it.
let Some((lo, hi)) = span(&corners, row as f64 * pitch_y + th / 2.0 - py) else { continue };
let row_shift = if row.rem_euclid(2) == 1 { shift } else { 0.0 };
let right = ((px + hi + row_shift - tw / 2.0) / pitch_x).floor() as i64;
let left = ((px + lo + row_shift - tw / 2.0) / pitch_x).ceil() as i64;
for col in (left..=right).rev() {
if layers >= MAX_LAYERS || acc[3] >= 1.0 {
break 'rows;
}
let place = placement(row, col);
let (u, v) = place.map(px, py);
if !(0.0..f64::from(width)).contains(&u) || !(0.0..f64::from(height)).contains(&v) {
continue;
}
layers += 1;
let mut q = tile.sample_area(&place, px, py);
let d = self.jitter.offsets(row, col);
// Without a drift a tile keeps its exact colour, also a float one past 1.
for ch in 0..3 {
if d[ch] != 0.0 {
q[ch] = (q[ch] + d[ch]).clamp(0.0, 1.0);
}
}
// Front to back: what is already in front covers this tile.
let k = q[3] * (1.0 - acc[3]);
for ch in 0..3 {
acc[ch] += q[ch] * k;
}
acc[3] += k;
}
}
if acc[3] > 0.0 {
out[i] = [acc[0] / acc[3], acc[1] / acc[3], acc[2] / acc[3], acc[3].min(1.0)];
}
i += 1;
}
}
out
}
}
+46 -3
View File
@@ -135,10 +135,16 @@ pub fn fill(s: &mut Session, p: &Value) -> Result<Value> {
// Edit › Fill (#14975).
let space = photocraft_compose::pattern::PatternSpace::of_pixels(&st.doc);
let tile = photocraft_compose::pattern::Tile::new_in(&pat, space).ok_or_else(|| bad("the pattern is empty or too large to paint"))?;
// Photoshop's Fill uses the canvas origin.
let place = photocraft_compose::pattern::Placement::new(Rect::EMPTY, false, (0.0, 0.0), scale, angle);
out["pattern"] = json!(pat.id);
Source::Pixels(area, photocraft_compose::pattern::render(&tile, &place, area))
// With a script the pattern is laid out tile by tile instead of repeated.
if let Some(script) = script(p)? {
out["script"] = json!(script);
Source::Pixels(area, scripted(p, script, &tile, &pat, area)?)
} else {
// Photoshop's Fill uses the canvas origin.
let place = photocraft_compose::pattern::Placement::new(Rect::EMPTY, false, (0.0, 0.0), scale, angle);
Source::Pixels(area, photocraft_compose::pattern::render(&tile, &place, area))
}
}
"history" => {
// A History panel row `state` or a `snapshot`, else the History Brush's source.
@@ -190,6 +196,43 @@ pub fn fill(s: &mut Session, p: &Value) -> Result<Value> {
Ok(out)
}
/// The `script` param of a pattern fill: a [`SCRIPTS`](photocraft_compose::scripted_pattern::SCRIPTS) key, or none.
fn script(p: &Value) -> Result<Option<&'static str>> {
use photocraft_compose::scripted_pattern::{SCRIPTS, script_key};
match p.get("script") {
None | Some(Value::Null) => Ok(None),
Some(Value::String(name)) => {
let names = SCRIPTS.iter().map(|(k, _)| *k).collect::<Vec<_>>().join("|");
script_key(name).map(Some).ok_or_else(|| bad(format!("unknown script `{name}` ({names})")))
}
Some(v) => Err(bad(format!("`script` must be a script name, not {v}"))),
}
}
/// The scripted pattern `script` laid out over `area`, with its values from `p` (each clamped to its range, the factory
/// value when missing) and an optional whole-number `seed` for the per-tile randomness.
fn scripted(p: &Value, script: &str, tile: &photocraft_compose::pattern::Tile, pat: &photocraft_doc::pattern::Pattern, area: Rect) -> Result<Vec<[f32; 4]>> {
use photocraft_compose::scripted_pattern::{BrickFill, Jitter, controls};
let controls =
controls(script, pat.width, pat.height).ok_or_else(|| bad(format!("the `{script}` script is not supported yet; only brickFill paints today")))?;
let mut values = std::collections::HashMap::new();
for c in &controls {
let v = match p.get(c.key) {
None | Some(Value::Null) => c.default,
Some(v) => v.as_f64().filter(|v| v.is_finite()).ok_or_else(|| bad(format!("`{}` must be a number {}..{}, not {v}", c.key, c.min, c.max)))?,
};
values.insert(c.key, c.clamp(v));
}
let seed = match p.get("seed") {
None | Some(Value::Null) => 1,
Some(v) => v.as_u64().ok_or_else(|| bad(format!("`seed` must be a whole number, not {v}")))?,
};
let get = |k: &str| values.get(k).copied().unwrap_or_default();
let jitter = Jitter { color: get("colorRandomness") as f32, brightness: get("brightnessRandomness") as f32, seed };
let brick = BrickFill { scale: get("patternScale"), spacing: get("spacing"), offset: get("offsetBetweenRows"), angle: get("patternRotateAngle"), jitter };
Ok(brick.render(tile, pat.width, pat.height, area))
}
/// The reference application refuses Fill on the Quick Mask with a colour-only blend mode, Preserve Transparency or
/// History contents, and leaves the channel as it was (#17489).
fn check_quick_mask(contents: &str, mode: BlendMode, preserve: bool) -> Result<()> {
@@ -0,0 +1,227 @@
//! #17428: Edit › Fill › Pattern with Script on lays the pattern out tile by tile. `edit.fill` takes `script` and the
//! script's values; Brick Fill paints rows of whole tiles from the canvas origin with every second row shifted left by
//! the row offset (50 % of the tile width by default). An unknown script is an error, not a plain fill; the five
//! listed scripts without a layout yet answer "not supported".
use serde_json::{Value, json};
use crate::Session;
const RED: [u8; 3] = [255, 0, 0];
const BLUE: [u8; 3] = [0, 0, 255];
const GREEN: [u8; 3] = [0, 255, 0];
/// The probe tile: 40 x 30, left half red, right half blue, the bottom-right 20 x 15 quarter green, so a shift, a turn
/// and a mirror all show. Defined as "probe" from a `mode` / `depth` document.
fn define_probe(s: &mut Session, mode: &str, depth: u32) {
s.execute("file.new", json!({"width": 40, "height": 30, "mode": mode, "depth": depth, "background": "white"})).unwrap();
for (rect, color) in [([0, 0, 20, 30], "#ff0000"), ([20, 0, 20, 15], "#0000ff"), ([20, 15, 20, 15], "#00ff00")] {
s.execute("select.rect", json!({"x": rect[0], "y": rect[1], "width": rect[2], "height": rect[3]})).unwrap();
s.execute("edit.fill", json!({"contents": "color", "color": color})).unwrap();
}
s.execute("edit.definePattern", json!({"name": "probe", "rect": [0, 0, 40, 30]})).unwrap();
}
/// A 600 x 400 white document of `mode` / `depth` with an empty pixel layer on top (active), the probe defined.
fn session_in(mode: &str, depth: u32) -> Session {
let mut s = crate::session();
define_probe(&mut s, mode, depth);
s.execute("file.new", json!({"width": 600, "height": 400, "mode": mode, "depth": depth, "background": "white"})).unwrap();
s.execute("layer.new.layer", json!({})).unwrap();
s
}
fn session() -> Session {
session_in("rgb", 8)
}
/// Brick Fill with both randomness values at 0 and `extra` values on top.
fn brick(extra: Value) -> Value {
let mut p = json!({"contents": "pattern", "pattern": "probe", "script": "brickFill", "colorRandomness": 0, "brightnessRandomness": 0});
for (k, v) in extra.as_object().into_iter().flatten() {
p[k] = v.clone();
}
p
}
fn pixel(s: &Session, x: i32, y: i32) -> [f32; 4] {
let st = s.active().unwrap();
st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y)
}
fn rgb8(px: [f32; 4]) -> [u8; 3] {
[0, 1, 2].map(|c| (px[c] * 255.0).round() as u8)
}
/// The colour runs along row `y` from x 0 to 79 (two tile widths).
fn runs(s: &Session, y: i32) -> Vec<(i32, [u8; 3])> {
let mut out: Vec<(i32, [u8; 3])> = Vec::new();
for x in 0..80 {
let c = rgb8(pixel(s, x, y));
if out.last().is_none_or(|(_, last)| *last != c) {
out.push((x, c));
}
}
out
}
fn undo_label(s: &Session) -> Option<String> {
s.active().unwrap().history.undo_label().map(str::to_string)
}
#[test]
fn brick_fill_shifts_every_second_row_by_half_a_tile() {
let mut s = session();
let r = s.execute("edit.fill", brick(json!({}))).unwrap();
assert_eq!(r["script"], "brickFill");
// Row 0 starts with the tile's left edge at x 0; row 1 (y 30-59) starts 20 px further left.
assert_eq!(runs(&s, 3), vec![(0, RED), (20, BLUE), (40, RED), (60, BLUE)]);
assert_eq!(runs(&s, 33), vec![(0, BLUE), (20, RED), (40, BLUE), (60, RED)]);
// The bottom quarter shows the shift too, and row 2 lines up with row 0 again.
assert_eq!(rgb8(pixel(&s, 5, 50)), GREEN);
assert_eq!(runs(&s, 63), runs(&s, 3));
assert_eq!(undo_label(&s).as_deref(), Some("Fill"));
}
#[test]
fn brick_fill_differs_from_the_plain_pattern_fill() {
let mut plain = session();
plain.execute("edit.fill", json!({"contents": "pattern", "pattern": "probe"})).unwrap();
let mut scripted = session();
scripted.execute("edit.fill", brick(json!({}))).unwrap();
assert_eq!(runs(&plain, 3), runs(&scripted, 3), "row 0 is the plain repeat");
assert_ne!(runs(&plain, 33), runs(&scripted, 33), "row 1 is shifted only with the script");
}
#[test]
fn row_offset_spacing_and_scale_move_the_tiles() {
// No offset: every row lines up like the plain repeat.
let mut s = session();
s.execute("edit.fill", brick(json!({"offsetBetweenRows": 0}))).unwrap();
assert_eq!(runs(&s, 33), runs(&s, 3));
// Spacing leaves transparent gaps between tiles, across and down.
let mut s = session();
s.execute("edit.fill", brick(json!({"spacing": 10, "offsetBetweenRows": 0}))).unwrap();
assert_eq!(pixel(&s, 45, 3)[3], 0.0, "gap after the first tile");
assert!(pixel(&s, 55, 3)[3] > 0.99, "the second tile starts after the gap");
assert_eq!(pixel(&s, 5, 35)[3], 0.0, "gap under the first row");
// Half the scale halves the tile.
let mut s = session();
s.execute("edit.fill", brick(json!({"patternScale": 0.5, "offsetBetweenRows": 0}))).unwrap();
assert_eq!(rgb8(pixel(&s, 25, 3)), RED, "the second, half-size tile starts at x 20");
}
#[test]
fn a_turned_tile_is_no_longer_upright() {
let mut s = session();
s.execute("edit.fill", brick(json!({"patternRotateAngle": 180}))).unwrap();
// Turned half way, the tile's blue half comes first.
assert_eq!(rgb8(pixel(&s, 5, 20)), BLUE);
}
#[test]
fn randomness_varies_tiles_only_above_zero() {
let mut exact = session();
exact.execute("edit.fill", brick(json!({}))).unwrap();
let mut drift = session();
drift.execute("edit.fill", brick(json!({"colorRandomness": 0.5, "brightnessRandomness": 0.5}))).unwrap();
// At 0 every tile keeps the pattern's colours.
for x in (5..600).step_by(40) {
assert_eq!(rgb8(pixel(&exact, x, 3)), RED, "x {x}");
}
// Above 0 the tiles drift, each its own way, while one tile stays one colour.
let tiles: Vec<[u8; 3]> = (5..600).step_by(40).map(|x| rgb8(pixel(&drift, x, 3))).collect();
assert!(tiles.iter().any(|c| *c != RED), "{tiles:?}");
assert!(tiles.windows(2).any(|w| w[0] != w[1]), "tiles differ from each other: {tiles:?}");
assert_eq!(rgb8(pixel(&drift, 5, 3)), rgb8(pixel(&drift, 15, 10)), "one tile drifts as a whole");
// The factory values drift a little.
let mut default = session();
let mut p = brick(json!({}));
p.as_object_mut().unwrap().retain(|k, _| !k.ends_with("Randomness"));
default.execute("edit.fill", p).unwrap();
let tiles: Vec<[u8; 3]> = (5..600).step_by(40).map(|x| rgb8(pixel(&default, x, 3))).collect();
assert!(tiles.iter().any(|c| *c != RED), "{tiles:?}");
}
#[test]
fn the_fill_stays_in_the_selection_with_mode_and_opacity() {
let mut s = session();
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 100, "height": 50})).unwrap();
s.execute("edit.fill", brick(json!({"opacity": 50}))).unwrap();
let inside = pixel(&s, 5, 3);
assert!((inside[3] - 0.5).abs() < 0.01, "half opacity: {inside:?}");
assert_eq!(pixel(&s, 150, 3)[3], 0.0, "outside the selection");
assert_eq!(pixel(&s, 5, 80)[3], 0.0, "below the selection");
assert_eq!(undo_label(&s).as_deref(), Some("Fill"));
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(pixel(&s, 5, 3)[3], 0.0, "one history state");
}
#[test]
fn an_unknown_script_is_an_error_and_the_unbuilt_ones_are_unsupported() {
let mut s = session();
let before = undo_label(&s);
let err = s.execute("edit.fill", brick(json!({"script": "noSuchScript"}))).unwrap_err().to_string();
assert!(err.contains("unknown script"), "{err}");
for script in ["crossWeave", "placeAlongPath", "randomFill", "spiral", "symmetryFill"] {
let err = s.execute("edit.fill", brick(json!({"script": script}))).unwrap_err().to_string();
assert!(err.contains("not supported"), "{script}: {err}");
}
assert_eq!(undo_label(&s), before, "nothing was filled");
assert_eq!(pixel(&s, 5, 3)[3], 0.0);
}
#[test]
fn bad_values_are_errors_and_out_of_range_ones_are_clamped() {
let mut s = session();
for bad in [json!({"script": 3}), json!({"patternScale": "big"}), json!({"spacing": [1]}), json!({"seed": -1}), json!({"offsetBetweenRows": true})] {
assert!(s.execute("edit.fill", brick(bad.clone())).is_err(), "{bad}");
}
// A huge scale paints at the 1.25 limit; a huge negative spacing at the overlap limit, without hanging.
let mut huge = session();
huge.execute("edit.fill", brick(json!({"patternScale": 1e9, "offsetBetweenRows": 0}))).unwrap();
let mut limit = session();
limit.execute("edit.fill", brick(json!({"patternScale": 1.25, "offsetBetweenRows": 0}))).unwrap();
assert_eq!(runs(&huge, 3), runs(&limit, 3));
let mut s = session();
s.execute("edit.fill", brick(json!({"spacing": -1e12, "patternRotateAngle": 45}))).unwrap();
}
#[test]
fn brick_fill_runs_in_every_mode_and_depth() {
for (mode, depth) in [("rgb", 8), ("rgb", 16), ("rgb", 32), ("cmyk", 8), ("lab", 8), ("gray", 8), ("gray", 16)] {
let mut s = session_in(mode, depth);
s.execute("edit.fill", brick(json!({}))).unwrap_or_else(|e| panic!("{mode}/{depth}: {e}"));
// Row 1's first pixel shows the tile's right half, row 0's its left half.
let (row0, row1) = (pixel(&s, 5, 3), pixel(&s, 5, 33));
assert!(row0[3] > 0.99 && row1[3] > 0.99, "{mode}/{depth}: painted");
assert_ne!(rgb8(row0), rgb8(row1), "{mode}/{depth}: row 1 is shifted");
assert_eq!(undo_label(&s).as_deref(), Some("Fill"), "{mode}/{depth}");
}
}
#[test]
fn a_long_turned_tile_still_covers_pixels_far_from_its_centre() {
// A 4000 x 4 tile overlapping its neighbours by the most (2 px between rows) and turned 45°: about 2000 rows of
// tiles lie near each pixel, and the one that covers (1000, 200) has its centre 1000 px above it.
let mut s = crate::session();
s.execute("file.new", json!({"width": 4000, "height": 4, "background": "white"})).unwrap();
s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap();
s.execute("edit.definePattern", json!({"name": "bar", "rect": [0, 0, 4000, 4]})).unwrap();
s.execute("file.new", json!({"width": 1200, "height": 400, "background": "white"})).unwrap();
s.execute("layer.new.layer", json!({})).unwrap();
s.execute("select.rect", json!({"x": 995, "y": 195, "width": 10, "height": 10})).unwrap();
let p = json!({"pattern": "bar", "spacing": -2, "offsetBetweenRows": 0, "patternRotateAngle": 45});
s.execute("edit.fill", brick(p)).unwrap();
let px = pixel(&s, 1000, 200);
assert!(px[3] > 0.99 && rgb8(px) == RED, "{px:?}");
}
#[test]
fn a_pixel_on_the_edge_of_a_scaled_tile_is_painted() {
// At scale 1.01249999 the tile is 40.5 px wide (at the placement's f32 precision a hair wider), so the centre of
// pixel 40 lies inside the first tile and must be painted, not left in the 1 px gap.
let mut s = session();
s.execute("edit.fill", brick(json!({"patternScale": 1.012_499_99, "spacing": 1, "offsetBetweenRows": 0}))).unwrap();
assert!(pixel(&s, 40, 5)[3] > 0.0, "{:?}", pixel(&s, 40, 5));
}
+2
View File
@@ -46,6 +46,8 @@ mod eraser_gray_background_tests;
#[cfg(test)]
mod fill_quick_mask_refusals_tests;
#[cfg(test)]
mod fill_script_brick_tests;
#[cfg(test)]
mod mixer_indexed_bitmap_tests;
#[cfg(test)]
mod mixer_toggle_commands_tests;
+5 -2
View File
@@ -40,8 +40,8 @@ pub(crate) mod params {
use super::{
PhotocraftApp, alerts, brush_preset_dialog, canvas_input, channel_options_ui, color_picker_ui, color_table_ui, contact_sheet_ui, count_group_name_ui,
duplicate_layer_ui, equalize_ui, file_forms, fill_ui, filter_dialog, history_options_ui, image_processor_ui, merge_channels_ui, new_group_ui,
new_layer_ui, paragraph_text_size, smart_filter_dialog, snapshot_dialog, stack_dialog, stroke_ui,
duplicate_layer_ui, equalize_ui, file_forms, fill_script_ui, fill_ui, filter_dialog, history_options_ui, image_processor_ui, merge_channels_ui,
new_group_ui, new_layer_ui, paragraph_text_size, smart_filter_dialog, snapshot_dialog, stack_dialog, stroke_ui,
};
use crate::canvas::document_display::CanvasHost;
@@ -95,6 +95,7 @@ pub(crate) mod params {
/// Every family of parameter dialogs, first match wins; the generic filter family owns what is left.
pub(crate) const PARAM_FAMILIES: &[ParamFamily] = &[
ParamFamily { check: Some(fill_ui::check), ..ParamFamily::new(fill_ui::owns, fill_ui::run) },
ParamFamily { check: Some(fill_ui::check), footer: Some(fill_script_ui::footer), ..ParamFamily::new(fill_script_ui::owns, fill_script_ui::run) },
ParamFamily { check: Some(stroke_ui::check), ..ParamFamily::new(stroke_ui::owns, stroke_ui::run) },
ParamFamily {
check: Some(smart_filter_dialog::check),
@@ -511,6 +512,7 @@ pub(crate) const TAKERS: &[fn(&mut PhotocraftApp, &egui::Context)] = &[
file_ui::take,
format_prompts::take,
pattern_fill_ui::take,
fill_script_ui::take,
crate::workspace_ui::take,
crate::kys_import::take,
crate::prefs_ui::take_presets,
@@ -834,6 +836,7 @@ pub mod export_dialog;
pub(crate) mod fade_modes;
pub mod file_forms;
pub mod file_ui;
pub mod fill_script_ui;
pub mod fill_ui;
pub mod filter_dialog;
pub(super) mod filter_preview_ui;
@@ -0,0 +1,275 @@
//! The script dialog of Edit › Fill › Pattern with Script on (#17428): OK in Fill opens the chosen script's own dialog,
//! titled with the script's name. Every script shares one layout: a live preview of the current values with the chosen
//! pattern, a Preset row (Default, Load / Save / Delete greyed, Custom), a field and slider per value, and OK, Reset and
//! Cancel. Reset restores the values the dialog opened with; Preset › Default sets the factory values, and changing a
//! value turns Preset back to Custom. The values are remembered per script after OK. Cancel fills nothing.
use craft::ui::contract::Bind;
use craft::ui::dialog::{DialogId, StackDialog};
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult, PreviewState};
use craft::ui::runtime::env::Label;
use craft::ui::runtime::memory::{MemoryStage, SaveKey};
use craft::ui::sections::{DialogRole, FooterButton};
use craft::ui::value_drag::SliderScale;
use photocraft_compose::scripted_pattern::{BrickFill, Control, Jitter, SCRIPTS, controls};
use serde_json::{Map, Value, json};
use crate::PhotocraftApp;
use crate::dialogs::params::{captured, memory_scope, open_param};
/// The dialog key of a script is this prefix and the script's parameter value (`edit.fill.script.brickFill`).
const PREFIX: &str = "edit.fill.script.";
/// The side of the preview's sample area, in pattern pixels.
const PREVIEW: u32 = 256;
/// The Preset entries: (value, label). Load, Save and Delete are listed greyed until presets can be filed.
const PRESETS: [(&str, &str); 5] =
[("default", "Default"), ("load", "Load Preset..."), ("save", "Save Preset..."), ("delete", "Delete Preset..."), ("custom", "Custom")];
/// The dialog key of `script`.
pub(crate) fn key(script: &str) -> String {
format!("{PREFIX}{script}")
}
/// Whether the dialog `key` is a script dialog.
pub(crate) fn owns(key: &str) -> bool {
key.starts_with(PREFIX)
}
fn script_of(key: &str) -> &str {
key.strip_prefix(PREFIX).unwrap_or_default()
}
/// The label of a script value.
fn label(key: &str) -> Label {
Label::from(match key {
"patternScale" => tl!("Pattern Scale"),
"spacing" => tl!("Spacing"),
"offsetBetweenRows" => tl!("Offset between rows"),
"colorRandomness" => tl!("Color randomness"),
"brightnessRandomness" => tl!("Brightness randomness"),
"patternRotateAngle" => tl!("Pattern rotate angle"),
_ => tl!("Value"),
})
}
/// The unit shown after a value's field, if any.
fn unit(key: &str) -> Option<Label> {
match key {
"spacing" => Some(Label::from(tl!("px"))),
"offsetBetweenRows" => Some(Label::from(tl!("%"))),
"patternRotateAngle" => Some(Label::from(tl!("°"))),
_ => None,
}
}
/// The title of a script's dialog: its name.
fn title(script: &str) -> Label {
Label::from(match script {
"brickFill" => tl!("Brick Fill"),
"crossWeave" => tl!("Cross Weave"),
"placeAlongPath" => tl!("Place Along Path"),
"randomFill" => tl!("Random Fill"),
"spiral" => tl!("Spiral"),
"symmetryFill" => tl!("Symmetry Fill"),
_ => tl!("Fill"),
})
}
/// The Script list of the Fill dialog: (value, label), in the reference order.
pub(crate) fn script_options() -> Vec<(String, Label)> {
SCRIPTS.iter().map(|(k, _)| (k.to_string(), title(k))).collect()
}
fn rows(controls: &[Control]) -> Vec<Param> {
let presets = PRESETS.iter().map(|(k, l)| (k.to_string(), Label::from(tl!(l)))).collect();
let mut rows = vec![
Param::new("preset", tl!("Preset:"), ParamKind::choice(presets, Some("default".into())))
.disabled_options(["load", "save", "delete"])
.separated_at(1)
.separated_at(4),
];
for c in controls {
let mut row = Param::new(c.key, label(c.key), ParamKind::range(c.min, c.max, c.default, SliderScale::Linear)).decimals(c.decimals);
if let Some(unit) = unit(c.key) {
row = row.unit_label(unit);
}
rows.push(row);
}
rows
}
/// The factory values of `controls`, with Preset › Default.
fn factory(controls: &[Control]) -> DialogFields {
let mut f = DialogFields::new();
f.set("preset", "default");
for c in controls {
f.set(c.key, c.default);
}
f
}
/// Whether the values of `f` are the factory values.
fn is_factory(f: &DialogFields, controls: &[Control]) -> bool {
controls.iter().all(|c| f.number(c.key).is_some_and(|v| (v - c.default).abs() < 1e-9))
}
/// The values a script dialog opens with: the ones confirmed last time (each kept in its range), else the factory values.
fn opening(ctx: &egui::Context, key: &str, controls: &[Control]) -> DialogFields {
let saved: Option<DialogFields> = MemoryStage::peek_saved(ctx, &SaveKey::named(memory_scope(key)));
let mut f = factory(controls);
if let Some(saved) = saved {
if let Some(preset) = saved.text("preset").filter(|p| *p == "default" || *p == "custom") {
f.set("preset", preset);
}
for c in controls {
if let Some(v) = saved.number(c.key) {
f.set(c.key, c.clamp(v));
}
}
}
f
}
/// Opens the dialog of `script` for the Fill whose `edit.fill` params are `fill`, on the document and layer `held`
/// names. A script without a dialog yet runs the fill as it is, so the engine reports it as not supported.
pub(crate) fn open(app: &mut PhotocraftApp, script: &str, fill: Value, held: &Value) -> Option<DialogId> {
let pattern = fill.get("pattern").and_then(Value::as_str).and_then(|id| photocraft_engine::pattern_cmds::resolve(&app.session, id));
let (w, h) = pattern.as_ref().map_or((1, 1), |p| (p.width, p.height));
let controls = controls(script, w, h)?;
let key = key(script);
let fields = opening(app.ctx(), &key, &controls);
let mut opened = Map::new();
for (k, v) in fields.iter() {
opened.insert(k.to_string(), json!(v));
}
let mut captured = held.clone();
captured["fill"] = fill;
captured["opening"] = Value::Object(opened);
captured["lastPreset"] = json!(fields.text("preset").unwrap_or("custom"));
let rows = rows(&controls);
let title = title(script);
Some(open_param(app, &key.clone(), fields, captured, move |fields| {
ParamDialog::new(key.clone(), title.clone(), rows.clone())
.values(Bind::bound(fields))
.previews(true)
.alt_resets(false)
.extra_buttons(vec![("reset".to_owned(), FooterButton::new(tl!("Reset").to_string(), DialogRole::Other))])
}))
}
/// The `edit.fill` params of a confirmed script dialog: the Fill's own, the script and its values.
pub fn params(script: &str, f: &DialogFields, fill: &Value) -> Value {
let mut p = fill.as_object().cloned().unwrap_or_default();
p.insert("contents".into(), json!("pattern"));
p.insert("script".into(), json!(script));
for c in controls(script, 1, 1).unwrap_or_default() {
if let Some(v) = f.number(c.key) {
p.insert(c.key.into(), json!(v));
}
}
Value::Object(p)
}
/// OK: fill with the script's values, remembered for the next time once the fill succeeded.
pub(crate) fn run(app: &mut PhotocraftApp, ctx: &egui::Context, result: ParamResult) {
let held = captured(app, &result.key);
let p = params(script_of(&result.key), &result.fields, held.get("fill").unwrap_or(&Value::Null));
match app.run(super::fill_ui::COMMAND, p) {
Ok(_) => result.remember(ctx),
Err(e) => crate::notices::error(app, e),
}
}
/// Reset puts back the values the dialog opened with.
pub(crate) fn footer(app: &mut PhotocraftApp, _ctx: &egui::Context, id: DialogId, action: &str) {
if action != "reset" {
return;
}
let Some(key) = app.framework.dialogs.get_by_id::<HostedParamDialog>(id).and_then(|d| d.key().map(str::to_owned)) else { return };
let opening = captured(app, &key).get("opening").cloned().unwrap_or(Value::Null);
let Some(dialog) = app.framework.dialogs.get_mut_by_id::<HostedParamDialog>(id) else { return };
for (k, v) in opening.as_object().into_iter().flatten() {
match v {
Value::String(s) => dialog.set_field(k.clone(), FieldValue::Text(s.clone())),
v => {
if let Some(n) = v.as_f64() {
dialog.set_field(k.clone(), FieldValue::Number(n));
}
}
}
}
if let Some(preset) = opening.get("preset").and_then(Value::as_str)
&& let Some(held) = app.framework.captured.get_mut(&key)
{
held["lastPreset"] = json!(preset);
}
}
/// Each pass: Preset › Default sets the factory values and a changed value turns Preset to Custom; the preview follows
/// the values.
pub(crate) fn take(app: &mut PhotocraftApp, ctx: &egui::Context) {
let ids: Vec<DialogId> = app.framework.dialogs.stack().ids().collect();
for id in ids {
let Some(dialog) = app.framework.dialogs.get_by_id::<HostedParamDialog>(id) else { continue };
let Some(key) = dialog.key().filter(|k| owns(k)).map(str::to_owned) else { continue };
let fields = dialog.fields().clone();
let held = captured(app, &key);
let pattern = held["fill"].get("pattern").and_then(Value::as_str).and_then(|p| photocraft_engine::pattern_cmds::resolve(&app.session, p));
let (w, h) = pattern.as_ref().map_or((1, 1), |p| (p.width, p.height));
let Some(controls) = controls(script_of(&key), w, h) else { continue };
let preset = fields.text("preset").unwrap_or("custom").to_owned();
let last = held.get("lastPreset").and_then(Value::as_str).unwrap_or("custom").to_owned();
let Some(dialog) = app.framework.dialogs.get_mut_by_id::<HostedParamDialog>(id) else { continue };
let mut shown = fields.clone();
if preset == "default" && last != "default" {
for (k, v) in factory(&controls).iter() {
dialog.set_field(k.to_string(), v.clone());
shown.set(k.to_string(), v.clone());
}
} else if preset == "default" && !is_factory(&fields, &controls) {
dialog.set_field("preset", FieldValue::Text("custom".into()));
shown.set("preset", "custom");
}
let now = shown.text("preset").unwrap_or("custom").to_owned();
if let Some(held) = app.framework.captured.get_mut(&key) {
held["lastPreset"] = json!(now);
}
let picture = pattern.and_then(|p| preview(ctx, id, &p, &shown, &controls));
if let Some(dialog) = app.framework.dialogs.get_mut_by_id::<HostedParamDialog>(id) {
dialog.set_preview(Some(match picture {
Some(texture) => PreviewState::Ready(egui::load::SizedTexture::from_handle(&texture)),
None => PreviewState::Failed(Label::from(tl!("No pattern to preview"))),
}));
}
}
}
/// The preview of the values `f`: the script laid out over a sample area with pattern `p`, on white. The texture is
/// kept per dialog and drawn again only when the values or the pattern change.
fn preview(ctx: &egui::Context, id: DialogId, p: &photocraft_doc::Pattern, f: &DialogFields, controls: &[Control]) -> Option<egui::TextureHandle> {
let values: Vec<f64> = controls.iter().map(|c| c.clamp(f.number(c.key).unwrap_or(c.default))).collect();
let stamp = format!("{}:{values:?}", p.id);
let cache = egui::Id::unique(("fill-script-preview", id.value()));
if let Some((seen, texture)) = ctx.data(|d| d.get_temp::<(String, egui::TextureHandle)>(cache))
&& seen == stamp
{
return Some(texture);
}
let tile = photocraft_compose::pattern::Tile::new(p)?;
let get = |k: &str| controls.iter().zip(&values).find(|(c, _)| c.key == k).map_or(0.0, |(_, v)| *v);
let jitter = Jitter { color: get("colorRandomness") as f32, brightness: get("brightnessRandomness") as f32, seed: 1 };
let brick = BrickFill { scale: get("patternScale"), spacing: get("spacing"), offset: get("offsetBetweenRows"), angle: get("patternRotateAngle"), jitter };
let px = brick.render(&tile, p.width, p.height, photocraft_geom::Rect::new(0, 0, PREVIEW as i32, PREVIEW as i32));
let level = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
let rgba: Vec<u8> = px.iter().flat_map(|q| [0, 1, 2].map(|c| level(q[c] * q[3] + (1.0 - q[3]))).into_iter().chain([255])).collect();
let image = egui::ColorImage::from_rgba_unmultiplied([PREVIEW as usize, PREVIEW as usize], &rgba);
let texture = ctx.load_texture("fill-script-preview", image, egui::TextureOptions::LINEAR);
ctx.data_mut(|d| d.insert_temp(cache, (stamp, texture.clone())));
Some(texture)
}
#[cfg(test)]
#[path = "fill_script_ui_tests.rs"]
mod tests;
@@ -0,0 +1,209 @@
//! #17428: Fill › Pattern has a Script check box and list (greyed until ticked); OK with Script on opens the script's own
//! dialog and only that dialog's OK fills. Preset › Default sets the factory values, a changed value turns Preset to
//! Custom, Reset puts back the opening values, and the values are remembered per script.
use craft::ui::patterns::form_dialogs::HostedParamDialog;
use egui::accesskit::Role;
use egui::vec2;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::{Value, json};
use crate::PhotocraftApp;
use crate::smart_filter_dialog::tests::{cancel, confirm, newest, open_count, pass, set};
type H = Harness<'static, Box<PhotocraftApp>>;
fn app() -> Box<PhotocraftApp> {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 120, "height": 90, "background": "white"})).unwrap();
app.run("layer.new.layer", json!({})).unwrap();
app
}
fn harness(app: Box<PhotocraftApp>) -> H {
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(1400.0, 900.0))
.with_step_dt(1.0 / 60.0)
.build_ui_state(|ui, app: &mut Box<PhotocraftApp>| crate::dialogs::run(app, ui), app);
h.run_steps(4);
h
}
fn click(h: &mut H, at: egui::Pos2) {
h.hover_at(at);
h.run_steps(1);
for pressed in [true, false] {
h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() });
h.run_steps(1);
}
}
fn past(app: &PhotocraftApp) -> usize {
app.session.active().unwrap().history.past_len()
}
fn alpha(app: &PhotocraftApp, x: i32, y: i32) -> f32 {
let st = app.session.active().unwrap();
st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y)[3]
}
fn top_key(app: &PhotocraftApp) -> Option<String> {
app.framework.dialogs.open_dialogs().pop().and_then(|d| d.key)
}
fn field(app: &PhotocraftApp, key: &str) -> Option<f64> {
app.framework.dialogs.get_by_id::<HostedParamDialog>(newest(app))?.fields().number(key)
}
fn text(app: &PhotocraftApp, key: &str) -> Option<String> {
app.framework.dialogs.get_by_id::<HostedParamDialog>(newest(app))?.fields().text(key).map(str::to_string)
}
/// Opens Fill with Contents Pattern and Script on (`script` chosen), and presses OK.
fn fill_with_script(app: &mut PhotocraftApp, script: &str) {
let id = super::super::fill_ui::open(app);
set(app, id, "contents", json!("pattern"));
set(app, id, "script", json!(true));
set(app, id, "scriptName", json!(script));
confirm(app, id);
pass(app);
}
/// Whether the Script list is greyed, or `None` without one.
fn list_greyed(h: &H) -> Option<bool> {
h.query_all_by_role(Role::ComboBox)
.find(|n| n.accesskit_node().label().is_some_and(|l| l.trim_end_matches(':') == "Script"))
.map(|n| n.accesskit_node().is_disabled())
}
#[test]
fn ok_in_fill_opens_the_script_dialog_and_only_its_ok_fills() {
let mut app = app();
let before = past(&app);
fill_with_script(&mut app, "brickFill");
assert_eq!(open_count(&app), 1, "Fill closed, the script dialog is open");
assert_eq!(top_key(&app).as_deref(), Some("edit.fill.script.brickFill"));
assert_eq!(past(&app), before, "nothing filled yet");
assert_eq!(text(&app, "preset").as_deref(), Some("default"));
assert_eq!(field(&app, "offsetBetweenRows"), Some(50.0));
let h = harness(app);
assert!(h.query_all_by_role(Role::Dialog).any(|n| n.accesskit_node().label().as_deref() == Some("Brick Fill")), "titled with the script's name");
let mut app = h.into_state();
let top = newest(&app);
confirm(&mut app, top);
assert_eq!(open_count(&app), 0);
assert_eq!(past(&app), before + 1, "one history state");
assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Fill"));
assert!(alpha(&app, 3, 3) > 0.99);
}
#[test]
fn cancel_in_the_script_dialog_fills_nothing() {
let mut app = app();
let before = past(&app);
fill_with_script(&mut app, "brickFill");
let top = newest(&app);
cancel(&mut app, top);
assert_eq!(open_count(&app), 0);
assert_eq!(past(&app), before);
assert_eq!(alpha(&app, 3, 3), 0.0);
}
#[test]
fn preset_default_sets_the_factory_values_and_an_edit_turns_it_custom() {
let mut app = app();
fill_with_script(&mut app, "brickFill");
let id = newest(&app);
set(&mut app, id, "spacing", json!(7));
pass(&mut app);
assert_eq!(text(&app, "preset").as_deref(), Some("custom"));
set(&mut app, id, "preset", json!("default"));
pass(&mut app);
assert_eq!(field(&app, "spacing"), Some(0.0), "Default puts back the factory spacing");
assert_eq!(text(&app, "preset").as_deref(), Some("default"));
}
#[test]
fn values_are_remembered_per_script_and_reset_restores_the_opening_ones() {
let mut app = app();
fill_with_script(&mut app, "brickFill");
let id = newest(&app);
set(&mut app, id, "spacing", json!(6));
confirm(&mut app, id);
// The next Brick Fill opens on the confirmed values.
fill_with_script(&mut app, "brickFill");
assert_eq!(field(&app, "spacing"), Some(6.0));
assert_eq!(text(&app, "preset").as_deref(), Some("custom"));
let id = newest(&app);
set(&mut app, id, "spacing", json!(20));
pass(&mut app);
// Reset, clicked in the dialog, puts back the opening 6, not the factory 0.
let mut h = harness(app);
let reset = h.get_by_role_and_label(Role::Button, "Reset").rect().center();
click(&mut h, reset);
h.run_steps(3);
assert_eq!(field(h.state(), "spacing"), Some(6.0));
assert_eq!(open_count(h.state()), 1, "Reset keeps the dialog open");
}
#[test]
fn fill_lists_the_six_scripts_greyed_until_script_is_ticked() {
let mut app = app();
let id = super::super::fill_ui::open(&mut app);
set(&mut app, id, "contents", json!("pattern"));
let mut h = harness(app);
assert!(!h.get_by_role_and_label(Role::CheckBox, "Script").accesskit_node().is_disabled());
assert_eq!(list_greyed(&h), Some(true), "the list is greyed while Script is off");
set(h.state_mut(), id, "script", json!(true));
h.run_steps(3);
assert_eq!(list_greyed(&h), Some(false), "ticked, the list takes input");
}
#[test]
fn the_fill_dialog_remembers_the_last_script() {
let mut app = app();
let id = super::super::fill_ui::open(&mut app);
set(&mut app, id, "contents", json!("pattern"));
set(&mut app, id, "script", json!(true));
set(&mut app, id, "scriptName", json!("spiral"));
confirm(&mut app, id);
pass(&mut app);
// Spiral has no layout yet: the fill is refused as not supported instead of filling.
assert_eq!(alpha(&app, 3, 3), 0.0);
while open_count(&app) > 0 {
let top = newest(&app);
cancel(&mut app, top);
}
let id = super::super::fill_ui::open(&mut app);
let fields = app.framework.dialogs.get_by_id::<HostedParamDialog>(id).unwrap().fields().clone();
assert_eq!(fields.text("scriptName"), Some("spiral"));
}
#[test]
fn a_typed_value_past_the_range_is_clamped_with_the_range_alert() {
let mut app = app();
fill_with_script(&mut app, "brickFill");
let mut h = harness(app);
let at = h
.query_all_by_role(Role::SpinButton)
.find(|n| n.accesskit_node().label().is_some_and(|l| l.starts_with("Pattern Scale")))
.expect("the Pattern Scale field")
.rect()
.center();
click(&mut h, at);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.event(egui::Event::Text("5".into()));
h.run_steps(1);
h.key_press(egui::Key::Tab);
h.run_steps(4);
let dialogs = h.state().framework.dialogs.open_dialogs();
let message =
dialogs.iter().find(|d| d.key.as_deref() == Some("alert")).and_then(|d| d.fields.as_ref()?.get("message").and_then(Value::as_str).map(str::to_string));
assert!(message.as_deref().is_some_and(|m| m.contains("Closest value inserted")), "{message:?}");
let script = dialogs.iter().find(|d| d.key.as_deref() == Some("edit.fill.script.brickFill")).map(|d| d.id).unwrap();
assert_eq!(h.state().framework.dialogs.get_by_id::<HostedParamDialog>(script).unwrap().fields().number("patternScale"), Some(1.25));
}
+20 -1
View File
@@ -69,6 +69,13 @@ fn rows(app: &PhotocraftApp, foreground: [f32; 3], first_pattern: Option<String>
contents,
Param::new("color", tl!("Color:"), ParamKind::color(Some(foreground))).visible_when("contents", "color"),
Param::new("pattern", tl!("Custom Pattern:"), ParamKind::pattern(first_pattern)).visible_when("contents", "pattern"),
// Script lays the pattern out tile by tile in the chosen script's own dialog, opened by OK (#17428).
Param::new("script", tl!("Script"), ParamKind::bool(false)).visible_when("contents", "pattern"),
Param::new("scriptName", tl!("Script"), ParamKind::choice(super::fill_script_ui::script_options(), Some("brickFill".into())))
.visible_when("contents", "pattern")
.enabled_when("script", true)
.hide_caption()
.beside_previous(),
Param::new("colorAdaptation", tl!("Color Adaptation"), ParamKind::bool(true)).visible_when("contents", "contentAware"),
];
rows.extend(blending_rows(app, preserve));
@@ -145,6 +152,9 @@ pub fn params(f: &DialogFields, held: &Value) -> Value {
if let Some(id) = f.text("pattern") {
p.insert("pattern".into(), json!(id));
}
if f.bool("script") == Some(true) {
p.insert("script".into(), json!(f.text("scriptName").unwrap_or("brickFill")));
}
}
"contentAware" => {
if let Some(on) = f.bool("colorAdaptation") {
@@ -177,7 +187,16 @@ pub(crate) fn check(app: &mut PhotocraftApp, result: &ParamResult) -> Result<(),
/// Fill with the confirmed choices; they are remembered only when the fill succeeded.
pub(crate) fn run(app: &mut PhotocraftApp, ctx: &egui::Context, result: ParamResult) {
let captured = captured(app, &result.key);
match app.run(COMMAND, params(&result.fields, &captured)) {
let p = params(&result.fields, &captured);
// With Script on, OK opens the script's dialog, whose OK fills; Cancel there fills nothing. The choice of script is
// remembered either way, as the reference application reopens on the last script.
if let Some(script) = p.get("script").and_then(Value::as_str).map(str::to_owned) {
remember_blending(ctx, &result);
if super::fill_script_ui::open(app, &script, p.clone(), &captured).is_some() {
return;
}
}
match app.run(COMMAND, p) {
Ok(_) => {
remember_blending(ctx, &result);
// The framework remembers visible parameter rows only; keep their ink companion in the same saved tier.