Pattern Stamp: grey Behind in the options bar on the Background; Impressionist keeps its pixels (#12879)

- The options bar's Mode dropdown greys Behind when the Background is the
  active layer, as the Shift+right-click menu does: the entry is drawn
  disabled, a click on it picks nothing, and the wheel and the keys step
  past it. On a pixel layer it is enabled. Only the Pattern Stamp's
  dropdown uses the new greyed-option variant of the dropdown widget.
- Behind with Impressionist was not measured, so an Impressionist stroke
  again gives exactly the pixels it gives in Normal, committed and live,
  when Behind is picked. The per-dab Behind code is removed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
ljkxandClaude Fable 5.2 committed 2026-11-10 23:59:10 +01:00
1 parent 8228c3649c
commit 5d6a491060
9 files changed
+229 -93

No files matched your search

@@ -5,7 +5,9 @@
//! with a seeded RNG so a replay of the same points is identical. //! with a seeded RNG so a replay of the same points is identical.
//! //!
//! `"mode": "behind"` is the painting-only Behind mode, as the Brush's: the pattern goes beneath //! `"mode": "behind"` is the painting-only Behind mode, as the Brush's: the pattern goes beneath
//! the layer's pixels, so it shows only where the layer is transparent (#12879). //! the layer's pixels, so it shows only where the layer is transparent (#12879). Behind with
//! Impressionist was not measured: those strokes lay their dabs over the pixels in Normal, as
//! they did before Behind existed.
use photocraft_color::{BlendMode, PixelFormat}; use photocraft_color::{BlendMode, PixelFormat};
use photocraft_compose::pattern::{Placement, Tile, render}; use photocraft_compose::pattern::{Placement, Tile, render};
@@ -33,7 +35,8 @@ pub(super) struct Setup {
pub(super) stroke: Stroke, pub(super) stroke: Stroke,
pub(super) id: Option<LayerId>, pub(super) id: Option<LayerId>,
pub(super) mode: BlendMode, pub(super) mode: BlendMode,
/// Behind: paint beneath the layer's pixels (`mode` is then Normal). /// Behind: paint beneath the layer's pixels (`mode` is then Normal). Aligned strokes only:
/// Impressionist dabs are laid in `mode`.
pub(super) behind: bool, pub(super) behind: bool,
aligned: bool, aligned: bool,
pub(super) impressionist: bool, pub(super) impressionist: bool,
@@ -79,30 +82,14 @@ impl Setup {
placement(self.phase, self.scale, self.angle) placement(self.phase, self.scale, self.angle)
} }
/// One Impressionist dab's edit of a working copy in `fmt`. With Behind, `lock` is the /// One Impressionist dab's edit of a working copy in `fmt`.
/// target's transparency lock: nothing can go beneath locked pixels. fn impressionist_effect(&self, fmt: PixelFormat) -> super::DabEffect {
fn impressionist_effect(&self, fmt: PixelFormat, lock: bool) -> super::DabEffect { let (tile, phase, scale, angle, seed, mode) = (self.tile.clone(), self.phase, self.scale, self.angle, self.seed, self.mode);
let (tile, phase, scale, angle, seed) = (self.tile.clone(), self.phase, self.scale, self.angle, self.seed);
let (tw, th) = (self.pat.width as f32 * scale, self.pat.height as f32 * scale); let (tw, th) = (self.pat.width as f32 * scale, self.pat.height as f32 * scale);
let lay = match (self.behind, alpha_index(&fmt)) { Box::new(move |work, fp| stamp_dab(work, &fmt, &tile, fp, phase, scale, angle, seed, tw, th, mode))
(false, _) => Lay::Over(self.mode),
(true, Some(a)) if !lock => Lay::Behind(a),
// No transparency to paint into (the Background, a mask or channel, a locked layer).
(true, _) => return Box::new(|_, _| {}),
};
Box::new(move |work, fp| stamp_dab(work, &fmt, &tile, fp, phase, scale, angle, seed, tw, th, lay))
} }
} }
/// How one Impressionist dab meets the working pixels.
#[derive(Clone, Copy)]
enum Lay {
/// Over them, in this blend mode.
Over(BlendMode),
/// Beneath them; the alpha channel's index.
Behind(usize),
}
/// `src` beneath `dst` at coverage `k`, in native channels with alpha at `a`: the Brush's Behind. /// `src` beneath `dst` at coverage `k`, in native channels with alpha at `a`: the Brush's Behind.
/// Opaque pixels are unchanged; partly transparent ones keep their colour's share. /// Opaque pixels are unchanged; partly transparent ones keep their colour's share.
fn under_native(a: usize, dst: &mut [f32], src: &[f32], k: f32) { fn under_native(a: usize, dst: &mut [f32], src: &[f32], k: f32) {
@@ -175,7 +162,7 @@ pub(super) fn run(s: &mut Session, p: &Value) -> Result<Value> {
let sel = pre.selection.as_ref(); let sel = pre.selection.as_ref();
if st.impressionist { if st.impressionist {
// Halo is the dab footprint only: Impressionist jitters phase, it does not blur. // Halo is the dab footprint only: Impressionist jitters phase, it does not blur.
let effect = st.impressionist_effect(surf.format(), lock); let effect = st.impressionist_effect(surf.format());
Ok(apply_dab_stroke(surf, &st.stroke, sel, lock, 0, effect)) Ok(apply_dab_stroke(surf, &st.stroke, sel, lock, 0, effect))
} else { } else {
paint_aligned(surf, &st, sel, lock, CMD) paint_aligned(surf, &st, sel, lock, CMD)
@@ -202,9 +189,7 @@ pub fn live_impressionist(s: &Session, p: &Value) -> Result<super::LiveDab> {
} }
let (stroke, id) = (st.stroke.clone(), st.id); let (stroke, id) = (st.stroke.clone(), st.id);
let doc = (*s.active().ok_or(crate::EngineError::NoDocument)?.doc).clone(); let doc = (*s.active().ok_or(crate::EngineError::NoDocument)?.doc).clone();
// Behind paints nothing beneath locked pixels, as the commit. super::LiveDab::with_effect_on(doc, CMD, p, stroke, id, 0, |pre| st.impressionist_effect(pre.format()))?.with_tail_preview()
let lock = st.behind && crate::channel_cmds::target_surface(&mut doc.clone(), id, p)?.1;
super::LiveDab::with_effect_on(doc, CMD, p, stroke, id, 0, |pre| st.impressionist_effect(pre.format(), lock))?.with_tail_preview()
} }
/// The pattern under destination `rect` in `fmt` (native channels): what an aligned stroke paints /// The pattern under destination `rect` in `fmt` (native channels): what an aligned stroke paints
@@ -315,7 +300,7 @@ fn stamp_dab(
seed: u64, seed: u64,
tw: f32, tw: f32,
th: f32, th: f32,
lay: Lay, mode: BlendMode,
) { ) {
let r = fp.rect.intersect(&work.rect); let r = fp.rect.intersect(&work.rect);
if r.is_empty() { if r.is_empty() {
@@ -340,24 +325,16 @@ fn stamp_dab(
let Some(px) = rgba.get(oy.saturating_mul(rw).saturating_add(ox)) else { continue }; let Some(px) = rgba.get(oy.saturating_mul(rw).saturating_add(ox)) else { continue };
from_rgba_into(fmt, *px, &mut enc); from_rgba_into(fmt, *px, &mut enc);
let dst = work.px_mut(x, y); let dst = work.px_mut(x, y);
match lay { if mode == BlendMode::Normal {
Lay::Behind(a) => { if let Some(src) = enc.get(..n) {
if let Some(src) = enc.get(..n) { over_native(fmt, dst, src, k, false);
under_native(a, dst, src, k);
}
} }
Lay::Over(BlendMode::Normal) => { } else {
if let Some(src) = enc.get(..n) { let d = to_rgba(fmt, dst);
over_native(fmt, dst, src, k, false); let o = photocraft_color::blend::composite(mode, d, *px, k);
} from_rgba_into(fmt, o, &mut enc);
} if let Some(src) = enc.get(..n) {
Lay::Over(mode) => { dst.copy_from_slice(src);
let d = to_rgba(fmt, dst);
let o = photocraft_color::blend::composite(mode, d, *px, k);
from_rgba_into(fmt, o, &mut enc);
if let Some(src) = enc.get(..n) {
dst.copy_from_slice(src);
}
} }
} }
} }
@@ -1,7 +1,8 @@
//! #12879: the Pattern Stamp's Behind mode (`"mode": "behind"`). The pattern goes beneath the //! #12879: the Pattern Stamp's Behind mode (`"mode": "behind"`). The pattern goes beneath the
//! layer's pixels: it shows where the layer is transparent and leaves existing pixels alone, //! layer's pixels: it shows where the layer is transparent and leaves existing pixels alone,
//! Aligned on and off, as the Brush's Behind does. The live stroke shows what the commit paints, //! Aligned on and off, as the Brush's Behind does. The live stroke shows what the commit paints,
//! and every other mode paints what it painted before. //! and every other mode paints what it painted before. Behind with Impressionist was not
//! measured, so an Impressionist stroke paints what it paints in Normal.
use photocraft_paint::StrokePoint; use photocraft_paint::StrokePoint;
use serde_json::json; use serde_json::json;
@@ -153,16 +154,10 @@ fn behind_paints_nothing_without_transparency_to_paint_into() {
}) })
.unwrap(); .unwrap();
let before = layer(&s); let before = layer(&s);
for impressionist in [false, true] { stamp(&mut s, json!({"mode": "behind"}));
stamp(&mut s, json!({"mode": "behind", "impressionist": impressionist})); assert_eq!(layer(&s), before, "locked transparency");
assert_eq!(layer(&s), before, "locked transparency, impressionist {impressionist}"); let live = super::super::LiveRetouch::begin(&s, "paint.patternStamp", &stroke(json!({"mode": "behind"}))).unwrap().doc.clone();
let live = if impressionist { assert_eq!(pixels(&live, &s), before, "the live stroke too");
live_impressionist(&s, &stroke(json!({"mode": "behind", "impressionist": true}))).unwrap().doc.clone()
} else {
super::super::LiveRetouch::begin(&s, "paint.patternStamp", &stroke(json!({"mode": "behind"}))).unwrap().doc.clone()
};
assert_eq!(pixels(&live, &s), before, "the live stroke too, impressionist {impressionist}");
}
// The Background has no transparency. // The Background has no transparency.
let mut s = Session::new(); let mut s = Session::new();
s.execute("file.new", json!({"width": W, "height": H})).unwrap(); s.execute("file.new", json!({"width": W, "height": H})).unwrap();
@@ -171,54 +166,63 @@ fn behind_paints_nothing_without_transparency_to_paint_into() {
assert_eq!(layer(&s), before, "the Background"); assert_eq!(layer(&s), before, "the Background");
} }
/// Impressionist dabs go beneath the pixels too. /// Behind with Impressionist was not measured: the stroke gives the pixels it gives in Normal,
/// committed and live, on a half-filled layer and with transparency locked.
#[test] #[test]
fn behind_with_impressionist_leaves_existing_pixels_alone() { fn impressionist_paints_as_in_normal_when_behind_is_picked() {
let all = [[12.0, 24.0], [30.0, 20.0], [40.0, 28.0], [52.0, 24.0]];
let opts = |v: &[[f64; 2]], mode: &str| json!({"points": v, "size": 14, "hardness": 40, "opacity": 70, "pattern": "Bricks", "impressionist": true, "mode": mode, "seed": 11});
for depth in [8, 16] { for depth in [8, 16] {
let mut s = session(depth, half); for lock in [false, true] {
let before = layer(&s); let run = |mode: &str| {
stamp(&mut s, json!({"mode": "behind", "impressionist": true, "pattern": "Bricks"})); let mut s = session(depth, half);
let got = layer(&s); if lock {
let mut painted = 0; s.edit("lock", |doc, active| {
for y in 0..H { doc.layer_mut(active.unwrap()).unwrap().locks.transparency = true;
for x in 0..W { Ok(())
if x < W / 2 { })
assert_eq!(at(&got, x, y), at(&before, x, y), "{depth}-bit ({x}, {y})"); .unwrap();
} else {
painted += usize::from(at(&got, x, y)[3] > 0.99);
} }
} let before = layer(&s);
let mut live = live_impressionist(&s, &opts(&all[..1], mode)).unwrap();
live.push(&all[1..].iter().map(|q| StrokePoint::new(q[0], q[1], 1.0)).collect::<Vec<_>>()).unwrap();
let shown = pixels(&live.doc, &s);
s.execute("paint.patternStamp", opts(&all, mode)).unwrap();
(before, shown, layer(&s))
};
let (before, live_behind, behind) = run("behind");
let (_, live_normal, normal) = run("normal");
let tag = format!("{depth}-bit lock {lock}");
assert_eq!(behind, normal, "{tag}: the committed stroke");
assert_eq!(live_behind, live_normal, "{tag}: the live stroke");
assert_eq!(live_behind, behind, "{tag}: live is the commit");
// As in Normal, the dabs go over the filled half.
assert!((0..W / 2).any(|x| at(&behind, x, 24) != at(&before, x, 24)), "{tag}: painted over the pixels");
} }
assert!(painted > 200, "{depth}-bit: {painted} px");
} }
} }
/// The live stroke, fed point by point, shows what the commit paints. /// The live aligned stroke, fed point by point, shows what the commit paints.
#[test] #[test]
fn the_live_behind_stroke_matches_the_commit() { fn the_live_behind_stroke_matches_the_commit() {
let all = [[12.0, 24.0], [30.0, 20.0], [40.0, 28.0], [52.0, 24.0]]; let all = [[12.0, 24.0], [30.0, 20.0], [40.0, 28.0], [52.0, 24.0]];
let pts = |v: &[[f64; 2]]| v.iter().map(|q| StrokePoint::new(q[0], q[1], 1.0)).collect::<Vec<_>>(); let pts = |v: &[[f64; 2]]| v.iter().map(|q| StrokePoint::new(q[0], q[1], 1.0)).collect::<Vec<_>>();
for depth in [8, 16] { for depth in [8, 16] {
for (impressionist, aligned) in [(false, true), (false, false), (true, true)] { for aligned in [true, false] {
let mut s = session(depth, |x, y| if x < W / 2 { RED } else { [0.2, 0.4, 0.9, 0.25 * ((x + y) % 4) as f32] }); let mut s = session(depth, |x, y| if x < W / 2 { RED } else { [0.2, 0.4, 0.9, 0.25 * ((x + y) % 4) as f32] });
let before = layer(&s); let before = layer(&s);
let opts = |v: &[[f64; 2]]| { let opts = |v: &[[f64; 2]]| {
json!({"points": v, "size": 14, "hardness": 40, "opacity": 70, "pattern": "Checkerboard", "scale": 150, "angle": 20, json!({"points": v, "size": 14, "hardness": 40, "opacity": 70, "pattern": "Checkerboard", "scale": 150, "angle": 20,
"aligned": aligned, "impressionist": impressionist, "mode": "behind", "seed": 11}) "aligned": aligned, "mode": "behind", "seed": 11})
}; };
let shown = if impressionist { let shown = {
let mut live = live_impressionist(&s, &opts(&all[..1])).unwrap();
live.push(&pts(&all[1..3])).unwrap();
live.push(&pts(&all[3..])).unwrap();
live.doc.clone()
} else {
let mut live = super::super::LiveRetouch::begin(&s, "paint.patternStamp", &opts(&all[..1])).unwrap(); let mut live = super::super::LiveRetouch::begin(&s, "paint.patternStamp", &opts(&all[..1])).unwrap();
live.push(&pts(&all[1..3])).unwrap(); live.push(&pts(&all[1..3])).unwrap();
live.push(&pts(&all[3..])).unwrap(); live.push(&pts(&all[3..])).unwrap();
live.doc.clone() live.doc.clone()
}; };
s.execute("paint.patternStamp", opts(&all)).unwrap(); s.execute("paint.patternStamp", opts(&all)).unwrap();
let tag = format!("{depth}-bit impressionist {impressionist} aligned {aligned}"); let tag = format!("{depth}-bit aligned {aligned}");
let committed = layer(&s); let committed = layer(&s);
assert_eq!(pixels(&shown, &s), committed, "{tag}"); assert_eq!(pixels(&shown, &s), committed, "{tag}");
assert_ne!(committed, before, "{tag}: the stroke painted"); assert_ne!(committed, before, "{tag}: the stroke painted");
+15
View File
@@ -73,6 +73,21 @@ pub(crate) fn pattern_stamp_choices() -> Vec<((Option<BlendMode>, bool), &'stati
choices().into_iter().filter(|c| c.0 != (None, false)).collect() choices().into_iter().filter(|c| c.0 != (None, false)).collect()
} }
/// What a pick in the Pattern Stamp's Mode dropdown sets, from `from` to `to` (both `(mode,
/// behind)` of [`pattern_stamp_choices`]). With Behind greyed (`behind_enabled` false, the
/// Background), a wheel notch or a key that lands on Behind steps on to the next mode the same
/// way, so the greyed entry is never picked.
pub(crate) fn pattern_stamp_pick(from: (Option<BlendMode>, bool), to: (Option<BlendMode>, bool), behind_enabled: bool) -> (Option<BlendMode>, bool) {
if behind_enabled || !to.1 {
return to;
}
let list = pattern_stamp_choices();
let at = |m: (Option<BlendMode>, bool)| list.iter().position(|c| c.0 == m);
let (Some(a), Some(b)) = (at(from), at(to)) else { return from };
let next = if a > b { b.checked_sub(1) } else { b.checked_add(1) };
next.and_then(|i| list.get(i)).map_or(from, |c| c.0)
}
/// The blend modes in their menu groups (a separator before Darken, Lighten, Overlay, Difference /// The blend modes in their menu groups (a separator before Darken, Lighten, Overlay, Difference
/// and Hue), with Behind and/or Clear after Dissolve. /// and Hue), with Behind and/or Clear after Dissolve.
fn blend_items(behind: bool, clear: bool) -> Vec<Item> { fn blend_items(behind: bool, clear: bool) -> Vec<Item> {
@@ -105,10 +105,13 @@ fn retouch_tools_have_a_mode_dropdown() {
} }
/// The Pattern Stamp's Mode dropdown has Behind after Dissolve and no Clear (#12879): the wheel /// The Pattern Stamp's Mode dropdown has Behind after Dissolve and no Clear (#12879): the wheel
/// steps Normal, Dissolve, Behind, Darken, and stepping on leaves Behind. /// steps Normal, Dissolve, Behind, Darken, and stepping on leaves Behind. On a pixel layer: on the
/// Background Behind is greyed and the wheel passes it.
#[test] #[test]
fn the_pattern_stamp_mode_dropdown_has_behind() { fn the_pattern_stamp_mode_dropdown_has_behind() {
let mut h = harness(Tool::PatternStamp); let mut h = harness(Tool::PatternStamp);
h.state_mut().run("layer.new.layer", json!({})).unwrap();
h.run_steps(4);
let at = mode_dropdown(&h).center(); let at = mode_dropdown(&h).center();
wheel(&mut h, at, -1.0); wheel(&mut h, at, -1.0);
assert_eq!(brush_mode(&h), BlendMode::Dissolve); assert_eq!(brush_mode(&h), BlendMode::Dissolve);
+8 -3
View File
@@ -38,10 +38,15 @@ pub(super) fn paint_mode_dropdown(ui: &mut egui::Ui, id: &str, b: &mut photocraf
/// The Pattern Stamp's Mode dropdown: the blend modes with Behind after Dissolve and no Clear, as /// The Pattern Stamp's Mode dropdown: the blend modes with Behind after Dissolve and no Clear, as
/// the reference application lists them (#12879). Behind is the tool's own brush's, as its mode; /// the reference application lists them (#12879). Behind is the tool's own brush's, as its mode;
/// picking another mode leaves it. The wheel steps it as it steps the other Mode dropdowns. /// picking another mode leaves it. The wheel steps it as it steps the other Mode dropdowns.
pub(super) fn pattern_stamp_mode_dropdown(ui: &mut egui::Ui, id: &str, b: &mut photocraft_engine::BrushSettings) { /// Without `behind_enabled` (the Background is the active layer) Behind is greyed, as in the
/// Shift+right-click menu, and the wheel and the keys step past it.
pub(super) fn pattern_stamp_mode_dropdown(ui: &mut egui::Ui, id: &str, b: &mut photocraft_engine::BrushSettings, behind_enabled: bool) {
let opts = crate::brush_mode_menu::pattern_stamp_choices(); let opts = crate::brush_mode_menu::pattern_stamp_choices();
let mut mode = if b.behind { (None, true) } else { (Some(b.mode), false) }; let before = if b.behind { (None, true) } else { (Some(b.mode), false) };
if !widgets::dropdown_wheel_grouped(ui, id, tl!("Mode"), &mut mode, &opts, 96.0, |m| m.0.is_some_and(starts_blend_group)).0.is_empty() { let mut mode = before;
let groups = |m: &(Option<BlendMode>, bool)| m.0.is_some_and(starts_blend_group);
if !widgets::dropdown_wheel_grouped_enabled(ui, id, tl!("Mode"), &mut mode, &opts, 96.0, groups, |m| behind_enabled || !m.1).0.is_empty() {
let mode = crate::brush_mode_menu::pattern_stamp_pick(before, mode, behind_enabled);
b.behind = mode.1; b.behind = mode.1;
b.mode = mode.0.unwrap_or(BlendMode::Normal); b.mode = mode.0.unwrap_or(BlendMode::Normal);
} }
+3 -2
View File
@@ -139,9 +139,10 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let mut brush = before.clone(); let mut brush = before.clone();
// Mode is the tool's own brush's, kept per tool like its size. // Mode is the tool's own brush's, kept per tool like its size.
if tool == Tool::PatternStamp { if tool == Tool::PatternStamp {
// Its list has Behind (#12879). // Its list has Behind, greyed on the Background (#12879).
opt_label(ui, tl!("Mode")); opt_label(ui, tl!("Mode"));
super::brush_controls::pattern_stamp_mode_dropdown(ui, "retouch-mode", &mut brush); let behind = crate::brush_mode_menu::enabled(app, crate::brush_mode_menu::Item::Behind);
super::brush_controls::pattern_stamp_mode_dropdown(ui, "retouch-mode", &mut brush, behind);
} else if let Some(modes) = crate::blend_keys::tool_modes(tool) { } else if let Some(modes) = crate::blend_keys::tool_modes(tool) {
opt_label(ui, tl!("Mode")); opt_label(ui, tl!("Mode"));
if let Some(Some(m)) = if let Some(Some(m)) =
@@ -7,7 +7,7 @@ use egui::{Context, Event, Key, Modifiers, RawInput};
use photocraft_doc::BlendMode; use photocraft_doc::BlendMode;
use serde_json::{Value, json}; use serde_json::{Value, json};
use super::{Item, current, enabled, engine_call, items, labels, pattern_stamp_choices}; use super::{Item, current, enabled, engine_call, items, labels, pattern_stamp_choices, pattern_stamp_pick};
use crate::PhotocraftApp; use crate::PhotocraftApp;
use crate::control::{ControlRequest, Outcome, handle}; use crate::control::{ControlRequest, Outcome, handle};
use crate::state::Tool; use crate::state::Tool;
@@ -233,3 +233,106 @@ fn a_behind_stroke_paints_only_the_transparent_half() {
assert_ne!(pixel(&app, 16, 32), red, "aligned {aligned}: Normal paints over"); assert_ne!(pixel(&app, 16, 32), red, "aligned {aligned}: Normal paints over");
} }
} }
/// The whole app drawn, with the Pattern Stamp on a new document; with `layer`, on a transparent
/// layer above the Background.
fn harness(layer: bool) -> egui_kittest::Harness<'static, PhotocraftApp> {
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(move |cc| {
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 64, "height": 48})).unwrap();
if layer {
app.run("layer.new.layer", json!({})).unwrap();
}
app.ui.tool = Tool::PatternStamp;
app
});
h.run_steps(8);
h
}
/// The options bar's Mode dropdown: the highest one showing `Normal` (the Layers panel's is lower).
fn mode_dropdown(h: &egui_kittest::Harness<'_, PhotocraftApp>) -> egui::Rect {
use egui_kittest::kittest::Queryable;
h.query_all_by_role(egui::accesskit::Role::ComboBox)
.filter(|n| n.value().as_deref() == Some("Normal"))
.map(|n| n.rect())
.min_by(|a, b| a.top().total_cmp(&b.top()))
.unwrap()
}
/// Opens the options bar's Mode dropdown with a click.
fn open_dropdown(h: &mut egui_kittest::Harness<'_, PhotocraftApp>) {
use egui_kittest::kittest::Queryable;
let top = mode_dropdown(h).top();
h.query_all_by_role(egui::accesskit::Role::ComboBox).find(|n| n.value().as_deref() == Some("Normal") && n.rect().top() == top).unwrap().click();
h.run_steps(4);
}
/// One wheel notch down (the next mode) over the point `at`.
fn wheel_down(h: &mut egui_kittest::Harness<'_, PhotocraftApp>, at: egui::Pos2) {
h.hover_at(at);
h.run_steps(1);
h.event(Event::MouseWheel {
source: egui::MouseWheelSource::Unknown,
unit: egui::MouseWheelUnit::Line,
delta: egui::vec2(0.0, -1.0),
phase: egui::TouchPhase::Move,
modifiers: Default::default(),
});
h.run_steps(3);
}
/// On the Background the options bar's dropdown greys Behind: the row is disabled, a click on it
/// picks nothing, and the wheel steps from Dissolve straight to Darken.
#[test]
fn the_options_bar_dropdown_greys_behind_on_the_background() {
use egui_kittest::kittest::{NodeT, Queryable};
let mut h = harness(false);
let at = mode_dropdown(&h).center();
open_dropdown(&mut h);
assert!(h.get_by_label("Behind").accesskit_node().is_disabled(), "Behind is greyed");
assert!(!h.get_by_label("Dissolve").accesskit_node().is_disabled());
assert!(!h.get_by_label("Darken").accesskit_node().is_disabled());
let n = h.state().session.journal.len();
h.get_by_label("Behind").click();
h.run_steps(4);
assert_eq!(h.state().session.journal.len(), n, "a greyed entry picks nothing");
assert!(!h.state().session.tools.brush.behind);
assert_eq!(h.state().session.tools.brush.mode, BlendMode::Normal);
// The wheel passes it.
let mut h = harness(false);
wheel_down(&mut h, at);
assert_eq!(h.state().session.tools.brush.mode, BlendMode::Dissolve);
wheel_down(&mut h, at);
assert!(!h.state().session.tools.brush.behind, "the wheel steps past the greyed Behind");
assert_eq!(h.state().session.tools.brush.mode, BlendMode::Darken);
}
/// On a pixel layer the dropdown's Behind is enabled and a click picks it.
#[test]
fn the_options_bar_dropdown_offers_behind_on_a_pixel_layer() {
use egui_kittest::kittest::{NodeT, Queryable};
let mut h = harness(true);
open_dropdown(&mut h);
assert!(!h.get_by_label("Behind").accesskit_node().is_disabled(), "Behind is enabled");
h.get_by_label("Behind").click();
h.run_steps(4);
assert!(h.state().session.tools.brush.behind, "picked");
assert_eq!(current(h.state(), Tool::PatternStamp), Some(Item::Behind));
}
/// What a pick stores: Behind when it is enabled; with it greyed, the mode one step further the
/// same way, whichever way the wheel or a key came.
#[test]
fn a_pick_that_lands_on_a_greyed_behind_steps_on() {
let (normal, dissolve, behind, darken) =
((Some(BlendMode::Normal), false), (Some(BlendMode::Dissolve), false), (None, true), (Some(BlendMode::Darken), false));
assert_eq!(pattern_stamp_pick(dissolve, behind, true), behind);
assert_eq!(pattern_stamp_pick(dissolve, behind, false), darken, "down");
assert_eq!(pattern_stamp_pick(normal, behind, false), darken, "two notches down");
assert_eq!(pattern_stamp_pick(darken, behind, false), dissolve, "up");
assert_eq!(pattern_stamp_pick(normal, darken, false), darken, "other modes are picked as they are");
// Behind chosen earlier on a pixel layer stays until another mode is picked.
assert_eq!(pattern_stamp_pick(behind, dissolve, false), dissolve);
}
+2 -1
View File
@@ -44,7 +44,8 @@ pub use color::{
#[cfg(test)] #[cfg(test)]
use color::{checker_tile_id, checker_uv}; use color::{checker_tile_id, checker_uv};
pub use dropdown::{ pub use dropdown::{
combo_list, dropdown, dropdown_hovered, dropdown_literal, dropdown_wheel_grouped, dropdown_wheel_hovered, dropdown_with_tooltips, menu_scroll, swatch_popup, combo_list, dropdown, dropdown_hovered, dropdown_literal, dropdown_wheel_grouped, dropdown_wheel_grouped_enabled, dropdown_wheel_hovered,
dropdown_with_tooltips, menu_scroll, swatch_popup,
}; };
pub(crate) use fields::compact_wrapping_value_field; pub(crate) use fields::compact_wrapping_value_field;
#[cfg(test)] #[cfg(test)]
+32 -5
View File
@@ -11,13 +11,13 @@ pub fn dropdown<T: PartialEq + Clone>(ui: &mut Ui, id: &str, name: &str, current
/// [`dropdown`] whose option labels are shown exactly as given: names the user typed (a channel /// [`dropdown`] whose option labels are shown exactly as given: names the user typed (a channel
/// or layer name) must not be translated, unlike the built-in labels [`dropdown`] translates (#5335). /// or layer name) must not be translated, unlike the built-in labels [`dropdown`] translates (#5335).
pub fn dropdown_literal<T: PartialEq + Clone>(ui: &mut Ui, id: &str, name: &str, current: &mut T, options: &[(T, &str)], width: f32) -> bool { pub fn dropdown_literal<T: PartialEq + Clone>(ui: &mut Ui, id: &str, name: &str, current: &mut T, options: &[(T, &str)], width: f32) -> bool {
let (chosen, _) = dropdown_with(ui, id, name, current, options, width, false, false, &|_| false); let (chosen, _) = dropdown_with(ui, id, name, current, options, width, false, false, &|_| false, &|_| true);
!chosen.is_empty() !chosen.is_empty()
} }
/// [`dropdown`], also returning the option under the pointer in its open list (live previews). /// [`dropdown`], also returning the option under the pointer in its open list (live previews).
pub fn dropdown_hovered<T: PartialEq + Clone>(ui: &mut Ui, id: &str, name: &str, current: &mut T, options: &[(T, &str)], width: f32) -> (bool, Option<T>) { pub fn dropdown_hovered<T: PartialEq + Clone>(ui: &mut Ui, id: &str, name: &str, current: &mut T, options: &[(T, &str)], width: f32) -> (bool, Option<T>) {
let (chosen, hovered) = dropdown_with(ui, id, name, current, options, width, false, true, &|_| false); let (chosen, hovered) = dropdown_with(ui, id, name, current, options, width, false, true, &|_| false, &|_| true);
(!chosen.is_empty(), hovered) (!chosen.is_empty(), hovered)
} }
@@ -35,7 +35,7 @@ pub fn dropdown_wheel_hovered<T: PartialEq + Clone>(
options: &[(T, &str)], options: &[(T, &str)],
width: f32, width: f32,
) -> (Vec<T>, Option<T>) { ) -> (Vec<T>, Option<T>) {
dropdown_with(ui, id, name, current, options, width, true, true, &|_| false) dropdown_with(ui, id, name, current, options, width, true, true, &|_| false, &|_| true)
} }
/// [`dropdown_wheel_hovered`] whose open list draws a line above each option (but the first) that /// [`dropdown_wheel_hovered`] whose open list draws a line above each option (but the first) that
@@ -50,7 +50,24 @@ pub fn dropdown_wheel_grouped<T: PartialEq + Clone>(
width: f32, width: f32,
starts_group: impl Fn(&T) -> bool, starts_group: impl Fn(&T) -> bool,
) -> (Vec<T>, Option<T>) { ) -> (Vec<T>, Option<T>) {
dropdown_with(ui, id, name, current, options, width, true, true, &starts_group) dropdown_with(ui, id, name, current, options, width, true, true, &starts_group, &|_| true)
}
/// [`dropdown_wheel_grouped`] whose open list greys the options `enabled` refuses: drawn disabled,
/// not picked by the pointer and not previewed. The wheel and the keys still land on them; the
/// caller steps past (#12879, the Pattern Stamp's Behind on the Background).
#[allow(clippy::too_many_arguments)]
pub fn dropdown_wheel_grouped_enabled<T: PartialEq + Clone>(
ui: &mut Ui,
id: &str,
name: &str,
current: &mut T,
options: &[(T, &str)],
width: f32,
starts_group: impl Fn(&T) -> bool,
enabled: impl Fn(&T) -> bool,
) -> (Vec<T>, Option<T>) {
dropdown_with(ui, id, name, current, options, width, true, true, &starts_group, &enabled)
} }
#[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]
@@ -64,6 +81,7 @@ fn dropdown_with<T: PartialEq + Clone>(
wheel: bool, wheel: bool,
translate: bool, translate: bool,
starts_group: &dyn Fn(&T) -> bool, starts_group: &dyn Fn(&T) -> bool,
enabled: &dyn Fn(&T) -> bool,
) -> (Vec<T>, Option<T>) { ) -> (Vec<T>, Option<T>) {
let shown = |l: &str| if translate { tl!(l).to_string() } else { l.to_string() }; let shown = |l: &str| if translate { tl!(l).to_string() } else { l.to_string() };
let label = options.iter().find(|(v, _)| v == current).map(|(_, l)| shown(l)).unwrap_or_else(|| "—".into()); let label = options.iter().find(|(v, _)| v == current).map(|(_, l)| shown(l)).unwrap_or_else(|| "—".into());
@@ -105,10 +123,19 @@ fn dropdown_with<T: PartialEq + Clone>(
if i > 0 && starts_group(v) { if i > 0 && starts_group(v) {
list_separator(ui); list_separator(ui);
} }
let item = ui.selectable_label(v == current, text.as_str()); let on = enabled(v);
let item = if on {
ui.selectable_label(v == current, text.as_str())
} else {
ui.add_enabled(false, egui::Button::selectable(v == current, text.as_str()))
};
if reveal && v == current { if reveal && v == current {
item.scroll_to_me(None); item.scroll_to_me(None);
} }
// A greyed option is neither previewed nor picked.
if !on {
continue;
}
if item.hovered() { if item.hovered() {
hovered = Some(v.clone()); hovered = Some(v.clone());
} }