Merge main into fix/stale-parity-rows

This commit is contained in:
dotCooCoo committed 2026-11-13 04:07:18 -08:00
commit d2716d5455
84 files changed
+3943 -346

No files matched your search

+3
View File
@@ -1785,3 +1785,6 @@ mod selected_alpha_tests {
}
}
}
#[cfg(test)]
mod paint_bucket_transparent_seed_tests;
+1 -1
View File
@@ -244,7 +244,7 @@ pub fn bucket_fill_inks(
return false;
}
let img = crate::selection::rgba8_image(s, area);
let Some(region) = crate::selection::wand_region(&img, area, seed, tolerance, contiguous, anti_alias) else { return false };
let Some(region) = crate::selection::wand_region_bucket(&img, area, seed, tolerance, contiguous, anti_alias) else { return false };
// Clicked on transparency with Anti-alias on: the wand's fringe gives the partly transparent
// pixels around the flood no coverage (their alpha is measured against the seed's 0), but the
// reference application fills each pixel 8-adjacent to the flood at coverage `1 − α`, so the
@@ -0,0 +1,185 @@
//! Paint Bucket match rule for transparent and semi-transparent seeds (#12529), Anti-alias off.
//!
//! The issue's document is 800 x 600 with a red square, a grey ramp and an anti-aliased black
//! disc on a transparent layer. These tests shrink the geometry (see `NOTES.md`) but keep every
//! measured relationship: the ramp is its own 256 x 1 strip so seeds 127 / 128 and the tolerances
//! 0 / 1 / 32 / 100 give the issue's exact grey ranges.
use photocraft_color::{PixelFormat, blend::BlendMode};
use photocraft_geom::Rect;
use photocraft_raster::Surface;
use crate::paint::{FillMode, bucket_fill_inks};
use crate::selection::{rgba8_image, wand_region};
const W: i32 = 100;
const H: i32 = 80;
const AREA: Rect = Rect { x0: 0, y0: 0, x1: W, y1: H };
const GREEN: [u8; 4] = [0, 255, 0, 255];
/// Row of the black disc's edge; x 10..14 hold alpha 40, 112, 197, 253 like (690..700, 400).
const EDGE_Y: i32 = 70;
/// Alphas of the edge row from x = 10: the 40 / 112 / 197 / 253 ladder, then solid 253 inside.
const LADDER: [u8; 4] = [40, 112, 197, 253];
fn idx(x: i32, y: i32) -> usize {
(y * W + x) as usize
}
/// Red square (40..60 x 10..30), grey ramp strip (value = x, x 0..64, y 40..43), and a black
/// edge row at `EDGE_Y` (x 10..14 the alpha ladder, x 14..30 alpha 253); the rest transparent.
fn document() -> Vec<[u8; 4]> {
let mut img = vec![[0u8; 4]; (W * H) as usize];
for y in 10..30 {
for x in 40..60 {
img[idx(x, y)] = [220, 30, 30, 255];
}
}
for y in 40..43 {
for x in 0..64 {
img[idx(x, y)] = [x as u8, x as u8, x as u8, 255];
}
}
for (i, a) in LADDER.iter().enumerate() {
img[idx(10 + i as i32, EDGE_Y)] = [0, 0, 0, *a];
}
for x in 14..30 {
img[idx(x, EDGE_Y)] = [0, 0, 0, 253];
}
img
}
fn surface(img: &[[u8; 4]], area: Rect) -> Surface {
let bytes: Vec<u8> = img.iter().flatten().copied().collect();
Surface::from_interleaved(PixelFormat::RGBA8, area, &bytes)
}
/// Bucket-fills green at `seed` and returns the layer afterwards.
fn fill(img: &[[u8; 4]], area: Rect, seed: (i32, i32), tol: f32, contiguous: bool) -> Vec<[u8; 4]> {
let mut s = surface(img, area);
let green = |_, _| [0.0, 1.0, 0.0, 1.0];
assert!(bucket_fill_inks(&mut s, area, seed, tol, contiguous, false, 1.0, None, false, green, None, FillMode::Blend(BlendMode::Normal)));
rgba8_image(&s, area)
}
/// Pixels the fill changed, as indices.
fn changed(before: &[[u8; 4]], after: &[[u8; 4]]) -> Vec<usize> {
(0..before.len()).filter(|&i| before[i] != after[i]).collect()
}
fn assert_only_alpha_zero_filled(before: &[[u8; 4]], after: &[[u8; 4]], label: &str) {
for (i, (b, a)) in before.iter().zip(after).enumerate() {
if b[3] == 0 {
assert_eq!(*a, GREEN, "{label}: transparent pixel {i} should fill");
} else {
assert_eq!(a, b, "{label}: pixel {i} with alpha {} must not change", b[3]);
}
}
}
#[test]
fn transparent_seed_fills_only_alpha_zero_at_any_tolerance() {
let img = document();
for tol in [0.0, 32.0, 255.0] {
let after = fill(&img, AREA, (49, 49), tol, true);
// The transparent background is one connected region here, so contiguous reaches all of it.
assert_only_alpha_zero_filled(&img, &after, &format!("tolerance {tol}"));
for (i, a) in LADDER.iter().enumerate() {
assert_eq!(after[idx(10 + i as i32, EDGE_Y)], [0, 0, 0, *a], "edge alpha {a} survives at tolerance {tol}");
}
assert_eq!(after[idx(9, EDGE_Y)], GREEN, "transparent pixel next to the edge fills");
assert_eq!(after[idx(50, 20)], [220, 30, 30, 255], "red square untouched at tolerance {tol}");
assert_eq!(after[idx(30, 41)], [30, 30, 30, 255], "ramp untouched at tolerance {tol}");
}
}
#[test]
fn transparent_seed_not_contiguous_fills_every_alpha_zero_pixel_only() {
let mut img = document();
// An enclosed transparent hole that contiguous fill cannot reach.
for y in 12..16 {
for x in 44..48 {
img[idx(x, y)] = [0, 0, 0, 0];
}
}
for tol in [0.0, 255.0] {
let after = fill(&img, AREA, (49, 49), tol, false);
assert_only_alpha_zero_filled(&img, &after, &format!("global, tolerance {tol}"));
assert_eq!(after[idx(45, 13)], GREEN, "the enclosed transparent hole fills");
assert_eq!(after[idx(13, EDGE_Y)], [0, 0, 0, 253]);
}
}
#[test]
fn semi_transparent_seed_takes_same_colour_pixels_of_any_nonzero_alpha() {
let img = document();
let after = fill(&img, AREA, (10, EDGE_Y), 32.0, true);
// The 40 / 112 / 197 / 253 ladder and the solid 253 run all fill: no alpha band applies.
for x in 10..30 {
assert_eq!(after[idx(x, EDGE_Y)], GREEN, "black alpha pixel at x {x} fills");
}
assert_eq!(after[idx(9, EDGE_Y)], [0, 0, 0, 0], "the transparent neighbour is never taken");
let n = changed(&img, &after).len();
assert_eq!(n, 20, "only the black edge row changes");
}
#[test]
fn semi_transparent_seed_respects_colour_tolerance() {
let mut img = document();
img[idx(12, EDGE_Y)] = [100, 100, 100, 112];
let after = fill(&img, AREA, (10, EDGE_Y), 32.0, true);
assert_eq!(after[idx(11, EDGE_Y)], GREEN);
assert_eq!(after[idx(12, EDGE_Y)], [100, 100, 100, 112], "a colour outside Tolerance stays");
assert_eq!(after[idx(13, EDGE_Y)], [0, 0, 0, 253], "and it cuts the contiguous run");
}
fn ramp_strip() -> Vec<[u8; 4]> {
(0..=255u8).map(|v| [v, v, v, 255]).collect()
}
fn filled_range(after: &[[u8; 4]]) -> Option<(usize, usize)> {
let hits: Vec<usize> = (0..after.len()).filter(|&i| after[i] == GREEN).collect();
Some((*hits.first()?, *hits.last()?))
}
#[test]
fn opaque_seed_keeps_todays_ranges() {
let img = ramp_strip();
let area = Rect::new(0, 0, 256, 1);
for (seed, tol, contiguous, lo, hi) in
[(127, 0.0, true, 127, 127), (127, 1.0, true, 126, 128), (127, 32.0, true, 95, 159), (127, 100.0, true, 27, 227), (128, 32.0, false, 96, 160)]
{
let after = fill(&img, area, (seed, 0), tol, contiguous);
assert_eq!(filled_range(&after), Some((lo, hi)), "seed {seed} tolerance {tol} contiguous {contiguous}");
let count = after.iter().filter(|p| **p == GREEN).count();
assert_eq!(count, hi - lo + 1, "the filled range is solid");
}
}
/// The wand rule did not move: a transparent seed at Tolerance 255 still matches every pixel
/// (alpha within 255 of 0), which is what the Magic Wand and Magic Eraser keep.
#[test]
fn wand_region_still_uses_the_alpha_band() {
let img = document();
let r = wand_region(&img, AREA, (49, 49), 255.0, true, false).expect("seed is inside");
assert_eq!(r.at(50, 20), 1.0, "red square is inside the wand region");
assert_eq!(r.at(30, 41), 1.0, "ramp is inside the wand region");
assert_eq!(r.at(13, EDGE_Y), 1.0, "disc edge is inside the wand region");
let r32 = wand_region(&img, AREA, (49, 49), 32.0, true, false).expect("seed is inside");
assert_eq!(r32.at(10, EDGE_Y), 0.0, "alpha 40 is outside a Tolerance 32 alpha band");
assert_eq!(r32.at(9, EDGE_Y), 1.0, "alpha 0 is inside it");
}
/// The measured semi-transparent case is one colour at several alphas; a pixel of another
/// colour keeps the alpha band the shared rule always had (the issue leaves unmeasured
/// cases at today's behaviour). Seed [0, 0, 0, 40] at x = 1: x = 0 is the same-colour
/// control [0, 0, 0, 253]; x = 2 is [20, 20, 20, 197] — its RGB distance of 20 passes
/// Tolerance 32, but its alpha sits 157 from the seed's, so it is not filled.
#[test]
fn semi_transparent_seed_keeps_the_alpha_band_for_other_colours() {
let img: Vec<[u8; 4]> = vec![[0, 0, 0, 253], [0, 0, 0, 40], [20, 20, 20, 197]];
let area = Rect::new(0, 0, 3, 1);
let after = fill(&img, area, (1, 0), 32.0, true);
let ch = changed(&img, &after);
assert!(ch.contains(&0), "same-colour pixel of alpha 253 fills");
assert!(!ch.contains(&2), "different-colour pixel of alpha 197 keeps the alpha band");
}
+53 -1
View File
@@ -354,6 +354,51 @@ pub fn wand_region_by(
anti_alias: bool,
within: Option<&[f32]>,
distance: ColorDistance,
) -> Option<Region> {
region_by_rule(img, area, seed, tolerance, contiguous, anti_alias, within, distance, MatchRule::Wand)
}
/// Which pixels count as "similar" to the clicked one.
#[derive(Clone, Copy)]
enum MatchRule {
/// The Magic Wand / Magic Eraser rule: colour and alpha each within Tolerance, except that
/// two fully transparent pixels always match.
Wand,
/// The Paint Bucket rule, see [`wand_region_bucket`].
Bucket,
}
/// [`wand_region`] with the Paint Bucket's match rule (measured on the reference, #12529).
///
/// It differs from the wand rule only when the clicked pixel is not opaque. The wand lets any
/// pixel whose alpha is within Tolerance of the seed's match, so a bucket click on transparent
/// pixels leaked into the anti-aliased edge of a shape and, at Tolerance 255, filled the whole
/// layer (#6183). The bucket rule is:
/// - seed alpha 0: only pixels with alpha 0 match; Tolerance plays no role;
/// - seed alpha 255: unchanged (colour and alpha each within Tolerance);
/// - seed alpha in between: a pixel of the seed's own colour matches when its alpha is
/// above 0 — there is no alpha band for that case (alpha 40, 197 and 253 of one colour
/// were measured to fill together). A pixel of any other colour must also sit within
/// Tolerance of the seed's alpha, as before: that case was not measured, and unmeasured
/// cases keep today's behaviour. Alpha-0 pixels are never taken.
///
/// Only that one semi-transparent case was measured; unmeasured cases keep the previous
/// behaviour. [`wand_region`] and [`wand_region_within`] are unchanged.
pub(crate) fn wand_region_bucket(img: &[[u8; 4]], area: Rect, seed: (i32, i32), tolerance: f32, contiguous: bool, anti_alias: bool) -> Option<Region> {
region_by_rule(img, area, seed, tolerance, contiguous, anti_alias, None, ColorDistance::LargestChannel, MatchRule::Bucket)
}
#[allow(clippy::too_many_arguments)]
fn region_by_rule(
img: &[[u8; 4]],
area: Rect,
seed: (i32, i32),
tolerance: f32,
contiguous: bool,
anti_alias: bool,
within: Option<&[f32]>,
distance: ColorDistance,
rule: MatchRule,
) -> Option<Region> {
if !area.contains(seed.0, seed.1) {
return None;
@@ -371,7 +416,14 @@ pub fn wand_region_by(
let tol = (tolerance + 1e-3).floor().max(0.0) as i32;
// Copying a selection can leave RGB under zero alpha. Those invisible colours must not
// split a transparent region into pieces, as if the copied source were still visible.
let similar = |p: [u8; 4]| (target[3] == 0 && p[3] == 0) || (distance.rgb(p, target) <= tol && (p[3] as i32 - target[3] as i32).abs() <= tol);
let similar = |p: [u8; 4]| match rule {
MatchRule::Wand => (target[3] == 0 && p[3] == 0) || (distance.rgb(p, target) <= tol && (p[3] as i32 - target[3] as i32).abs() <= tol),
MatchRule::Bucket => match target[3] {
0 => p[3] == 0,
255 => distance.rgb(p, target) <= tol && (p[3] as i32 - 255).abs() <= tol,
_ => p[3] != 0 && distance.rgb(p, target) <= tol && (p[..3] == target[..3] || (p[3] as i32 - target[3] as i32).abs() <= tol),
},
};
let mut marks = vec![0u8; w * h];
let (mut bx0, mut by0, mut bx1, mut by1) = (usize::MAX, usize::MAX, 0usize, 0usize);
if contiguous {
+2
View File
@@ -100,6 +100,8 @@ pub mod frame_cmds;
pub mod fx_view_cmds;
pub mod fx_visibility_cmds;
pub mod gallery_cmds;
#[cfg(test)]
mod gradient_alpha_method_tests;
pub mod gradient_fill_cmds;
pub mod group_view_cmds;
pub mod history_cmds;
@@ -0,0 +1,118 @@
//! #12010: the transparency of a gradient drawn with the Gradient tool follows the interpolation
//! method (Smooth by default) instead of a straight line. Reference: Foreground to Transparent,
//! Smooth, dragged (100, 300) to (700, 300): alpha 255 / 179 / 100 / 35 / 0 at x 50 / 250 / 400 /
//! 550 / 750.
use serde_json::{Value, json};
use crate::Session;
fn drawn(extra: Value) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 800, "height": 600, "background": "transparent"})).unwrap();
let mut p = json!({"gradient": "Foreground to Transparent", "from": [100, 300], "to": [700, 300], "dither": false});
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
s.execute("paint.gradient", p).unwrap();
s
}
fn alpha_at(s: &Session, x: i32) -> f32 {
let d = s.active().unwrap();
let l = d.doc.layer(d.active_layer.unwrap()).unwrap();
let photocraft_doc::LayerContent::Raster(surface) = &l.content else { panic!("a pixel layer") };
surface.pixel(x, 300)[3] * 255.0
}
#[test]
fn smooth_transparency_ramp_matches_the_reference() {
let s = drawn(json!({"method": "smooth"}));
for (x, want) in [(50, 255.0), (250, 179.0), (400, 100.0), (550, 35.0), (750, 0.0)] {
let got = alpha_at(&s, x);
assert!((got - want).abs() <= 2.0, "x={x}: alpha {got:.1}, want {want}");
}
}
#[test]
fn without_a_method_the_ramp_stays_straight() {
let s = drawn(json!({}));
for (x, want) in [(250, 191.0), (400, 128.0), (550, 64.0)] {
let got = alpha_at(&s, x);
assert!((got - want).abs() <= 2.0, "x={x}: alpha {got:.1}, want {want}");
}
}
#[test]
fn opaque_gradients_paint_the_same_with_a_method() {
let paint = |extra: Value| {
let mut s = Session::new();
s.execute("file.new", json!({"width": 64, "height": 8, "background": "white"})).unwrap();
let mut p = json!({"colors": ["#000000", "#ffffff"], "from": [0, 4], "to": [64, 4], "dither": false});
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
s.execute("paint.gradient", p).unwrap();
(0..64).map(|x| alpha_and_red(&s, x)).collect::<Vec<_>>()
};
fn alpha_and_red(s: &Session, x: i32) -> Vec<f32> {
let d = s.active().unwrap();
let l = d.doc.layer(d.active_layer.unwrap()).unwrap();
let photocraft_doc::LayerContent::Raster(surface) = &l.content else { panic!() };
surface.pixel(x, 4)
}
// The colours still follow the method; the alpha stays opaque.
let smooth = paint(json!({"method": "smooth"}));
assert!(smooth.iter().all(|p| (p[3] - 1.0).abs() < 1e-3));
assert_ne!(smooth, paint(json!({})));
}
// Not measured in the Gradient tool: the other methods, and Smooth below 100 % Smoothness, keep
// today's merged stops (each dense stop takes the nearest stop's alpha).
#[test]
fn unmeasured_methods_and_smoothness_keep_todays_ramp() {
for extra in [json!({"method": "classic"}), json!({"method": "perceptual"}), json!({"method": "linear"}), json!({"method": "smooth", "smoothness": 50})] {
let s = drawn(extra.clone());
for (x, want) in [(250, 191.0), (400, 128.0), (550, 64.0)] {
let got = alpha_at(&s, x);
assert!((got - want).abs() <= 1.0, "{extra} x={x}: alpha {got:.1}, want {want}");
}
}
}
fn drawn_colors(colors: Value) -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 800, "height": 600, "background": "transparent"})).unwrap();
let p = json!({"colors": colors, "transparency": [[0, 100], [1, 0]], "method": "smooth", "from": [100, 300], "to": [700, 300], "dither": false});
s.execute("paint.gradient", p).unwrap();
s
}
#[test]
fn one_colour_with_a_transparency_ramp_follows_smooth() {
let s = drawn_colors(json!(["#ff0000"]));
for (x, want) in [(50, 255.0), (250, 179.0), (400, 100.0), (550, 35.0), (750, 0.0)] {
let got = alpha_at(&s, x);
assert!((got - want).abs() <= 2.0, "x={x}: alpha {got:.1}, want {want}");
}
}
#[test]
fn legacy_colours_keep_their_own_alpha() {
let s = drawn_colors(json!(["#ff000080", "#ff000080"]));
for (x, want) in [(50, 128.0), (400, 64.0), (750, 0.0)] {
let got = alpha_at(&s, x);
assert!((got - want).abs() <= 1.0, "x={x}: alpha {got:.1}, want {want}");
}
}
// paint_gradient scans the stops for every pixel: Smooth's colour and opacity bakes share their
// 97 positions and must not be cut into four per interval (385 stops).
#[test]
fn smooth_transparency_keeps_one_stop_per_sampled_position() {
use photocraft_color::Color;
let black = Color::rgb(0.0, 0.0, 0.0);
let stops = super::paint_cmds::smooth_split_stops((vec![(0.0, black), (1.0, black)], vec![(0.0, 1.0), (1.0, 0.0)]));
assert_eq!(stops.len(), 97);
assert!((stops[0].1[3] - 1.0).abs() < 1e-6 && stops[96].1[3].abs() < 1e-6);
}
+78 -9
View File
@@ -161,15 +161,26 @@ fn gradient(s: &mut Session, p: &Value) -> Result<Value> {
// where straight stops give 0.0625.
let stops = match p.get("method").and_then(Value::as_str).and_then(photocraft_io::GradientMethod::from_name) {
Some(m) if stops.len() >= 2 => {
let colors = stops.iter().map(|(t, c)| (*t, photocraft_color::Color::rgba(c[0], c[1], c[2], c[3]))).collect();
let mids = vec![0.5; stops.len() - 1];
photocraft_io::bake_gradient(colors, &mids, (f(p, "smoothness", 100.0) / 100.0).clamp(0.0, 1.0), m)
.into_iter()
.map(|(t, c)| {
let rgb = c.to_rgb();
(t, [rgb[0], rgb[1], rgb[2], c.alpha])
})
.collect()
let smoothness = (f(p, "smoothness", 100.0) / 100.0).clamp(0.0, 1.0);
// Smooth at 100 % Smoothness bakes the colour and opacity stops apart: the colours by
// the method, the opacity by Smooth's measured transparency curve (#12010). Merged
// stops would take the nearest stop's alpha. The other methods and Smoothness values
// were not measured in the Gradient tool and keep the merged stops.
let split = if m == photocraft_io::GradientMethod::Smooth && smoothness >= 1.0 { split_stops(s, p, fg)? } else { None };
match split {
Some(split) => smooth_split_stops(split),
None => {
let colors = stops.iter().map(|(t, c)| (*t, photocraft_color::Color::rgba(c[0], c[1], c[2], c[3]))).collect();
let mids = vec![0.5; stops.len() - 1];
photocraft_io::bake_gradient(colors, &mids, smoothness, m)
.into_iter()
.map(|(t, c)| {
let rgb = c.to_rgb();
(t, [rgb[0], rgb[1], rgb[2], c.alpha])
})
.collect()
}
}
}
_ => stops,
};
@@ -188,6 +199,64 @@ fn gradient(s: &mut Session, p: &Value) -> Result<Value> {
Ok(Value::Null)
}
/// Smooth's colour and opacity stops baked apart, then joined. Both bakes sample the same
/// positions, so the alpha is multiplied in at each one: [`gradients::apply_opacity`] would cut
/// every interval into four (385 stops instead of 97), and `paint_gradient` scans the stops for
/// every pixel. Positions that differ still go through `apply_opacity`.
pub(crate) fn smooth_split_stops((cs, os): gradients::FillStops) -> gradients::Stops {
let mids = vec![0.5; cs.len().saturating_sub(1)];
let colours: gradients::Stops = photocraft_io::bake_gradient(cs, &mids, 1.0, photocraft_io::GradientMethod::Smooth)
.into_iter()
.map(|(t, c)| {
let rgb = c.to_rgb();
(t, [rgb[0], rgb[1], rgb[2], 1.0])
})
.collect();
let omids = vec![0.5; os.len().saturating_sub(1)];
let opacity = photocraft_io::bake_gradient_smooth_opacity(os, &omids);
if colours.len() != opacity.len() || colours.iter().zip(&opacity).any(|(c, o)| (c.0 - o.0).abs() > 1e-6) {
return gradients::apply_opacity(colours, &opacity);
}
colours
.into_iter()
.zip(opacity)
.map(|((t, mut c), (_, a))| {
c[3] = if a.is_finite() { a.clamp(0.0, 1.0) } else { 1.0 };
(t, c)
})
.collect()
}
/// The Gradient tool's colour stops (opaque) and opacity stops kept apart, for Smooth's own
/// transparency curve. `None` when the opacity is constant, or when legacy `colors` carry their
/// own alpha (that case keeps the merged stops). A single colour stop spans the whole gradient.
fn split_stops(s: &Session, p: &Value, fg: [f32; 4]) -> Result<Option<gradients::FillStops>> {
let (mut cs, os) = match gradients::tool_fill_stops(s, p)? {
Some(split) => split,
None => {
// The legacy `colors` list, evenly spaced.
let colors: Vec<[f32; 4]> = p.get("colors").and_then(Value::as_array).map(|a| a.iter().map(|v| color(Some(v), fg)).collect()).unwrap_or_default();
if colors.iter().any(|c| c[3] < 1.0) {
return Ok(None);
}
let n = colors.len();
let cs = colors
.iter()
.enumerate()
.map(|(i, c)| (if n > 1 { i as f32 / (n - 1) as f32 } else { 0.0 }, photocraft_color::Color::rgb(c[0], c[1], c[2])))
.collect();
(cs, gradients::transparency_param(p, "paint.gradient")?.unwrap_or_default())
}
};
if os.iter().all(|o| (o.1 - 1.0).abs() < 1e-6) {
return Ok(None);
}
if let [(_, c)] = cs.as_slice() {
cs = vec![(0.0, *c), (1.0, *c)];
}
Ok(if cs.is_empty() { None } else { Some((cs, os)) })
}
/// Paint helper command specs.
pub fn specs() -> Vec<CommandSpec> {
vec![
+3 -1
View File
@@ -29,7 +29,9 @@ mod art_history;
mod content_aware_move;
mod patch;
mod pattern_stamp;
pub use pattern_stamp::live_impressionist as live_pattern_impressionist;
pub use pattern_stamp::{
INDEXED_REFUSAL as PATTERN_STAMP_INDEXED_REFUSAL, live_impressionist as live_pattern_impressionist, press_refusal as pattern_stamp_press_refusal,
};
mod periodic;
mod remove;
pub use content_aware_move::{ContentAwarePreview, preview as content_aware_move_preview};
@@ -9,7 +9,7 @@
//! 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, ColorMode, PixelFormat};
use photocraft_compose::pattern::{Placement, Tile, render};
use photocraft_doc::{LayerId, Pattern};
use photocraft_geom::Rect;
@@ -19,11 +19,30 @@ use photocraft_raster::{Surface, from_rgba_into, to_rgba};
use serde_json::{Value, json};
use super::{bad, blend_param, damage_json, flag, has_pixel_layer, parse_brush, reject_huge_stroke};
use crate::{Result, Session};
use crate::{EngineError, Result, Session};
const STREAM_PHASE_X: u64 = 101;
const STREAM_PHASE_Y: u64 = 102;
/// The reference's alert for a Pattern Stamp stroke in an Indexed Color document (#12887).
pub const INDEXED_REFUSAL: &str = "Could not fill because the pattern and image have different color modes.";
/// The reference refuses every pattern in an Indexed Color document before painting: RGB,
/// Grayscale, CMYK, Lab and Indexed ones from another image. It paints only a pattern with the
/// document's own colour table, which PhotoCraft can't tell apart, so that one is refused too.
/// Bitmap, Duotone and Multichannel documents weren't measured and paint as before.
fn mode_refusal(s: &Session) -> Result<()> {
if s.active().is_some_and(|st| st.doc.mode == ColorMode::Indexed) { Err(EngineError::Other(INDEXED_REFUSAL.into())) } else { Ok(()) }
}
/// [`mode_refusal`] for a press with the stroke's `p`, so the canvas can alert before the stroke
/// starts: `None` when the pattern paints, or when `p` names no pattern (the stroke reports that).
pub fn press_refusal(s: &Session, p: &Value) -> Option<String> {
mode_refusal(s).err()?;
crate::pattern_cmds::resolve_param(s, "paint.patternStamp", p).ok()?;
Some(INDEXED_REFUSAL.into())
}
pub(super) fn enabled(s: &Session) -> std::result::Result<(), String> {
has_pixel_layer(s)?;
if crate::pattern_cmds::resolve_id(s, "").is_none() { Err("no pattern selected".into()) } else { Ok(()) }
@@ -58,6 +77,7 @@ impl Setup {
let aligned = flag(p, "aligned", true);
let impressionist = flag(p, "impressionist", false);
let pat = crate::pattern_cmds::resolve_param(s, CMD, p)?;
mode_refusal(s)?;
if pat.is_empty() {
return Err(bad(CMD, "the pattern is empty"));
}
@@ -366,3 +386,7 @@ mod tests {
assert!(reject_huge_stroke("t", &stroke(&[(0.0, 0.0), (9000.0, 9000.0)], 100.0)).is_err());
}
}
#[cfg(test)]
#[path = "pattern_stamp_indexed_tests.rs"]
mod pattern_stamp_indexed_tests;
@@ -0,0 +1,96 @@
//! #12887: in an Indexed Color document the Pattern Stamp refuses every pattern (RGB, Grayscale,
//! CMYK, Lab, or one defined from an Indexed image) with the reference application's message,
//! painting nothing and adding no history; the live strokes are refused the same way. RGB,
//! Grayscale, CMYK and Lab documents at every depth keep painting with it.
use super::super::LiveRetouch;
use super::*;
/// A new `mode` document of `depth` bits, 64 × 64, white.
fn new_doc(s: &mut Session, mode: &str, depth: u64) {
s.execute("file.new", json!({"width": 64, "height": 64, "depth": depth, "mode": mode})).unwrap();
}
/// The reference's test pattern: 20 × 20 with red, green, blue and white quadrants, defined from a
/// `mode` document. Returns its id.
fn quadrants(s: &mut Session, mode: &str) -> String {
s.execute("file.new", json!({"width": 20, "height": 20, "depth": 8, "mode": mode})).unwrap();
for (x, y, color) in [(0, 0, "#ff0000"), (10, 0, "#00ff00"), (0, 10, "#0000ff")] {
s.execute("select.rect", json!({"x": x, "y": y, "width": 10, "height": 10})).unwrap();
s.execute("edit.fill", json!({"color": color})).unwrap();
}
s.execute("select.deselect", json!({})).unwrap();
let r = s.execute("edit.definePattern", json!({"name": format!("Quadrants {mode}")})).unwrap();
r["pattern"].as_str().unwrap().to_string()
}
fn to_indexed(s: &mut Session) {
s.execute("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none"})).unwrap();
}
fn stroke(pattern: &str, impressionist: bool) -> Value {
json!({"points": [[12, 32], [52, 32]], "size": 30, "hardness": 100, "pattern": pattern, "impressionist": impressionist})
}
/// The active layer's pixels and the History length.
fn state(s: &Session) -> (Vec<[f32; 4]>, usize) {
let st = s.active().unwrap();
let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap();
((0..64).flat_map(|y| (0..64).map(move |x| surf.rgba(x, y))).collect(), st.history.past_len())
}
#[test]
fn an_rgb_pattern_is_refused_in_an_indexed_document_with_the_reference_words() {
let mut s = Session::new();
let pat = quadrants(&mut s, "rgb");
new_doc(&mut s, "rgb", 8);
to_indexed(&mut s);
let before = state(&s);
for impressionist in [false, true] {
let err = s.execute("paint.patternStamp", stroke(&pat, impressionist)).unwrap_err().to_string();
assert_eq!(err, INDEXED_REFUSAL, "impressionist {impressionist}");
assert_eq!(state(&s), before, "impressionist {impressionist}: nothing painted, no history");
}
// The press check the canvas alerts with, and the live strokes, which preview nothing.
assert_eq!(press_refusal(&s, &stroke(&pat, false)).as_deref(), Some(INDEXED_REFUSAL));
let live = LiveRetouch::begin(&s, "paint.patternStamp", &stroke(&pat, false)).err().map(|e| e.to_string());
assert_eq!(live.as_deref(), Some(INDEXED_REFUSAL), "live");
let dabs = live_impressionist(&s, &stroke(&pat, true)).err().map(|e| e.to_string());
assert_eq!(dabs.as_deref(), Some(INDEXED_REFUSAL), "live Impressionist");
}
#[test]
fn other_documents_keep_painting_with_the_rgb_pattern() {
let mut s = Session::new();
let pat = quadrants(&mut s, "rgb");
for mode in ["rgb", "grayscale", "cmyk", "lab"] {
for depth in [8, 16, 32] {
new_doc(&mut s, mode, depth);
let (pixels, steps) = state(&s);
assert_eq!(press_refusal(&s, &stroke(&pat, false)), None, "{mode}/{depth}");
s.execute("paint.patternStamp", stroke(&pat, false)).unwrap_or_else(|e| panic!("{mode}/{depth}: {e}"));
let after = state(&s);
assert_ne!(after.0, pixels, "{mode}/{depth}: painted");
assert_eq!(after.1, steps + 1, "{mode}/{depth}: one history step");
}
}
}
#[test]
fn grayscale_cmyk_lab_and_indexed_patterns_are_refused_in_an_indexed_document_too() {
let mut s = Session::new();
let mut patterns = ["grayscale", "cmyk", "lab"].map(|mode| quadrants(&mut s, mode)).to_vec();
// A pattern defined from an Indexed Color image.
s.execute("file.new", json!({"width": 20, "height": 20, "depth": 8, "mode": "rgb"})).unwrap();
to_indexed(&mut s);
patterns.push(s.execute("edit.definePattern", json!({"name": "Indexed"})).unwrap()["pattern"].as_str().unwrap().to_string());
new_doc(&mut s, "rgb", 8);
to_indexed(&mut s);
let before = state(&s);
for pat in patterns {
let err = s.execute("paint.patternStamp", stroke(&pat, false)).unwrap_err().to_string();
assert_eq!(err, INDEXED_REFUSAL, "{pat}");
assert_eq!(press_refusal(&s, &stroke(&pat, false)).as_deref(), Some(INDEXED_REFUSAL), "{pat}");
assert_eq!(state(&s), before, "{pat}: nothing painted, no history");
}
}
+2 -2
View File
@@ -98,7 +98,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New Shape Layer",
["Layer", "New"],
leak(format!(
r##"{{"kind":"rect|roundedRect|ellipse|polygon|star|line|path"="rect","rect":[x,y,w,h] (rect/roundedRect/ellipse/polygon/star),"radii":[tl,tr,br,bl]|r (roundedRect=10),"sides":3..100=5,"starRatio":0..1 (star=0.5),"cornerRadius":px=0 (polygon: rounds every vertex, star: its outer points; the Triangle tool is a 3-sided polygon),"from":[x,y],"to":[x,y],"weight":px=1 (line),"arrowStart":bool=false,"arrowEnd":bool=false,"arrowWidth":px=52,"arrowLength":px=50,"arrowConcavity":0..100=0 (line),"path":{{…}} (kind path),{fill}=foreground,{stroke}=none,"name":str?,"addTo":layerId? + "op":"combine|subtract|intersect|exclude" (append to an existing shape layer)}} → shape.info. {PATH_FORM}"##
r##"{{"kind":"rect|roundedRect|ellipse|polygon|star|line|path"="rect","rect":[x,y,w,h] (rect/roundedRect/ellipse/polygon/star),"radii":[tl,tr,br,bl]|r (roundedRect=10),"sides":3..100=5,"starRatio":0..1 (star=0.5),"cornerRadius":px=0 (polygon: rounds every vertex, star: its outer points; the Triangle tool is a 3-sided polygon),"from":[x,y],"to":[x,y],"weight":px=1 (line),"arrowStart":bool=false,"arrowEnd":bool=false,"arrowWidth":px=52,"arrowLength":px=50,"arrowConcavity":-50..50=0 (line; rounded to a whole percent),"path":{{…}} (kind path),{fill}=foreground,{stroke}=none,"name":str?,"addTo":layerId? + "op":"combine|subtract|intersect|exclude" (append to an existing shape layer)}} → shape.info. {PATH_FORM}"##
)),
has_doc,
shape_create
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Edit Shape",
[],
leak(format!(
r##"{{"layer":id?,"path":{{…}}? (replaces; drops live shape),"kind":str?,"rect":[x,y,w,h]?,"radii":[tl,tr,br,bl]|r?,"sides":n?,"starRatio":r?,"cornerRadius":px?,"from":[x,y]?,"to":[x,y]?,"weight":px? (live-shape params regenerate the path),"arrowStart":bool?,"arrowEnd":bool?,"arrowWidth":px?,"arrowLength":px?,"arrowConcavity":0..100? (line arrows),"move":[dx,dy]?,"transform":[a,b,c,d,e,f]?,"op":"combine|…"? + "subpath":index? (default all but the first),"fillRule":"nonzero|evenodd"?,{fill}?,{stroke}? (merged into the current stroke),"name":str?}} → shape.info"##
r##"{{"layer":id?,"path":{{…}}? (replaces; drops live shape),"kind":str?,"rect":[x,y,w,h]?,"radii":[tl,tr,br,bl]|r?,"sides":n?,"starRatio":r?,"cornerRadius":px?,"from":[x,y]?,"to":[x,y]?,"weight":px? (live-shape params regenerate the path),"arrowStart":bool?,"arrowEnd":bool?,"arrowWidth":px?,"arrowLength":px?,"arrowConcavity":-50..50? (line arrows),"move":[dx,dy]?,"transform":[a,b,c,d,e,f]?,"op":"combine|…"? + "subpath":index? (default all but the first),"fillRule":"nonzero|evenodd"?,{fill}?,{stroke}? (merged into the current stroke),"name":str?}} → shape.info"##
)),
has_layer,
shape_edit
+3 -1
View File
@@ -398,7 +398,9 @@ pub(super) fn live_from_params(cmd: &str, kind: &str, p: &Value, prev: Option<&L
end: flag("arrowEnd", pe)?,
width: dim("arrowWidth", pwidth, 1.0, 4096.0)?,
length: dim("arrowLength", plen, 1.0, 4096.0)?,
concavity: dim("arrowConcavity", pc, 0.0, 100.0)?,
// A whole -50..50 % as in Photoshop (#13258); a shape saved with the old 0..100
// range keeps working when another property is edited.
concavity: dim("arrowConcavity", if pc.is_finite() { pc.clamp(-50.0, 50.0) } else { 0.0 }, -50.0, 50.0)?.round(),
}
} else {
LiveShape::Line { from, to, weight }
+30 -1
View File
@@ -1464,7 +1464,7 @@ fn arrowhead_dimensions_reject_invalid_values_without_mutation() {
for (key, invalids) in [
("arrowWidth", [json!("52"), json!(null), json!([]), json!(0), json!(4097)]),
("arrowLength", [json!("50"), json!(null), json!([]), json!(0), json!(4097)]),
("arrowConcavity", [json!("0"), json!(null), json!([]), json!(-1), json!(101)]),
("arrowConcavity", [json!("0"), json!(null), json!([]), json!(-51), json!(51)]),
] {
for invalid in invalids {
let mut create = json!({
@@ -1486,6 +1486,35 @@ fn arrowhead_dimensions_reject_invalid_values_without_mutation() {
}
}
/// Concavity takes -50..50 % (#13258); a shape saved with the old 0..100 range still edits.
#[test]
fn arrow_concavity_takes_minus_fifty_to_fifty() {
let mut s = session(160, 120, 8);
let concavity = |s: &Session, id: u64| match s.active().unwrap().doc.layer(LayerId(id)).map(|l| &l.content) {
Some(LayerContent::Shape(sh)) => match sh.live {
Some(LiveShape::ArrowLine { concavity, .. }) => concavity,
_ => panic!("expected a live arrow"),
},
_ => panic!("expected a shape layer"),
};
let created = s.execute("shape.create", json!({"kind": "line", "from": [10, 20], "to": [120, 20], "arrowEnd": true, "arrowConcavity": -50})).unwrap();
let id = created["layer"].as_u64().unwrap();
assert_eq!(concavity(&s, id), -50.0);
s.execute("shape.edit", json!({"layer": id, "arrowConcavity": 50})).unwrap();
assert_eq!(concavity(&s, id), 50.0);
// Whole percents only, as the fields take them.
s.execute("shape.edit", json!({"layer": id, "arrowConcavity": -20.6})).unwrap();
assert_eq!(concavity(&s, id), -21.0);
if let Some(LayerContent::Shape(sh)) = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc).layer_mut(LayerId(id)).map(|l| &mut l.content)
&& let Some(LiveShape::ArrowLine { concavity, .. }) = &mut sh.live
{
*concavity = 80.0;
}
s.execute("shape.edit", json!({"layer": id, "arrowWidth": 12})).unwrap();
assert_eq!(concavity(&s, id), 50.0, "an old 0..100 value is clamped, not refused");
}
#[test]
fn headless_diagonal_arrow_preserves_geometry_after_nonuniform_scale() {
let mut s = session(400, 400, 8);
+12 -3
View File
@@ -401,19 +401,28 @@ pub const STOP: &str = "gradient.presets.stop";
/// own. `None` when the caller gave `colors` (the legacy evenly spaced form `paint.gradient`
/// handles itself).
pub fn tool_stops(s: &Session, p: &Value) -> Result<Option<Stops>> {
Ok(tool_preset(s, p)?.map(|g| g.resolve(s.tools.foreground, s.tools.background)))
}
/// The same gradient as [`tool_stops`] with its colour and opacity stops kept apart, for the
/// interpolation `method`, which treats the two differently.
pub fn tool_fill_stops(s: &Session, p: &Value) -> Result<Option<FillStops>> {
Ok(tool_preset(s, p)?.map(|g| g.fill_stops(s.tools.foreground, s.tools.background)))
}
fn tool_preset(s: &Session, p: &Value) -> Result<Option<GradientPreset>> {
const CMD: &str = "paint.gradient";
if p.get("colors").and_then(Value::as_array).is_some_and(|a| !a.is_empty()) {
return Ok(None);
}
let g = if let Some(name) = str_param(p, "gradient") {
Ok(Some(if let Some(name) = str_param(p, "gradient") {
let (gi, ii) = find(&s.presets.gradients, name, None).ok_or_else(|| bad(CMD, format!("no gradient preset \"{name}\"")))?;
s.presets.gradients[gi].items[ii].clone().with_transparency(p, CMD)?
} else if p.get("stops").is_some() {
GradientPreset::from_params("Custom", p, CMD)?
} else {
s.presets.gradient.clone().with_transparency(p, CMD)?
};
Ok(Some(g.resolve(s.tools.foreground, s.tools.background)))
}))
}
/// The preset named by `"preset"` (else the current gradient), or explicit `"stops"`.
+42 -2
View File
@@ -230,8 +230,8 @@ const OPACITY_RESPONSE: f32 = 0.65;
/// Dense linear opacity stops reproducing Photoshop's interpolation of a gradient's transparency
/// (Smoothness, opacity midpoints and the method, see [`OPACITY_RESPONSE`]). Returns the input
/// unchanged when it already interpolates linearly. Smooth keeps Classic's opacity curve: it was
/// not measured (the Photoshop build it was fitted on has no Smooth method).
/// unchanged when it already interpolates linearly. Smooth keeps Classic's opacity curve here: it
/// was measured only in the Gradient tool at 100 % Smoothness ([`bake_smooth_opacity`]).
pub fn bake_opacity(stops: Vec<(f32, f32)>, midpoints: &[f32], smoothness: f32, method: Method) -> Vec<(f32, f32)> {
let method = if method == Method::Smooth { Method::Classic } else { method };
let plain_mids = midpoints.iter().all(|m| (m - 0.5).abs() < 1e-3);
@@ -271,6 +271,38 @@ pub fn bake_opacity(stops: Vec<(f32, f32)>, midpoints: &[f32], smoothness: f32,
baked
}
/// Gamma of Smooth's opacity response: the opacity of a fully transparent gradient ramp is the
/// Oklab lightness curve's linear value `y` raised to `1 / 2.2`. Photoshop 27.11, "Foreground to
/// Transparent" dragged over 600 px: alpha 255 / 179 / 100 / 35 / 0 at 50 / 250 / 400 / 550 / 750
/// (#12010). The same ramp as an sRGB grey (`y` encoded with the sRGB curve) gives 30 at the dark
/// end, 5 levels off, where the 2.2 power gives 35.
const SMOOTH_OPACITY_GAMMA: f32 = 2.2;
/// Smooth's transparency ramp: each opacity stop is a grey whose Oklab lightness is
/// `(opacity^2.2)^(1/3)`, which the colours' measured Smooth easing ([`SMOOTH_EASE`]) crosses
/// segment by segment, and the linear value `y = L^3` comes out as opacity `y^(1/2.2)`. Measured
/// in the Gradient tool at 100 % Smoothness with 50 % midpoints, the only case that uses it.
/// Constant opacity comes back as it is, clamped to 0..=1.
pub fn bake_smooth_opacity(stops: Vec<(f32, f32)>, midpoints: &[f32]) -> Vec<(f32, f32)> {
let clamp = |o: f32| if o.is_finite() { o.clamp(0.0, 1.0) } else { 1.0 };
if stops.len() < 2 || stops.windows(2).all(|w| w[0].1 == w[1].1) {
return stops.into_iter().map(|(t, o)| (t, clamp(o))).collect();
}
let mut s = stops;
s.sort_by(|a, b| a.0.total_cmp(&b.0));
let pts: Vec<(f32, [f32; 3])> = s.iter().map(|(t, o)| (*t, [clamp(*o).powf(SMOOTH_OPACITY_GAMMA).cbrt(); 3])).collect();
const N: usize = 96;
let mut baked: Vec<(f32, f32)> = (0..=N)
.map(|k| {
let t = k as f32 / N as f32;
let l = eval(&pts, midpoints, 0.0, t, Method::Smooth)[0];
(t, if l.is_finite() { l.clamp(0.0, 1.0).powi(3).powf(1.0 / SMOOTH_OPACITY_GAMMA) } else { 1.0 })
})
.collect();
baked.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-6);
baked
}
#[cfg(test)]
mod tests {
use super::*;
@@ -426,6 +458,14 @@ mod tests {
assert!((at(&s, 0.25)[0] - 0.5).abs() < 0.01);
}
#[test]
fn smooth_opacity_clamps_constant_stops() {
let flat = vec![(0.0, 0.4), (1.0, 0.4)];
assert_eq!(bake_smooth_opacity(flat.clone(), &[0.5]), flat);
assert_eq!(bake_smooth_opacity(vec![(0.0, 2.0), (1.0, 2.0)], &[0.5]), vec![(0.0, 1.0), (1.0, 1.0)]);
assert_eq!(bake_smooth_opacity(vec![(0.5, f32::NAN)], &[]), vec![(0.5, 1.0)]);
}
/// `eval` guards its own stops instead of relying on `bake`'s two-stop check.
#[test]
fn eval_with_fewer_than_two_stops_does_not_index_out_of_range() {
+1 -1
View File
@@ -53,7 +53,7 @@ mod flat;
pub mod gradient_bake;
pub mod guides_map;
mod png_steps;
pub use gradient_bake::{Method as GradientMethod, bake as bake_gradient};
pub use gradient_bake::{Method as GradientMethod, bake as bake_gradient, bake_smooth_opacity as bake_gradient_smooth_opacity};
mod duotone_map;
mod kra;
pub mod linked;
+17 -1
View File
@@ -420,7 +420,8 @@ pub fn live_from_vogk(data: &[u8]) -> Option<LiveShape> {
// Missing or invalid PSD arrow sizes must not prevent later edits.
let width = if width.is_finite() && width >= 1.0 { width } else { 52.0 };
let length = if length.is_finite() && length >= 1.0 { length } else { 50.0 };
let concavity = if concavity.is_finite() { concavity.clamp(0.0, 100.0) } else { 0.0 };
// Photoshop's range is -50..50 % (#13258): keep a negative value.
let concavity = if concavity.is_finite() { concavity.clamp(-50.0, 50.0) } else { 0.0 };
Some(LiveShape::ArrowLine { from, to, weight, start, end, width, length, concavity })
} else {
Some(LiveShape::Line { from, to, weight })
@@ -747,6 +748,21 @@ mod tests {
assert!(vogk_bytes(&LiveShape::Polygon { rect: [0.0; 4], sides: 5, star_ratio: 1.0, corner_radius: 0.0 }, 72.0).is_none());
}
/// A PSD arrow keeps a negative concavity, and one past 50 % opens clamped to 50 (#13258).
#[test]
fn vogk_arrow_concavity_keeps_negatives_and_clamps_to_fifty() {
let arrow =
|concavity| LiveShape::ArrowLine { from: [0.0, 10.0], to: [20.0, 0.0], weight: 3.0, start: false, end: true, width: 5.0, length: 10.0, concavity };
let read = |c| match live_from_vogk(&vogk_bytes(&arrow(c), 72.0).unwrap()) {
Some(LiveShape::ArrowLine { concavity, .. }) => concavity,
other => panic!("{other:?}"),
};
assert_eq!(read(-50.0), -50.0);
assert_eq!(read(-20.0), -20.0);
assert_eq!(read(80.0), 50.0);
assert_eq!(read(-90.0), -50.0);
}
#[test]
fn shape_blocks_keep_unchanged_and_regenerate_changed() {
let sh = ShapeLayer {
@@ -0,0 +1,171 @@
//! Free Transform stalls (#11103): two selected raster layers on a 24 MP document, one box.
//!
//! ```sh
//! cargo run --release -p photocraft-ui-egui --example free_transform_bench -- [--size 6000x4000] [--reps 9] [--steps 60]
//! ```
//!
//! - begin: Ctrl+T (`transform_tool::begin`) and the first preview frame, then Esc.
//! - drag update: one pointer move and the preview frame it draws. "scale" drags the bottom-right
//! handle towards the top-left corner, shrinking the box from 100 % to 20 % at 100 % view zoom,
//! so the scale crosses ½ and ¼ (new mip levels) mid-drag; "move" drags the box by its middle.
//!
//! CPU side only: the egui frame and the texture preparation it does, not GPU upload or
//! presentation. A helper thread's work (a mip level built off the UI thread) isn't counted.
use std::time::Instant;
use photocraft_ui_egui::canvas::{ToolEvent, ViewXform};
use photocraft_ui_egui::{PhotocraftApp, Services, transform_tool};
use serde_json::json;
fn arg(args: &[String], name: &str) -> Option<String> {
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1).cloned())
}
fn median(v: &[f64]) -> f64 {
let mut v = v.to_vec();
v.sort_by(f64::total_cmp);
v.get(v.len() / 2).copied().unwrap_or(0.0)
}
fn worst(v: &[f64]) -> f64 {
v.iter().copied().fold(0.0, f64::max)
}
/// The view the frames draw through: 100 %, the document centred in a 1600 × 1000 canvas.
fn view(w: u32, h: u32) -> ViewXform {
ViewXform {
rect: egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0)),
zoom: 1.0,
center: [w as f32 / 2.0, h as f32 / 2.0],
flip: false,
rotation: 0.0,
aspect: 1.0,
}
}
/// The texture size limit a desktop GPU reports (egui's default without a renderer is 2048,
/// which would shrink the preview to a fraction of the layer and hide the cost being measured).
const MAX_TEXTURE_SIDE: usize = 16384;
/// One frame drawing the open box's preview, in milliseconds.
fn frame(app: &PhotocraftApp, ctx: &egui::Context, xf: &ViewXform) -> f64 {
let input = egui::RawInput { screen_rect: Some(xf.rect), max_texture_side: Some(MAX_TEXTURE_SIDE), ..Default::default() };
let start = Instant::now();
let output = ctx.run_ui(input, |ui| transform_tool::draw_content(app, ui.painter(), xf));
let ms = start.elapsed().as_secs_f64() * 1e3;
drop(output);
ms
}
fn pointer(app: &mut PhotocraftApp, ev: ToolEvent) {
transform_tool::pointer(app, ev, egui::Modifiers::NONE);
}
fn main() {
let args: Vec<String> = std::env::args().collect();
let (w, h) =
arg(&args, "--size").and_then(|s| s.split_once('x').and_then(|(a, b)| Some((a.parse::<u32>().ok()?, b.parse::<u32>().ok()?)))).unwrap_or((6000, 4000));
let reps: usize = arg(&args, "--reps").and_then(|s| s.parse().ok()).unwrap_or(9).max(1);
let steps: usize = arg(&args, "--steps").and_then(|s| s.parse().ok()).unwrap_or(60).max(2);
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default());
app.run("file.new", json!({"width": w, "height": h, "background": "white"})).expect("new document");
// Two overlapping layers, each covering most of the canvas.
let (fw, fh) = (w * 2 / 3, h * 3 / 4);
let mut ids = Vec::new();
for (name, x, y, color) in [("A", 0, 0, "#c03020"), ("B", w - fw, h - fh, "#2050c0")] {
let id = app.run("layer.new.layer", json!({"name": name})).expect("new layer")["layer"].as_u64().unwrap_or(0);
app.run("layer.select", json!({"layer": id})).expect("select");
app.run("select.rect", json!({"x": x, "y": y, "width": fw, "height": fh})).expect("select.rect");
app.run("edit.fill", json!({"contents": "color", "color": color})).expect("fill");
app.run("select.deselect", json!({})).expect("deselect");
ids.push(id);
}
if let (Some(a), Some(b)) = (ids.first(), ids.get(1)) {
app.run("layer.select", json!({"layer": a})).expect("select A");
app.run("layer.select", json!({"layer": b, "mode": "add"})).expect("add B");
}
app.sync_views();
if let Some(v) = app.ui.views.first_mut() {
v.zoom = 1.0;
v.center = [w as f32 / 2.0, h as f32 / 2.0];
v.fit_pending = false;
}
let xf = view(w, h);
let ctx = egui::Context::default();
let _ = ctx.run_ui(egui::RawInput { max_texture_side: Some(MAX_TEXTURE_SIDE), ..Default::default() }, |_| {});
// Ctrl+T and its first preview frame.
let (mut begin, mut first, mut begin_total) = (Vec::new(), Vec::new(), Vec::new());
for _ in 0..reps {
let t0 = Instant::now();
transform_tool::begin(&mut app, &ctx).expect("Free Transform");
let opened = t0.elapsed().as_secs_f64() * 1e3;
let drawn = frame(&app, &ctx, &xf);
begin.push(opened);
first.push(drawn);
begin_total.push(opened + drawn);
transform_tool::cancel(&mut app);
}
// Drags: one pointer move + its frame per update.
let mut drag = |kind: &str| -> Vec<f64> {
transform_tool::begin(&mut app, &ctx).expect("Free Transform");
let _ = frame(&app, &ctx, &xf);
let q = app.ui.transform.as_ref().map(|t| t.quad).unwrap_or_default();
let (from, to) = if kind == "scale" {
// The bottom-right handle towards the top-left corner: 100 % → 20 %.
let (a, c) = (q[0], q[2]);
(c, [a[0] + 0.2 * (c[0] - a[0]), a[1] + 0.2 * (c[1] - a[1])])
} else {
let m = [(q[0][0] + q[2][0]) / 2.0, (q[0][1] + q[2][1]) / 2.0];
(m, [m[0] + 400.0, m[1] + 250.0])
};
pointer(&mut app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 });
let mut times = Vec::with_capacity(steps);
for s in 1..=steps {
let k = s as f64 / steps as f64;
let p = [from[0] + k * (to[0] - from[0]), from[1] + k * (to[1] - from[1])];
let t0 = Instant::now();
pointer(&mut app, ToolEvent::Move { x: p[0], y: p[1], pressure: 1.0 });
let moved = t0.elapsed().as_secs_f64() * 1e3;
times.push(moved + frame(&app, &ctx, &xf));
}
pointer(&mut app, ToolEvent::Up { x: to[0], y: to[1] });
transform_tool::cancel(&mut app);
times
};
let mut scale = Vec::new();
let mut moving = Vec::new();
for _ in 0..reps.min(3) {
scale.extend(drag("scale"));
moving.extend(drag("move"));
}
if let Some(out) = arg(&args, "--json") {
use photocraft_testkit::perf::{process_peak_rss_bytes, report, row, write_report};
let rss = photocraft_testkit::perf::current_rss_bytes().max(process_peak_rss_bytes());
let rows = vec![
row("Free Transform begin, 2 layers on 24 MP: Ctrl+T + first frame", &begin_total, rss, None),
row("Free Transform begin, 2 layers on 24 MP: Ctrl+T", &begin, rss, None),
row("Free Transform begin, 2 layers on 24 MP: first frame", &first, rss, None),
row("Free Transform drag update, 2 layers on 24 MP: scale through mip levels", &scale, rss, None),
row("Free Transform drag update, 2 layers on 24 MP: move", &moving, rss, None),
];
let rep = report("free_transform_bench", json!({"width": w, "height": h, "layers": 2, "reps": reps, "steps": steps}), rows, None);
if let Err(e) = write_report(&out, &rep) {
eprintln!("{e}");
}
}
println!("{w}×{h}, 2 layers, {reps} reps, {steps} steps per drag");
println!(
"begin: Ctrl+T {:.1} ms + first frame {:.1} ms = {:.1} ms (median; worst {:.1} ms)",
median(&begin),
median(&first),
median(&begin_total),
worst(&begin_total)
);
println!("drag update, scale 100 % → 20 %: median {:.2} ms, worst {:.2} ms", median(&scale), worst(&scale));
println!("drag update, move: median {:.2} ms, worst {:.2} ms", median(&moving), worst(&moving));
}
+32 -10
View File
@@ -189,15 +189,19 @@ pub(crate) fn is_gesture(tool: Tool, mods: egui::Modifiers) -> bool {
mods.shift && !mods.alt && !mods.ctrl && !mods.command && !mods.mac_cmd && !items(tool).is_empty()
}
/// Does a right-click with `mods` open the menu? The Shift gesture for every tool that has one,
/// and a plain right-click with the Eraser in Block mode, where the Brush Preset picker's Size and
/// Hardness mean nothing (#11937, as in the reference application).
/// A plain right-click opens it only where it would otherwise open the picker: with the Erase
/// preference it still erases.
pub(crate) fn opens_on(app: &PhotocraftApp, tool: Tool, mods: egui::Modifiers) -> bool {
/// Does a right-click with `mods` at document point `doc` open the menu? The Shift gesture for
/// every tool that has one, and a plain right-click with the Eraser in Block mode, where the Brush
/// Preset picker's Size and Hardness mean nothing (#11937), or with the Paint Bucket (#12530), as
/// in the reference application.
/// A plain right-click opens it only where it would otherwise open the picker or nothing: with the
/// Erase preference it still erases, and on the pasteboard its colour menu opens.
pub(crate) fn opens_on(app: &PhotocraftApp, tool: Tool, mods: egui::Modifiers, doc: Option<[f64; 2]>) -> bool {
let plain = !mods.shift && !mods.alt && !mods.ctrl && !mods.command && !mods.mac_cmd;
let block = tool == Tool::Eraser && app.ui.tool_options.eraser_mode == "block";
is_gesture(tool, mods) || (plain && block && !crate::paint_mouse::right_erases(app, tool))
let pasteboard = doc.is_some_and(|d| crate::canvas_tool_menu::pasteboard_at(app, tool, d));
// An open Free Transform box owns the plain right-click: its transform menu opens instead.
let bucket = tool == Tool::PaintBucket && app.ui.transform.is_none();
is_gesture(tool, mods) || (plain && (block || bucket) && !crate::paint_mouse::right_erases(app, tool) && !pasteboard)
}
/// The modifiers that decide a right-button gesture: the ones held when the button went down.
@@ -228,11 +232,25 @@ pub(crate) fn menu_id() -> Id {
Id::unique("canvas-brush-mode-menu")
}
/// Opens the active tool's menu at screen point `pos`.
pub(crate) fn open(app: &mut PhotocraftApp, ctx: &Context, pos: [f32; 2]) {
/// Temp data: was the open menu opened by a plain right-click (not the Shift gesture)?
fn plain_id() -> Id {
menu_id().with("plain")
}
/// The row drawn checked. The Paint Bucket's plain right-click menu checks none, as in the
/// reference application; its Shift+right-click menu checks the current mode.
pub(crate) fn checked(app: &PhotocraftApp, ctx: &Context, tool: Tool) -> Option<Item> {
let plain = ctx.data(|d| d.get_temp::<bool>(plain_id())).unwrap_or(false);
if plain && tool == Tool::PaintBucket { None } else { current(app, tool) }
}
/// Opens the active tool's menu at screen point `pos`, for a right-click with `mods`.
pub(crate) fn open(app: &mut PhotocraftApp, ctx: &Context, pos: [f32; 2], mods: egui::Modifiers) {
if !pos.iter().all(|v| v.is_finite()) || items(app.ui.tool).is_empty() {
return;
}
let plain = !is_gesture(app.ui.tool, mods);
ctx.data_mut(|d| d.insert_temp(plain_id(), plain));
// The checked row reads the tool's own brush.
crate::paint_mouse::sync_tool_brush(app);
app.ui.brush_picker = None;
@@ -378,7 +396,7 @@ pub(crate) fn show(app: &mut PhotocraftApp, ctx: &Context) {
crate::paint_mouse::sync_tool_brush(app);
let tool = app.ui.tool;
let rows: Vec<(Item, bool)> = items(tool).into_iter().map(|i| (i, enabled(app, i))).collect();
let current = current(app, tool);
let current = checked(app, ctx, tool);
let screen = crate::work_area::visible_rect(ctx);
let id = menu_id();
let margin = ctx.global_style().spacing.menu_margin.sum() + egui::Vec2::splat(2.0);
@@ -424,3 +442,7 @@ mod eraser_block_right_click_tests;
#[cfg(test)]
#[path = "pattern_stamp_behind_tests.rs"]
mod pattern_stamp_behind_tests;
#[cfg(test)]
#[path = "paint_bucket_right_click_menu_tests.rs"]
mod paint_bucket_right_click_menu_tests;
@@ -17,7 +17,7 @@ const CONTROLS: [(Role, &str, &str); 3] = [
];
/// Build a settled options-bar fixture with the requested tool, locale, viewport and scale.
fn bar(tool: Tool, lang: Lang, width: f32, scale: f32, narrow: bool) -> Harness<'static, PhotocraftApp> {
pub(super) fn bar(tool: Tool, lang: Lang, width: f32, scale: f32, narrow: bool) -> Harness<'static, PhotocraftApp> {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 80, "height": 80})).unwrap();
app.run("prefs.set", json!({"path": "workspace.enableNarrowOptionsBar", "value": narrow})).unwrap();
@@ -39,7 +39,7 @@ fn bar(tool: Tool, lang: Lang, width: f32, scale: f32, narrow: bool) -> Harness<
}
/// Find the named control by its accessibility role without matching tooltip labels.
fn control<'a>(h: &'a Harness<'static, PhotocraftApp>, role: Role, label: &str) -> egui_kittest::Node<'a> {
pub(super) fn control<'a>(h: &'a Harness<'static, PhotocraftApp>, role: Role, label: &str) -> egui_kittest::Node<'a> {
h.query_all_by_role(role).find(|n| n.accesskit_node().label().as_deref() == Some(label)).unwrap_or_else(|| panic!("missing {role:?} {label:?}"))
}
@@ -54,7 +54,7 @@ fn control_name(h: &Harness<'static, PhotocraftApp>, lang: Lang, role: Role, lab
}
/// Scroll a control into view, wait for its hover delay and assert the visible tooltip text.
fn hover(h: &mut Harness<'static, PhotocraftApp>, role: Role, label: &str, tip: &str) {
pub(super) fn hover(h: &mut Harness<'static, PhotocraftApp>, role: Role, label: &str, tip: &str) {
control(h, role, label).scroll_to_me();
h.run_steps(4);
let rect = control(h, role, label).rect();
+86 -1
View File
@@ -1021,7 +1021,7 @@ fn handle_primary_canvas_input(app: &mut PhotocraftApp, ui: &mut egui::Ui, view:
// Tools follow the left button; the right one opens the Brush Preset picker or erases
// (Preferences › Tools, `paint_mouse`).
crate::paint_mouse::sync_tool_brush(app);
let mut buttons = crate::paint_mouse::canvas_buttons(app, response, tool);
let mut buttons = crate::paint_mouse::canvas_buttons(app, response, tool, xf);
if input.menu_dismiss_press {
// Navigation and drags read `buttons` directly (zoom holds and drags, Rotate View):
// starve them. The release click stays armed, so the click handling below consumes
@@ -1276,6 +1276,7 @@ fn handle_canvas_tool_stroke(
if press_stroke || (strokes_live(tool) && (app.alt_sampling || app.mixer_sampling)) {
buttons.started = false;
}
let transform_press = transform_press_moves(app, ui, input, mods, buttons);
if buttons.started
&& !input.menu_dismiss_press
&& let Some(p) = ui.input(|i| i.pointer.press_origin()).filter(|p| rect.contains(*p)).or(response.interact_pointer_pos())
@@ -1413,6 +1414,90 @@ fn handle_canvas_tool_stroke(
if press_stroke && (app.drag.is_none() || !ui.input(|i| i.pointer.primary_down())) {
app.press_stroke = false;
}
if transform_press {
transform_press_release(app, ui, input, mods, buttons);
}
}
/// Marks a Free Transform drag started on the press (`transform_press_moves`).
fn transform_press_id(ctx: &egui::Context) -> egui::Id {
egui::Id::unique(("free-transform-press", ctx.viewport_id()))
}
/// An open Free Transform box follows the pointer from the press (#11103): the press goes to the
/// box at once and every move before egui recognises a drag (past its click distance) moves it,
/// so the box doesn't sit still and then jump to catch up. Warp keeps its own gesture. Returns
/// whether the current press started this way; the drag egui recognises later continues it.
fn transform_press_moves(
app: &mut PhotocraftApp,
ui: &egui::Ui,
input: &CanvasToolInput<'_>,
mods: egui::Modifiers,
buttons: &mut crate::paint_mouse::Buttons,
) -> bool {
let ctx = input.ctx;
let id = transform_press_id(ctx);
let view = Some(tool_input::ToolViewContext::new(input.xf, Some(ctx.viewport_id())));
let open = input.transform_owns_pointer && app.ui.transform.as_ref().is_some_and(|t| t.warp.is_none());
if open
&& !input.menu_dismiss_press
&& !input.under_dialog
&& input.response.is_pointer_button_down_on()
&& ui.input(|i| i.pointer.primary_pressed())
&& let Some(p) = ui.input(|i| i.pointer.press_origin()).filter(|p| input.rect.contains(*p))
{
let d = input.xf.to_doc(p);
let press_mods = ui.input(|i| pointer_button_modifiers(&i.events, PointerButton::Primary)).unwrap_or(mods);
tool_input::tool_event_with_view(app, ToolEvent::Down { x: d[0], y: d[1], pressure: app.stylus.pressure() }, press_mods, view);
ctx.data_mut(|m| m.insert_temp(id, true));
}
let pressed = ctx.data(|m| m.get_temp::<bool>(id)).unwrap_or(false);
if !pressed {
return false;
}
// The press already went to the box: the recognised drag continues it, it doesn't start over.
buttons.started = false;
let moved = ui.input(|i| i.pointer.primary_down() && i.pointer.delta() != egui::Vec2::ZERO);
if moved
&& !buttons.dragged
&& !buttons.stopped
&& let Some(p) = ui.input(|i| i.pointer.latest_pos())
{
let d = input.xf.to_doc(p);
tool_input::tool_event_with_view(app, ToolEvent::Move { x: d[0], y: d[1], pressure: app.stylus.pressure() }, mods, view);
}
true
}
/// Ends a Free Transform press that egui never recognised as a drag: its release is the gesture's
/// `Up` (a click outside the box still accepts or keeps it), not a second click-sized `Down`/`Up`.
fn transform_press_release(
app: &mut PhotocraftApp,
ui: &egui::Ui,
input: &CanvasToolInput<'_>,
mods: egui::Modifiers,
buttons: &mut crate::paint_mouse::Buttons,
) {
let ctx = input.ctx;
if !buttons.stopped && ui.input(|i| i.pointer.primary_released()) {
buttons.clicked = false;
if app.ui.transform.is_some()
&& let Some(p) = input.response.interact_pointer_pos().or(ui.input(|i| i.pointer.latest_pos()))
{
let d = input.xf.to_doc(p);
tool_input::tool_event_with_view(
app,
ToolEvent::Up { x: d[0], y: d[1] },
mods,
Some(tool_input::ToolViewContext::new(input.xf, Some(ctx.viewport_id()))),
);
}
}
if app.ui.transform.is_none() || !ui.input(|i| i.pointer.primary_down()) {
// The id first: reading the viewport inside `data_mut` would wait on its own lock.
let id = transform_press_id(ctx);
ctx.data_mut(|m| m.remove::<bool>(id));
}
}
/// Dispatches discrete pointer click and release events to active tools with view transform context.
@@ -105,7 +105,9 @@ fn shift_click_still_connects_brush_pencil_history_brush_and_other_painting_tool
tool_event(&mut app, ToolEvent::Up { x: 20.0, y: 40.0 }, none);
tool_event(&mut app, ToolEvent::Down { x: 120.0, y: 40.0, pressure: 1.0 }, shift);
tool_event(&mut app, ToolEvent::Up { x: 120.0, y: 40.0 }, shift);
assert_eq!(last_points(&app, cmd), vec![[20.0, 40.0], [120.0, 40.0]], "{tool:?}");
// The Pencil's 1 px tip paints whole pixels, so its points sit on pixel centres (#12200).
let want = if tool == Tool::Pencil { vec![[20.5, 40.5], [120.5, 40.5]] } else { vec![[20.0, 40.0], [120.0, 40.0]] };
assert_eq!(last_points(&app, cmd), want, "{tool:?}");
assert!(red(&app, 70, 40) > 0.9, "{tool:?} painted the connecting line midpoint");
}
}
@@ -1114,7 +1114,9 @@ pub fn open_pasteboard(app: &mut PhotocraftApp, ctx: &Context, tool: Tool, pos:
transform: false,
pasteboard: true,
anchor: None,
under: None,
// Space's Hand keeps the menu over the selected tool (#11271); a held zoom key's goes with
// the key, as before.
under: (tool == Tool::Hand && tool != app.ui.tool).then_some(app.ui.tool),
text: false,
type_layer: false,
type_shape: None,
+15 -6
View File
@@ -34,11 +34,12 @@ pub(crate) fn pencil_tip_is_round(size: f32) -> bool {
(h - 0.5) * std::f32::consts::SQRT_2 > h
}
/// Whether a brush-tip circle draws its centre mark.
/// Clone Stamp and Healing Brush stay an empty circle until Option is held, the source-point
/// cursor. Other brushes follow Preferences › Cursors › Show Crosshair in Brush Tip, as in
/// Photoshop; the Background Eraser always shows its sampling hotspot, and the Remove tool its
/// centre + (#12550).
/// Whether a brush-tip circle draws its centre mark, for Normal and Full Size Brush Tip cursors
/// alike (both draw through this). Quick Selection never draws one. Clone Stamp and Healing Brush
/// stay an empty circle until Option is held, the source-point cursor. Other brushes follow
/// Preferences › Cursors › Show Crosshair in Brush Tip, as in Photoshop; the Background Eraser
/// and the Color Replacement tool (#11934) always show their sampling hotspot, and the Remove
/// tool its centre + (#12550).
pub(super) fn brush_tip_centre(tool: Tool, option: bool, show_crosshair: bool) -> bool {
if tool == Tool::QuickSelection {
return false;
@@ -46,7 +47,7 @@ pub(super) fn brush_tip_centre(tool: Tool, option: bool, show_crosshair: bool) -
if matches!(tool, Tool::CloneStamp | Tool::Healing) {
return option || show_crosshair;
}
show_crosshair || matches!(tool, Tool::BackgroundEraser | Tool::Remove)
show_crosshair || matches!(tool, Tool::BackgroundEraser | Tool::ColorReplacement | Tool::Remove)
}
/// The display colour of an RGB triple (0..1 per channel) as an egui colour.
@@ -413,6 +414,10 @@ pub(crate) fn alt_picks(tool: Tool, mods: egui::Modifiers) -> bool {
#[path = "../eyedropper_mask_sample_tests.rs"]
mod eyedropper_mask_sample_tests;
#[cfg(test)]
#[path = "../color_replacement_cursor_tests.rs"]
mod color_replacement_cursor_tests;
#[cfg(test)]
#[path = "../color_replacement_alt_click_tests.rs"]
mod color_replacement_alt_click_tests;
@@ -424,3 +429,7 @@ mod background_eraser_alt_click_tests;
#[cfg(test)]
#[path = "remove_cursor_tests.rs"]
mod remove_cursor_tests;
#[cfg(test)]
#[path = "paint_bucket_cursor_tests.rs"]
mod paint_bucket_cursor_tests;
+1 -1
View File
@@ -173,7 +173,7 @@ fn finish(app: &mut PhotocraftApp, mut d: Drag, click: Option<bool>) {
if made.is_ok() && d.tool != Tool::Lasso {
crate::retouch_ui::patch_hint(app);
}
} else if app.session.is_enabled("select.deselect") {
} else if (d.tool != Tool::Lasso || selection_mode(app, d.modifiers) == "replace") && app.session.is_enabled("select.deselect") {
let _ = app.run("select.deselect", json!({}));
}
}
@@ -0,0 +1,103 @@
//! The Paint Bucket cursor (#12539): with Standard Other Cursors it is the bucket with a small
//! arrow at its top left, the hotspot on the arrow tip, and a click fills the pixel under that tip.
//! Precise Other Cursors and Caps Lock keep the crosshair; ⌥ and ⌘ keep the Eyedropper and Move
//! cursors. Tests drive the real canvas (`document_area`) and read the OS cursor bitmap it sets.
use egui::{CursorIcon, Modifiers};
use egui_kittest::Harness;
use serde_json::json;
use super::remove_cursor_tests::{Cursor, cursor, harness, set_pref};
use crate::PhotocraftApp;
use crate::state::Tool;
/// The cursor with `mods` held over the canvas centre.
fn cursor_with(h: &mut Harness<'_, PhotocraftApp>, mods: Modifiers) -> Cursor {
let p = h.state().last_canvas_rect.center();
h.event(egui::Event::ModifiersChanged(mods));
h.event(egui::Event::PointerMoved(p));
h.run_steps(3);
cursor(h)
}
fn pixel(app: &PhotocraftApp, x: i32, y: i32) -> [u8; 3] {
let st = app.session.active().unwrap();
let c = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y);
[0, 1, 2].map(|i| (c[i] * 255.0).round() as u8)
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn the_standard_cursor_is_the_bucket_with_the_arrow_tip_on_the_hotspot() {
let h = harness(Tool::PaintBucket);
let (icon, image) = cursor(&h);
assert_eq!(icon, CursorIcon::Crosshair, "the OS bitmap keeps its visible fallback");
let (size, [x, y], rgba) = image.expect("the Paint Bucket's OS cursor bitmap");
assert_eq!([x, y], [1, 1], "the hotspot is the arrow tip at the bitmap's top left");
let at = |x: u16, y: u16| {
let i = (usize::from(y) * usize::from(size[0]) + usize::from(x)) * 4;
[rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]]
};
// The tip sits on the hotspot texel's centre, so that pixel is antialiased, not solid.
assert!(at(x, y)[3] > 128, "the tip itself is drawn: no open crosshair centre under the pointer");
let body = at(x + 1, y + 4);
assert!(body[3] > 230 && body[0] < 40, "a black arrow runs down from the tip: {body:?}");
let bucket = (0..size[1]).flat_map(|row| (0..size[0]).map(move |col| (col, row))).any(|(col, row)| {
let p = at(col, row);
col > x + 10 && row > y + 10 && p[0] > 200 && p[3] > 200
});
assert!(bucket, "the white bucket art sits below right of the arrow");
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn a_click_fills_the_pixel_under_the_arrow_tip() {
let mut h = harness(Tool::PaintBucket);
let p = h.state().last_canvas_rect.center();
let (x, y) = crate::panels::info::hover_pixel(h.state()).expect("the pointer is over the image");
// Black left of and above the pointer's pixel: a fill there stops at the edges, a fill one
// pixel off to the left or up would turn the black red.
let app = h.state_mut();
for rect in [[0, 0, x, 300], [0, 0, 400, y]] {
app.run("select.rect", json!({"x": rect[0], "y": rect[1], "width": rect[2], "height": rect[3]})).unwrap();
app.run("edit.fill", json!({"contents": "color", "color": "#000000"})).unwrap();
}
app.run("select.deselect", json!({})).unwrap();
app.run("tools.setColors", json!({"foreground": "#ff0000"})).unwrap();
h.run_steps(2);
for pressed in [true, false] {
h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
h.run_steps(2);
}
assert_eq!(pixel(h.state(), x, y), [255, 0, 0], "the pixel under the tip is filled");
assert_eq!(pixel(h.state(), x - 1, y), [0, 0, 0], "the pixel left of it is not");
assert_eq!(pixel(h.state(), x, y - 1), [0, 0, 0], "the pixel above it is not");
}
#[test]
fn precise_other_cursors_and_caps_lock_keep_the_crosshair() {
let mut h = harness(Tool::PaintBucket);
let standard = cursor(&h);
set_pref(&mut h, "cursors.other", json!("precise"));
let precise = cursor(&h);
assert_eq!(precise.0, CursorIcon::Crosshair, "Precise: the crosshair");
assert_ne!(precise, standard, "Precise: not the bucket");
set_pref(&mut h, "cursors.other", json!("standard"));
h.state_mut().caps_lock = true;
h.run_steps(2);
assert_eq!(cursor(&h), precise, "Caps Lock: the same crosshair");
}
#[test]
fn alt_and_command_keep_the_eyedropper_and_move_cursors() {
let mut bucket = harness(Tool::PaintBucket);
let standard = cursor(&bucket);
let eyedropper = cursor(&harness(Tool::Eyedropper));
let alt = cursor_with(&mut bucket, Modifiers::ALT);
assert_eq!(alt, eyedropper, "⌥: the Eyedropper cursor");
assert_ne!(alt, standard);
let mv = cursor_with(&mut harness(Tool::Move), Modifiers::NONE);
let command = cursor_with(&mut bucket, Modifiers::COMMAND);
assert_eq!(command, mv, "⌘: the Move cursor");
assert_ne!(command, standard);
}
+33 -12
View File
@@ -40,18 +40,27 @@ 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): its Opacity is its own.
// 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 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).
None if matches!(tool, Tool::BackgroundEraser | Tool::Healing | Tool::Burn | Tool::Dodge | Tool::Sponge | Tool::CloneStamp | Tool::Smudge) => {
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) },
None => {
let opacity = if tool == Tool::ArtHistoryBrush { BrushSettings::default().opacity } else { current.opacity };
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),
};
// The Remove tool starts at its measured 19 px; the rest is the current brush (#12548).
let size = if tool == Tool::Remove { REMOVE_TOOL_SIZE } else { current.size };
BrushSettings { smoothing: first_smoothing(), mode: photocraft_color::BlendMode::Normal, opacity, size, ..current }
BrushSettings { smoothing: first_smoothing(), mode: photocraft_color::BlendMode::Normal, opacity, flow, size, ..current }
}
};
// The picked preset was the outgoing tool's brush: forget it, so Update Brush can't overwrite
@@ -82,6 +91,9 @@ const BRUSH_TOOL_TIP: (f32, f32, f32) = (13.0, 0.0, 0.25);
const BACKGROUND_ERASER_TIP: (f32, f32, f32) = (13.0, 1.0, 0.25);
/// The Healing Brush's tip after Reset Tool (#12099): a 19 px hard round at 25 % spacing.
const HEALING_BRUSH_TIP: (f32, f32, f32) = (19.0, 1.0, 0.25);
/// The Pencil tool's starting and Reset Tool tip, as the reference measures it (#12200): size,
/// hardness and spacing of a 1 px hard round at 25 % spacing.
const PENCIL_TOOL_TIP: (f32, f32, f32) = (1.0, 1.0, 0.25);
/// The Burn, Dodge and Sponge tools' tip after Reset Tool (#12671, #12684, #13029): a 65 px soft
/// round at 25 % spacing.
const TONING_TOOL_TIP: (f32, f32, f32) = (65.0, 0.0, 0.25);
@@ -98,13 +110,15 @@ const SMUDGE_TOOL_TIP: (f32, f32, f32) = (13.0, 0.0, 0.25);
/// [`BRUSH_TOOL_TIP`], 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
/// tool's [`SMUDGE_TOOL_TIP`]; the other tools keep the default tip.
/// 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 {
let mut brush = BrushSettings { smoothing: first_smoothing(), ..BrushSettings::default() };
match tool {
Tool::Brush => (brush.size, brush.hardness, brush.spacing) = BRUSH_TOOL_TIP,
Tool::BackgroundEraser => (brush.size, brush.hardness, brush.spacing) = BACKGROUND_ERASER_TIP,
Tool::Healing => (brush.size, brush.hardness, brush.spacing) = HEALING_BRUSH_TIP,
Tool::Pencil => (brush.size, brush.hardness, brush.spacing) = PENCIL_TOOL_TIP,
Tool::Burn | Tool::Dodge | Tool::Sponge => (brush.size, brush.hardness, brush.spacing) = TONING_TOOL_TIP,
Tool::Smudge => (brush.size, brush.hardness, brush.spacing) = SMUDGE_TOOL_TIP,
Tool::CloneStamp => {
@@ -353,8 +367,9 @@ pub fn track_right_press_view(response: &Response, view: &crate::state::View, fl
/// Route the canvas response's buttons: the left one drives the tool; the right one resizes the
/// brush with Alt held (#297), erases (Erase preference) or opens the Brush Preset picker. Arms
/// `secondary_erase` or `brush_resize_armed` for this frame's `Down`.
pub fn canvas_buttons(app: &mut PhotocraftApp, response: &Response, tool: Tool) -> Buttons {
/// `secondary_erase` or `brush_resize_armed` for this frame's `Down`. `xf` is this canvas's view,
/// one cell of a Window › Arrange layout: it places a right-click on the image or the pasteboard.
pub fn canvas_buttons(app: &mut PhotocraftApp, response: &Response, tool: Tool, xf: &crate::canvas::ViewXform) -> Buttons {
if crate::brush_mode_menu::blocks_canvas(app, &response.ctx) {
app.secondary_erase = false;
return Buttons::default();
@@ -383,12 +398,13 @@ pub fn canvas_buttons(app: &mut PhotocraftApp, response: &Response, tool: Tool)
// ⌘/Ctrl+right-click lists the layers under the pointer instead (layer_pick_ui.rs, #307).
let layer_menu = crate::layer_pick_ui::is_gesture(tool, mods);
// Decided by the modifiers held when the button went down, not by those of the release frame that reports the click.
let mode_menu =
crate::brush_mode_menu::opens_on(app, tool, crate::workspace_ui::sticky_mods(app, crate::brush_mode_menu::gesture_mods(&response.ctx, mods)));
let menu_mods = crate::workspace_ui::sticky_mods(app, crate::brush_mode_menu::gesture_mods(&response.ctx, mods));
let menu_at = right_click_at(response);
let mode_menu = crate::brush_mode_menu::opens_on(app, tool, menu_mods, menu_at.map(|p| xf.to_doc(p)));
if mode_menu && !resizing && app.drag.is_none() {
app.secondary_erase = false;
if let Some(p) = right_click_at(response) {
crate::brush_mode_menu::open(app, &response.ctx, [p.x, p.y]);
if let Some(p) = menu_at {
crate::brush_mode_menu::open(app, &response.ctx, [p.x, p.y], menu_mods);
}
return Buttons {
started: response.drag_started_by(PointerButton::Primary),
@@ -461,10 +477,11 @@ pub fn pointer_secondary(app: &mut PhotocraftApp, ctx: &egui::Context, down: boo
app.brush_resize_armed = down && app.drag.is_none();
return true;
}
if crate::brush_mode_menu::opens_on(app, tool, mods) && app.drag.is_none() && app.brush_resize.is_none() {
// The control channel opens the pasteboard menu before it gets here (`secondary_canvas_menu_took`).
if crate::brush_mode_menu::opens_on(app, tool, mods, None) && app.drag.is_none() && app.brush_resize.is_none() {
app.secondary_erase = false;
if down {
crate::brush_mode_menu::open(app, ctx, at);
crate::brush_mode_menu::open(app, ctx, at, mods);
}
return false;
}
@@ -565,3 +582,7 @@ pub fn show_picker(app: &mut PhotocraftApp, ctx: &egui::Context) {
#[cfg(test)]
mod tests;
#[cfg(test)]
#[path = "../pencil_reset_defaults_tests.rs"]
mod pencil_reset_defaults_tests;
@@ -11,7 +11,7 @@ use crate::PhotocraftApp;
use crate::state::Tool;
/// The canvas at 100 % with `tool` and a 40 px tip, the pointer over its centre.
fn harness(tool: Tool) -> Harness<'static, PhotocraftApp> {
pub(super) fn harness(tool: Tool) -> Harness<'static, PhotocraftApp> {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.ui.tool = tool;
@@ -41,7 +41,7 @@ fn harness(tool: Tool) -> Harness<'static, PhotocraftApp> {
h
}
fn set_pref(h: &mut Harness<'_, PhotocraftApp>, path: &str, value: serde_json::Value) {
pub(super) fn set_pref(h: &mut Harness<'_, PhotocraftApp>, path: &str, value: serde_json::Value) {
h.state_mut().run("prefs.set", json!({"path": path, "value": value})).unwrap();
h.run_steps(2);
}
@@ -66,10 +66,10 @@ fn circle_drawn(h: &Harness<'_, PhotocraftApp>) -> bool {
}
/// A cursor icon, and its bitmap's size, hotspot and pixels.
type Cursor = (CursorIcon, Option<([u16; 2], [u16; 2], Vec<u8>)>);
pub(super) type Cursor = (CursorIcon, Option<([u16; 2], [u16; 2], Vec<u8>)>);
/// The cursor the canvas asks for this frame.
fn cursor(h: &Harness<'_, PhotocraftApp>) -> Cursor {
pub(super) fn cursor(h: &Harness<'_, PhotocraftApp>) -> Cursor {
let out = h.output();
let image = out.platform_output.cursor_image.as_ref().map(|i| (i.size, i.hotspot, i.rgba.to_vec()));
(out.platform_output.cursor_icon, image)
+8
View File
@@ -547,6 +547,14 @@ pub(super) fn live_stroke_busy(app: &PhotocraftApp) -> bool {
app.live_stroke.as_ref().is_some_and(|l| l.paint.busy())
}
impl PhotocraftApp {
/// Is the live stroke still painting, or holding steps the canvas hasn't shown yet? Lets a
/// test read the canvas only once what it shows is the whole stroke so far (#13477).
pub fn live_stroke_busy(&self) -> bool {
live_stroke_busy(self)
}
}
/// The points the live retouching stroke has rendered.
#[cfg(test)]
pub(crate) fn live_retouch_points(app: &PhotocraftApp) -> Option<Vec<photocraft_engine::paint::StrokePoint>> {
+1 -1
View File
@@ -152,7 +152,7 @@ pub(crate) fn count(ctx: &egui::Context, at: Pos2, kind: CountCursor) -> CursorI
CursorIcon::Default
}
/// The bucket artwork and its exact fill crosshair move as one native cursor or painted image.
/// The bucket artwork and the arrow on its fill target move as one native cursor or painted image.
pub(crate) fn bucket(painter: &Painter, at: Pos2) -> Result<CursorIcon, String> {
bucket::show(painter, at)
}
+69 -22
View File
@@ -1,11 +1,23 @@
//! One image owns the bucket artwork and its lower-right fill target. Splitting those between
//! the frame and the OS pointer lets them drift apart whenever a frame arrives after the pointer.
//! One image owns the bucket artwork and the arrow at its top left whose tip is the fill target
//! (#12539). Splitting those between the frame and the OS pointer lets them drift apart whenever a
//! frame arrives after the pointer.
use super::{CursorIcon, CustomCursorImage, Painter, Pos2, native, native_scale};
use std::sync::Arc;
const SIZE: f32 = 22.0;
const HOT: egui::Vec2 = egui::vec2(26.0 / 24.0 * SIZE, 25.0 / 24.0 * SIZE);
/// The bucket icon's top-left corner, in points from the arrow tip.
const ICON: egui::Vec2 = egui::vec2(6.0, 6.0);
/// Our own small arrow, in points from its tip: the hotspot, so a click fills the pixel under it.
const ARROW: [egui::Vec2; 7] = [
egui::vec2(0.0, 0.0),
egui::vec2(0.0, 10.5),
egui::vec2(2.6, 8.2),
egui::vec2(4.3, 11.8),
egui::vec2(5.9, 11.1),
egui::vec2(4.2, 7.5),
egui::vec2(7.5, 7.5),
];
#[derive(Clone)]
struct Cached {
@@ -58,40 +70,75 @@ pub(super) fn rasterize(scale: f32) -> Result<CustomCursorImage, String> {
if !scale.is_finite() || scale <= 0.0 {
return Err(format!("Invalid Paint Bucket cursor scale: {scale}"));
}
// Round the hotspot itself, rather than the box, so it always lands on an exact bitmap pixel.
// Keep one logical pixel of the existing icon halo and its antialiasing fringe inside the box.
let margin = (scale + 1.0).ceil();
let hot = [(HOT.x * scale).round() + margin, (HOT.y * scale).round() + margin];
let cross = super::rasterize(&super::STANDARD_CROSSHAIR, scale).ok_or_else(|| format!("Paint Bucket crosshair does not fit a cursor at scale {scale}"))?;
let size = [hot[0] + f32::from(cross.size[0] - cross.hotspot[0]), hot[1] + f32::from(cross.size[1] - cross.hotspot[1])];
// The arrow's halo reaches one halo width above and left of its tip, so the tip lands on
// (1, 1) at 1x, as in the reference cursor. The bucket's halo and fringe get room below right.
let halo = scale.round();
let side = (SIZE * scale).round();
let icon_at = (ICON * scale).round() + egui::Vec2::splat(halo);
let size = [icon_at.x + side + halo + 1.0, icon_at.y + side + halo + 1.0];
if size.iter().any(|side| !side.is_finite() || *side > f32::from(super::MAX_SIDE)) {
return Err(format!("Paint Bucket cursor does not fit the platform bitmap limit at scale {scale}"));
}
let size = size.map(|side| side as u16);
let hotspot = hot.map(|coord| coord as u16);
let hotspot = [halo as u16; 2];
let mut pixels = vec![egui::Color32::TRANSPARENT; usize::from(size[0]) * usize::from(size[1])];
let icon = crate::icons::rasterize("paint-bucket", (SIZE * scale).round() as u32)?;
let margin = margin as i32;
let halo = scale.round() as i32;
// The same eight dark halo offsets and white SVG as icons::cursor, now in the image that
// also owns the crosshair. Color32 keeps composition premultiplied until the final upload.
for (dx, dy) in [(-1, 0), (1, 0), (0, -1), (0, 1), (-1, -1), (1, 1), (-1, 1), (1, -1), (0, 0)] {
let icon = crate::icons::rasterize("paint-bucket", side as u32)?;
let halo = halo as i32;
let (arrow_width, arrow) = arrow_mask(scale);
// The same eight dark halo offsets and white SVG as icons::cursor, then the arrow on top of
// the bucket: black on a white halo. Color32 keeps composition premultiplied until the upload.
const OFFSETS: [(i32, i32); 9] = [(-1, 0), (1, 0), (0, -1), (0, 1), (-1, -1), (1, 1), (-1, 1), (1, -1), (0, 0)];
for (dx, dy) in OFFSETS {
for (i, pixel) in icon.pixels.iter().enumerate() {
let x = (i % icon.size[0]) as i32 + margin + dx * halo;
let y = (i / icon.size[0]) as i32 + margin + dy * halo;
let x = (i % icon.size[0]) as i32 + icon_at.x as i32 + dx * halo;
let y = (i / icon.size[0]) as i32 + icon_at.y as i32 + dy * halo;
let color = if dx == 0 && dy == 0 { *pixel } else { egui::Color32::from_black_alpha((f32::from(pixel.a()) * 200.0 / 255.0).round() as u8) };
over(&mut pixels, size, x, y, color);
}
}
for (i, pixel) in cross.rgba.as_chunks::<4>().0.iter().enumerate() {
let x = (i % usize::from(cross.size[0])) as i32 + i32::from(hotspot[0]) - i32::from(cross.hotspot[0]);
let y = (i / usize::from(cross.size[0])) as i32 + i32::from(hotspot[1]) - i32::from(cross.hotspot[1]);
over(&mut pixels, size, x, y, egui::Color32::from_rgba_unmultiplied(pixel[0], pixel[1], pixel[2], pixel[3]));
for (dx, dy) in OFFSETS {
for (i, alpha) in arrow.iter().enumerate() {
let x = (i % arrow_width) as i32 + i32::from(hotspot[0]) + dx * halo;
let y = (i / arrow_width) as i32 + i32::from(hotspot[1]) + dy * halo;
let color = if dx == 0 && dy == 0 { egui::Color32::from_black_alpha(*alpha) } else { egui::Color32::from_white_alpha(*alpha) };
over(&mut pixels, size, x, y, color);
}
}
let rgba = pixels.into_iter().flat_map(|pixel| pixel.to_srgba_unmultiplied()).collect::<Vec<_>>();
Ok(CustomCursorImage { rgba: Arc::from(rgba), size, hotspot })
}
/// The arrow's coverage per physical pixel, its tip at the centre of pixel (0, 0), the texel
/// centre the painted fallback puts on the pointer: the mask's width and its alpha values, row by row.
fn arrow_mask(scale: f32) -> (usize, Vec<u8>) {
const SAMPLES: u16 = 4;
let extent = ARROW.iter().fold(egui::Vec2::ZERO, |extent, point| extent.max(*point)) * scale + egui::Vec2::splat(0.5);
let (width, height) = (extent.x.ceil() as usize, extent.y.ceil() as usize);
let mut mask = Vec::with_capacity(width * height);
for y in 0..height {
for x in 0..width {
let mut hits = 0_u16;
for sy in 0..SAMPLES {
for sx in 0..SAMPLES {
let sample = egui::vec2(x as f32 + (f32::from(sx) + 0.5) / f32::from(SAMPLES), y as f32 + (f32::from(sy) + 0.5) / f32::from(SAMPLES));
hits += u16::from(inside((sample - egui::Vec2::splat(0.5)) / scale, &ARROW));
}
}
mask.push((f32::from(hits) * 255.0 / f32::from(SAMPLES * SAMPLES)).round() as u8);
}
}
(width, mask)
}
/// Even-odd point in polygon.
fn inside(point: egui::Vec2, polygon: &[egui::Vec2]) -> bool {
let next = polygon.iter().skip(1).chain(polygon.first());
polygon.iter().zip(next).fold(false, |inside, (a, b)| {
let crosses = (a.y > point.y) != (b.y > point.y) && point.x < (b.x - a.x) * (point.y - a.y) / (b.y - a.y) + a.x;
inside != crosses
})
}
fn over(pixels: &mut [egui::Color32], size: [u16; 2], x: i32, y: i32, foreground: egui::Color32) {
if x < 0 || y < 0 || x >= i32::from(size[0]) || y >= i32::from(size[1]) {
return;
+7 -29
View File
@@ -10,11 +10,6 @@ fn alpha(image: &CustomCursorImage, x: u16, y: u16) -> u8 {
image.rgba[(usize::from(y) * usize::from(image.size[0]) + usize::from(x)) * 4 + 3]
}
fn rgba_at(image: &CustomCursorImage, x: u16, y: u16) -> [u8; 4] {
let offset = (usize::from(y) * usize::from(image.size[0]) + usize::from(x)) * 4;
image.rgba[offset..offset + 4].try_into().unwrap()
}
fn frame(ctx: &egui::Context, draw: impl FnMut(&mut egui::Ui)) -> egui::FullOutput {
let mut output = ctx.run_ui(Default::default(), draw);
// These tests inspect cursor output without a renderer.
@@ -67,36 +62,19 @@ fn precise_and_tip_centre_crosshairs_have_distinct_hotspots() {
}
#[test]
fn bucket_bitmap_keeps_the_svg_above_left_of_its_exact_crosshair_hotspot() {
for scale in [1.0, 1.25, 2.0] {
fn bucket_bitmap_keeps_the_svg_below_right_of_its_arrow_tip_hotspot() {
for (scale, hotspot) in [(1.0, [1, 1]), (1.25, [1, 1]), (2.0, [2, 2])] {
let image = super::bucket::rasterize(scale).unwrap();
let expected_x = (26.0 / 24.0 * 22.0 * scale).round() + (scale + 1.0).ceil();
let expected_y = (25.0 / 24.0 * 22.0 * scale).round() + (scale + 1.0).ceil();
assert_eq!(image.hotspot, [expected_x as u16, expected_y as u16], "bucket box target at {scale}x");
let gradient_cross = rasterize(&STANDARD_CROSSHAIR, scale).unwrap();
assert_eq!(alpha(&image, image.hotspot[0], image.hotspot[1]), 0, "Gradient-style open center at {scale}x");
assert_eq!(image.hotspot, hotspot, "the arrow tip sits one halo in from the top left at {scale}x");
assert!(alpha(&image, image.hotspot[0], image.hotspot[1]) > 128, "the antialiased tip itself is drawn at {scale}x");
let side = usize::from(image.size[0]);
let has_bucket_art = image.rgba.as_chunks::<4>().0.iter().enumerate().any(|(i, p)| {
let x = (i % side) as u16;
let y = (i / side) as u16;
p[3] > 200 && x + 2 < image.hotspot[0] && y + 2 < image.hotspot[1]
p[0] > 200 && p[3] > 200 && x > image.hotspot[0] + 10 && y > image.hotspot[1] + 10
});
assert!(has_bucket_art, "opaque bucket art remains above-left of the hotspot at {scale}x");
for arm in [1, 5, 8] {
let arm = (arm as f32 * scale).round() as u16;
assert_eq!(
rgba_at(&image, image.hotspot[0] + arm, image.hotspot[1]),
rgba_at(&gradient_cross, gradient_cross.hotspot[0] + arm, gradient_cross.hotspot[1]),
"right arm matches the Gradient crosshair at {scale}x"
);
assert_eq!(
rgba_at(&image, image.hotspot[0], image.hotspot[1] + arm),
rgba_at(&gradient_cross, gradient_cross.hotspot[0], gradient_cross.hotspot[1] + arm),
"lower arm matches the Gradient crosshair at {scale}x"
);
}
assert!(has_bucket_art, "opaque white bucket art below-right of the hotspot at {scale}x");
}
}
@@ -196,7 +174,7 @@ fn scaled_wayland_bucket_uses_one_cached_image_area_without_a_split_crosshair()
let (first, first_images) = run(1.25, first_at);
assert!(first.platform_output.cursor_image.is_none(), "scaled Wayland does not send a bitmap to winit");
assert_eq!(first.platform_output.cursor_icon, CursorIcon::None, "the image replaces the system arrow");
assert_eq!(first_images.len(), 1, "bucket and fill crosshair are one Image primitive");
assert_eq!(first_images.len(), 1, "bucket and arrow are one Image primitive");
let image = super::bucket::rasterize(1.25).unwrap();
let image_bounds = first_images[0].1;
let image_hotspot = image_bounds.min + egui::vec2((f32::from(image.hotspot[0]) + 0.5) / 1.25, (f32::from(image.hotspot[1]) + 0.5) / 1.25);
@@ -0,0 +1,129 @@
//! In an Indexed Color document the Clone Stamp's Sample is greyed at Current Layer and a stroke
//! samples the current layer, whatever Sample held; the Normal Mode reads "Threshold". Opacity,
//! Flow and Aligned stay enabled, and RGB documents keep the list, the label and the Sample choice.
use egui::Modifiers;
use egui::accesskit::Role;
use egui_kittest::kittest::{NodeT, Queryable};
use egui_kittest::{Harness, Node};
use photocraft_doc::BlendMode;
use serde_json::{Value, json};
use crate::PhotocraftApp;
use crate::canvas::{ToolEvent, tool_event};
use crate::options_bar_mode_wheel_tests::{brush_mode, harness, mode_dropdown, wheel};
use crate::state::Tool;
/// The Clone Stamp in a new document, Sample set to All Layers; `indexed` converts it first.
fn bar(indexed: bool) -> Harness<'static, PhotocraftApp> {
let mut h = harness(Tool::CloneStamp);
let app = h.state_mut();
if indexed {
app.run("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none"})).unwrap();
}
app.ui.tool_options.clone_sample = "all".into();
h.run_steps(4);
h
}
/// The Sample dropdown: the one showing one of its choices.
fn sample<'a>(h: &'a Harness<'_, PhotocraftApp>) -> Node<'a> {
let choices = ["Current Layer", "Current & Below", "All Layers"];
h.query_all_by_role(Role::ComboBox).find(|n| n.value().is_some_and(|v| choices.contains(&v.as_str()))).expect("the Sample dropdown")
}
/// The options bar's field or checkbox named `name` ("Opacity:" in the Photoshop-look themes).
fn control<'a>(h: &'a Harness<'_, PhotocraftApp>, role: Role, name: &str) -> Node<'a> {
h.query_all_by_role(role).find(|n| n.accesskit_node().label().is_some_and(|l| l.trim_end_matches(':') == name)).unwrap_or_else(|| panic!("{name}"))
}
/// An Alt-click for the source, then a drag, through the canvas: the committed stroke's params.
fn clone_stroke(h: &mut Harness<'_, PhotocraftApp>) -> Value {
let app = h.state_mut();
tool_event(app, ToolEvent::Down { x: 40.0, y: 20.0, pressure: 1.0 }, Modifiers::ALT);
tool_event(app, ToolEvent::Up { x: 40.0, y: 20.0 }, Modifiers::ALT);
tool_event(app, ToolEvent::Down { x: 10.0, y: 30.0, pressure: 1.0 }, Modifiers::NONE);
tool_event(app, ToolEvent::Move { x: 30.0, y: 30.0, pressure: 1.0 }, Modifiers::NONE);
tool_event(app, ToolEvent::Up { x: 30.0, y: 30.0 }, Modifiers::NONE);
let (id, params) = app.session.journal.last().unwrap();
assert_eq!(id, "paint.cloneStamp", "{}", app.ui.status);
params.clone()
}
#[test]
fn in_an_indexed_document_sample_is_greyed_at_current_layer() {
let h = bar(true);
let node = sample(&h);
assert_eq!(node.value().as_deref(), Some("Current Layer"));
assert!(node.accesskit_node().is_disabled());
assert_eq!(h.state().ui.tool_options.clone_sample, "all", "the stored choice is kept");
}
#[test]
fn a_stroke_in_an_indexed_document_samples_the_current_layer() {
let mut h = bar(true);
let steps = h.state().session.active().unwrap().history.past_len();
assert_eq!(clone_stroke(&mut h)["sampleLayer"], "current");
assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1, "one Clone Stamp state");
}
fn shows(h: &Harness<'_, PhotocraftApp>, value: &str) -> bool {
h.query_all_by_role(Role::ComboBox).any(|n| n.value().as_deref() == Some(value))
}
#[test]
fn in_an_indexed_document_normal_reads_threshold_in_the_same_list() {
let mut h = bar(true);
assert_eq!(brush_mode(&h), BlendMode::Normal);
assert!(shows(&h, "Threshold"));
// The list itself is today's: the wheel steps on to Dissolve and back.
let at = h.query_all_by_role(Role::ComboBox).find(|n| n.value().as_deref() == Some("Threshold")).unwrap().rect().center();
wheel(&mut h, at, -1.0);
assert_eq!(brush_mode(&h), BlendMode::Dissolve);
assert!(shows(&h, "Dissolve"));
wheel(&mut h, at, 1.0);
assert_eq!(brush_mode(&h), BlendMode::Normal);
assert!(shows(&h, "Threshold"));
}
/// Other modes in Indexed Color weren't measured: they keep today's list.
#[test]
fn in_an_indexed_document_another_mode_keeps_the_list() {
let mut h = bar(true);
h.state_mut().session.tools.brush.mode = BlendMode::Dissolve;
h.run_steps(4);
assert!(shows(&h, "Dissolve"));
assert!(!shows(&h, "Threshold"));
}
#[test]
fn back_in_rgb_sample_shows_and_sends_the_stored_choice() {
let mut h = bar(true);
h.state_mut().run("image.mode.rgb", json!({})).unwrap();
h.run_steps(4);
let node = sample(&h);
assert_eq!(node.value().as_deref(), Some("All Layers"));
assert!(!node.accesskit_node().is_disabled());
assert_eq!(clone_stroke(&mut h)["sampleLayer"], "all");
}
#[test]
fn opacity_flow_and_aligned_stay_enabled_in_an_indexed_document() {
let h = bar(true);
for (role, name) in [(Role::SpinButton, "Opacity"), (Role::SpinButton, "Flow"), (Role::CheckBox, "Aligned")] {
assert!(!control(&h, role, name).accesskit_node().is_disabled(), "{name}");
}
}
#[test]
fn rgb_documents_keep_the_mode_list_and_the_sample_choice() {
let mut h = bar(false);
let node = sample(&h);
assert_eq!(node.value().as_deref(), Some("All Layers"));
assert!(!node.accesskit_node().is_disabled());
assert!(!shows(&h, "Threshold"));
let at = mode_dropdown(&h).center();
wheel(&mut h, at, -1.0);
assert_eq!(brush_mode(&h), BlendMode::Dissolve);
assert_eq!(clone_stroke(&mut h)["sampleLayer"], "all");
}
@@ -0,0 +1,40 @@
//! #11934: with Normal and Full Size Brush Tip cursors the Color Replacement cursor always draws
//! the centre +, its sampling hotspot, whatever Show Crosshair in Brush Tip says. Other brush
//! tools follow the preference, and Clone Stamp / Healing Brush keep their Alt behaviour.
use super::*;
#[test]
fn color_replacement_always_shows_its_centre() {
for show_crosshair in [false, true] {
for option in [false, true] {
assert!(brush_tip_centre(Tool::ColorReplacement, option, show_crosshair), "crosshair pref {show_crosshair}, Alt {option}");
}
}
}
#[test]
fn other_brush_tools_follow_the_preference() {
for tool in [Tool::Brush, Tool::Eraser, Tool::PatternStamp, Tool::Dodge, Tool::Pencil, Tool::Smudge] {
for option in [false, true] {
assert!(!brush_tip_centre(tool, option, false), "{tool:?} off, Alt {option}");
assert!(brush_tip_centre(tool, option, true), "{tool:?} on, Alt {option}");
}
}
for show_crosshair in [false, true] {
for option in [false, true] {
// The Background Eraser keeps its hotspot, as before; Quick Selection never has one.
assert!(brush_tip_centre(Tool::BackgroundEraser, option, show_crosshair));
assert!(!brush_tip_centre(Tool::QuickSelection, option, show_crosshair));
}
}
}
#[test]
fn clone_stamp_and_healing_keep_their_alt_behaviour() {
for tool in [Tool::CloneStamp, Tool::Healing] {
assert!(!brush_tip_centre(tool, false, false), "{tool:?}");
assert!(brush_tip_centre(tool, true, false), "{tool:?} with Alt");
assert!(brush_tip_centre(tool, false, true), "{tool:?} with the preference");
}
}
+3
View File
@@ -1273,6 +1273,9 @@ fn pointer(app: &mut PhotocraftApp, ctx: &egui::Context, p: &Value) -> Outcome {
};
if let Some(t) = parsed.tool {
crate::tool_memory::select(app, t);
// The tool's own brush now, not at the next frame, so a paint command right after uses
// it (the Pencil's 1 px tip, #12200; any tool's remembered brush).
crate::paint_mouse::sync_tool_brush(app);
}
// Space held: the Crop tool moves the frame being drawn, a marquee, lasso or shape
// being drawn moves instead of growing (hold_keys.rs). Like a modifier flag, it may be
+2 -1
View File
@@ -57,13 +57,14 @@ pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value {
use crate::brush_mode_menu as m;
let tool = app.ui.tool;
let current = m::current(app, tool);
let checked = m::checked(app, ctx, tool);
json!({
"pos": pos,
"tool": tool,
"mode": current.and_then(m::Item::label),
"choices": m::labels(tool),
"items": m::items(tool).into_iter().map(|i| match i.label() {
Some(label) => json!({"label": label, "enabled": m::enabled(app, i), "checked": Some(i) == current}),
Some(label) => json!({"label": label, "enabled": m::enabled(app, i), "checked": Some(i) == checked}),
None => json!({"separator": true}),
}).collect::<Vec<_>>(),
})
@@ -10,7 +10,7 @@ use crate::PhotocraftApp;
use crate::control::{ControlRequest, Outcome, handle};
use crate::state::Tool;
fn app(mode: &str) -> PhotocraftApp {
pub(super) fn app(mode: &str) -> PhotocraftApp {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 64, "height": 64, "background": "white"})).unwrap();
app.run("layer.new.layer", json!({})).unwrap();
@@ -21,7 +21,7 @@ fn app(mode: &str) -> PhotocraftApp {
app
}
fn call(app: &mut PhotocraftApp, ctx: &egui::Context, method: &str, params: Value) -> Value {
pub(super) fn call(app: &mut PhotocraftApp, ctx: &egui::Context, method: &str, params: Value) -> Value {
let (req, _rx) = ControlRequest::new(method, params);
match handle(app, ctx, &req) {
Outcome::Done(v) => v,
@@ -29,7 +29,7 @@ fn call(app: &mut PhotocraftApp, ctx: &egui::Context, method: &str, params: Valu
}
}
fn right_click(app: &mut PhotocraftApp, ctx: &egui::Context, modifiers: Value) {
pub(super) fn right_click(app: &mut PhotocraftApp, ctx: &egui::Context, modifiers: Value) {
call(
app,
ctx,
@@ -38,7 +38,7 @@ fn right_click(app: &mut PhotocraftApp, ctx: &egui::Context, modifiers: Value) {
);
}
fn steps(app: &PhotocraftApp) -> usize {
pub(super) fn steps(app: &PhotocraftApp) -> usize {
app.session.active().unwrap().history.past_len()
}
@@ -94,18 +94,7 @@ fn with_the_erase_preference_block_mode_still_erases() {
/// nothing is erased.
#[test]
fn a_real_right_click_opens_the_menu_and_escape_closes_it() {
let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut PhotocraftApp| {
let ctx = ui.ctx().clone();
if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {
return;
}
egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui));
},
app("block"),
);
crate::PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);
h.run_steps(4);
let mut h = harness(app("block"));
let n = steps(h.state());
let c = h.state().last_canvas_rect.center();
h.event(egui::Event::PointerMoved(c));
@@ -121,3 +110,20 @@ fn a_real_right_click_opens_the_menu_and_escape_closes_it() {
assert!(h.state().ui.brush_mode_menu.is_none(), "Escape closes it");
assert_eq!(steps(h.state()), n, "nothing erased");
}
/// The canvas alone, drawn by the real mouse path.
pub(super) fn harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> {
let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut PhotocraftApp| {
let ctx = ui.ctx().clone();
if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {
return;
}
egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui));
},
app,
);
crate::PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);
h.run_steps(4);
h
}
+111 -1
View File
@@ -782,7 +782,14 @@ fn tilde_held_with_the_brush_or_pencil_erases_with_its_brush() {
drag_with(&mut h, Modifiers::NONE, 110.0, 130.0, 150.0, 130.0);
key(&mut h, Key::Backtick, false, Modifiers::NONE);
assert_eq!(last_stroke_erases(&h), Some(true), "{tool:?}");
assert_eq!(rgba(&h, 130, 130)[3], 0.0, "{tool:?}: erased to transparency");
// `drag_with` bends through `(118, 136)` on the way from `(110, 130)` to `(150, 130)`,
// so the Pencil's 1 px tip (#12200) no longer reaches `(130, 130)`; check `(110, 130)`
// at the stroke start instead.
assert_eq!(rgba(&h, 110, 130)[3], 0.0, "{tool:?}: erased to transparency");
// The whole drag erases, not only its first dab: a 1 px Pencil line along the 40 px drag
// clears far more pixels than one dab.
let cleared = (100..160).flat_map(|x| (120..146).map(move |y| (x, y))).filter(|&(x, y)| rgba(&h, x, y)[3] == 0.0).count();
assert!(cleared >= 20, "{tool:?}: erased along the drag, {cleared} pixels");
assert_eq!(last_stroke(h.state())["mode"], json!("clear"), "{tool:?}");
assert_eq!(h.state().session.active().unwrap().history.undo_label(), Some(label));
assert_eq!(h.state().ui.tool, tool, "the tool stays");
@@ -1152,3 +1159,106 @@ fn command_or_alt_space_right_click_opens_no_view_menu() {
}
}
}
/// A right-click at `p` with Space already held (the Hand over the selected tool).
fn right_click_at(h: &mut Harness<'static, PhotocraftApp>, p: Pos2) {
h.event(Event::PointerMoved(p));
h.run_steps(1);
h.event(Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE });
h.run_steps(1);
h.event(Event::PointerButton { pos: p, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE });
h.run_steps(2);
}
/// A pending crop frame on the Crop tool, as the held-key test above sets one up.
fn with_pending_crop(h: &mut Harness<'static, PhotocraftApp>) -> [f64; 4] {
let frame = [100.0, 50.0, 300.0, 200.0];
h.state_mut().ui.crop_rect = Some(frame);
h.state_mut().crop.default_frame = false;
h.run_steps(2);
assert!(crate::crop_ui::pending(h.state()));
frame
}
/// The Space-Hand view menu over a pending crop (#11271): Esc closes only the menu and Enter
/// commits nothing, as under the crop's own menu; with the menu closed Esc discards the crop.
#[test]
fn space_hand_view_menu_keeps_escape_and_enter_from_the_pending_crop() {
let mut h = harness(Tool::Crop);
let frame = with_pending_crop(&mut h);
let size = h.state().session.active().map(|s| s.doc.size);
let steps = h.state().session.active().map(|s| s.history.past_len());
let p = screen(&h, 200.0, 125.0);
key(&mut h, Key::Space, true, Modifiers::NONE);
right_click_at(&mut h, p);
assert!(
h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.crop.is_none() && crate::canvas_tool_menu::is_view_tool(m.tool)),
"Space's Hand opens the view menu"
);
tap(&mut h, Key::Escape, Modifiers::NONE);
h.run_steps(2);
assert!(h.state().ui.canvas_tool_menu.is_none(), "Esc closes the menu");
assert_eq!(h.state().ui.crop_rect, Some(frame), "and only the menu: the crop is not discarded");
assert!(crate::crop_ui::pending(h.state()));
right_click_at(&mut h, p);
assert!(h.state().ui.canvas_tool_menu.is_some(), "the view menu opens again");
tap(&mut h, Key::Enter, Modifiers::NONE);
h.run_steps(2);
assert_eq!(h.state().session.active().map(|s| s.doc.size), size, "Enter under the menu doesn't crop");
assert_eq!(h.state().session.active().map(|s| s.history.past_len()), steps, "no history step");
assert_eq!(h.state().ui.crop_rect, Some(frame));
// Close the menu and let Space go: Esc discards the pending crop as ever.
h.state_mut().ui.canvas_tool_menu = None;
key(&mut h, Key::Space, false, Modifiers::NONE);
h.run_steps(3);
tap(&mut h, Key::Escape, Modifiers::NONE);
h.run_steps(2);
assert!(!crate::crop_ui::pending(h.state()), "with no menu open Esc discards the crop");
}
/// Only a plain Esc and Enter are the view menu's (#11271): Ctrl+Alt+Enter dispatches with the menu
/// open (it leaves the menu open), and Esc with a tool key in one pass closes the menu and picks
/// the tool.
#[test]
fn space_hand_view_menu_reserves_only_plain_escape_and_enter() {
let mut h = harness(Tool::Move);
let p = screen(&h, 200.0, 125.0);
key(&mut h, Key::Space, true, Modifiers::NONE);
right_click_at(&mut h, p);
assert!(h.state().ui.canvas_tool_menu.is_some(), "Space's Hand opens the view menu");
let mods = platform(Modifiers::COMMAND | Modifiers::ALT);
let steps = h.state().session.active().map(|s| s.history.past_len());
h.input_mut()
.events
.extend([Event::ModifiersChanged(mods), Event::Key { key: Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: mods }]);
h.run_steps(2);
h.event(Event::ModifiersChanged(Modifiers::NONE));
h.run_steps(1);
assert!(h.state().ui.canvas_tool_menu.is_some(), "a modified Enter leaves the menu open");
assert_eq!(h.state().session.active().map(|s| s.history.past_len()), steps, "and changes nothing");
h.input_mut().events.extend([
Event::Key { key: Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE },
Event::Key { key: Key::B, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE },
]);
h.run_steps(2);
assert!(h.state().ui.canvas_tool_menu.is_none(), "Esc closes the menu");
assert_eq!(h.state().ui.tool, Tool::Brush, "and B in the same pass still picks the Brush");
}
/// Space's Hand outside the image opens the pasteboard menu, which outlives the held Space and
/// closes when the tool underneath changes (#11271).
#[test]
fn space_hand_pasteboard_menu_opens_outside_the_image_and_outlives_space() {
let mut h = harness(Tool::Move);
let outside = screen(&h, -60.0, -60.0);
key(&mut h, Key::Space, true, Modifiers::NONE);
right_click_at(&mut h, outside);
assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.pasteboard), "Space's Hand opens the pasteboard menu outside");
assert_eq!(h.state().ui.tool, Tool::Move, "the Move tool stays selected");
key(&mut h, Key::Space, false, Modifiers::NONE);
h.run_steps(3);
assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.pasteboard), "the pasteboard menu outlives the held Space");
h.state_mut().ui.tool = Tool::Brush;
h.run_steps(2);
assert!(h.state().ui.canvas_tool_menu.is_none(), "another tool selected closes it");
}
+58
View File
@@ -534,6 +534,20 @@ fn preflight_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool {
if app.ui.canvas_tool_menu.as_ref().is_some_and(|m| m.text || m.crop.is_some()) {
return false;
}
// The Space-Hand view menu (the menu of a view tool opened over another tool, #11271) takes a
// plain Esc and ↵ too: they don't cancel or commit a pending crop under it. Esc closes the
// menu here and both keys are withheld from the dispatch below; every other key, modified ↵
// and tool keys included, dispatches as usual.
if app.ui.canvas_tool_menu.as_ref().is_some_and(|m| m.under.is_some() && crate::canvas_tool_menu::is_view_tool(m.tool)) {
let plain = |e: &egui::Event, k: egui::Key| matches!(e, egui::Event::Key { key, pressed: true, modifiers, .. } if *key == k && modifiers.is_none());
let (esc, enter) = ctx.input(|i| (i.events.iter().any(|e| plain(e, egui::Key::Escape)), i.events.iter().any(|e| plain(e, egui::Key::Enter))));
if esc {
app.ui.canvas_tool_menu = None;
}
if esc || enter {
ctx.input_mut(|i| i.events.retain(|e| !plain(e, egui::Key::Escape) && !plain(e, egui::Key::Enter)));
}
}
let symmetry_editing = app.ui.symmetry_transform.is_some();
crate::symmetry_ui::track(app, ctx);
if symmetry_editing && (app.ui.symmetry_transform.is_none() || egui::Popup::is_any_open(ctx)) {
@@ -910,6 +924,17 @@ fn handle_escape_and_view_keys(app: &mut PhotocraftApp, ctx: &egui::Context) {
|| ctx.any_popup_open()
|| ctx.data(|d| d.get_temp::<(egui::Id, egui::Rect)>(egui::Id::unique("tool-flyout")).is_some())
|| crate::panels::toolbar::more_flyout_open(ctx);
// Active operations and popups have already had priority. Reset a rotated view before
// idle Escape actions such as leaving full screen or deselecting; Rotate View handles its
// own Escape later, where it also clears an in-progress rotation drag.
if !esc_taken
&& let Some(view) = app.session.active_index().and_then(|i| app.ui.views.get_mut(i))
&& view.rotation != 0.0
&& pressed(Key::Escape)
{
view.rotation = 0.0;
return;
}
// Both full screen modes (with and without the menu bar) return to Standard, as in Photoshop
// (#4116), through the menu command so the window and the Screen Mode check follow.
if !esc_taken && app.ui.view.screen_mode != "standard" && pressed(Key::Escape) {
@@ -955,6 +980,39 @@ fn handle_escape_and_view_keys(app: &mut PhotocraftApp, ctx: &egui::Context) {
return;
}
}
// Path Selection (#13287): with components of the saved path targeted in the Paths panel
// selected, Esc deselects the components and keeps the path targeted and drawn, while a plain
// Enter deselects the components and also untargets the path (its Paths panel row and outline
// go). Neither adds a History step. Free Transform Path and ⌘↩ (Make Selection) took their
// keys earlier; with no component selected both keys keep today's behaviour. Not while the
// path's name is typed in the panel. Only the bare keys: `consume_key` would also take them with
// ⇧ or ⌥, which were not measured.
let bare = |k: Key| {
ctx.input_mut(|i| {
let n = i.events.len();
i.events.retain(|e| !matches!(e, egui::Event::Key { key, pressed: true, modifiers, .. } if *key == k && modifiers.is_none()));
i.events.len() != n
})
};
if !esc_taken
&& app.ui.tool == Tool::PathSelection
&& !crate::vector_ui::path_renaming(app, ctx)
&& let Some((index, _)) = crate::vector_ui::selected_saved_path_index(app)
&& let Some((crate::direct_select::PathRef::Saved(i), ..)) = crate::path_components::selected(app)
&& i == index
{
if bare(Key::Escape) {
crate::path_components::deselect_components(app);
return;
}
if bare(Key::Enter) {
crate::path_components::deselect_components(app);
if let Some(name) = app.ui.selected_path.clone() {
crate::vector_ui::deselect_loaded_path(app, &name);
}
return;
}
}
// + / − pick a Path Operation with the Pen tools and Path Selection (`path_components`)…
crate::path_components::handle_keys(app, ctx);
// … and otherwise ⇧+ / ⇧− step the blend mode and ⇧⌥ letters pick one (`blend_keys`). Before the
+28 -3
View File
@@ -1113,15 +1113,15 @@ fn paint_bucket_shows_a_bucket_cursor() {
let cursor = output.platform_output.cursor_image.as_ref().expect("native root viewport uses the unified bucket bitmap");
let [hot_x, hot_y] = cursor.hotspot;
let hot_pixel = (usize::from(hot_y) * usize::from(cursor.size[0]) + usize::from(hot_x)) * 4 + 3;
assert_eq!(cursor.rgba[hot_pixel], 0, "the Gradient-style crosshair leaves its exact bitmap hotspot open");
assert!(cursor.rgba[hot_pixel] > 128, "the arrow tip is drawn on the exact bitmap hotspot");
let side = usize::from(cursor.size[0]);
assert!(
cursor.rgba.as_chunks::<4>().0.iter().enumerate().any(|(i, pixel)| {
let x = (i % side) as u16;
let y = (i / side) as u16;
pixel[3] > 200 && x + 2 < hot_x && y + 2 < hot_y
pixel[3] > 200 && x > hot_x + 2 && y > hot_y + 2
}),
"the bucket artwork is opaque above-left of the same hotspot"
"the bucket artwork is opaque below-right of the same hotspot"
);
assert!(!cursor_area_visible(&h, "pc-icon-cursor"), "native cursor has no frame-painted icon overlay");
assert!(!cursor_area_visible(&h, "pc-tool-cursor"), "native cursor does not create a painted cursor Area");
@@ -1251,12 +1251,14 @@ fn hand_pointer_over_the_canvas_under_a_dialog() {
fn esc_ends_a_pen_path_and_keeps_it() {
let mut h = harness();
h.state_mut().ui.tool = crate::state::Tool::Pen;
h.state_mut().ui.views[0].rotation = 40.0;
let owner = crate::vector_ui::capture_pen_owner(h.state());
h.state_mut().ui.pen =
Some(crate::vector_ui::PenPath { knots: vec![[[50.0, 50.0]; 3], [[150.0, 50.0]; 3], [[150.0, 120.0]; 3]], owner, ..Default::default() });
h.key_press(Key::Escape);
h.run_steps(2);
assert!(h.state().ui.pen.is_none(), "the Pen leaves drawing state");
assert_eq!(h.state().ui.views[0].rotation, 40.0, "the active path owns Escape");
let doc = &h.state().session.active().unwrap().doc;
let path = doc.work_path.as_ref().expect("the path is kept as the work path");
assert_eq!(path.subpaths.len(), 1);
@@ -1295,6 +1297,27 @@ fn pen_shows_the_close_path_pointer_over_the_first_anchor() {
assert_eq!(pointer(&mut h, 50.0, 50.0), close, "back on the first anchor");
}
/// A rotated view takes the first idle Esc; the next retains normal deselection.
#[test]
fn escape_resets_rotation_before_idle_deselection_for_paint_tools() {
for tool in [crate::state::Tool::Brush, crate::state::Tool::Pencil] {
let mut h = harness();
h.state_mut().ui.tool = tool;
h.state_mut().ui.views[0].rotation = 40.0;
h.state_mut().run("select.all", json!({})).unwrap();
h.run_steps(1);
let history = h.state().session.active().unwrap().history.entries().len();
h.key_press(Key::Escape);
h.run_steps(2);
assert_eq!(h.state().ui.views[0].rotation, 0.0, "{tool:?}");
assert!(h.state().session.active().unwrap().doc.selection.is_some(), "first Esc keeps the selection");
assert_eq!(h.state().session.active().unwrap().history.entries().len(), history, "view reset is not an edit");
h.key_press(Key::Escape);
h.run_steps(2);
assert!(h.state().session.active().unwrap().doc.selection.is_none(), "second Esc deselects normally");
}
}
/// Esc with no active operation deselects (#2674), like ⌘D.
#[test]
fn escape_deselects_when_nothing_else_needs_cancelling() {
@@ -1318,11 +1341,13 @@ fn escape_deselects_when_nothing_else_needs_cancelling() {
fn escape_with_a_dialog_open_cancels_the_dialog_not_the_selection() {
let mut h = harness();
h.state_mut().run("select.all", json!({})).unwrap();
h.state_mut().ui.views[0].rotation = 40.0;
open_dialog(&mut h);
h.key_press(Key::Escape);
h.run_steps(2);
assert!(h.state().ui.dialogs.is_empty(), "Esc cancelled the dialog");
assert!(h.state().session.active().unwrap().doc.selection.is_some(), "the selection stays");
assert_eq!(h.state().ui.views[0].rotation, 40.0, "the dialog owns the first Esc");
}
/// The command palette owns Esc: it closes the palette and the selection stays.
+5
View File
@@ -879,6 +879,8 @@ mod transform_fx_tests;
#[cfg(test)]
mod transform_commit_click_tests;
#[cfg(test)]
mod transform_drag_start_tests;
#[cfg(test)]
mod layer_props_ui_tests;
@@ -1109,3 +1111,6 @@ mod sponge_default_tip_tests;
#[cfg(test)]
mod red_eye_context_menu_tests;
#[cfg(test)]
mod clone_stamp_indexed_bar_tests;
+3
View File
@@ -106,6 +106,9 @@ fn frame_convert_dialog(app: &mut PhotocraftApp, id: &str) -> Result<Value, Stri
fn invoke_early_commands(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option<Result<Value, String>> {
if let Some(tool) = crate::tool_shortcuts::tool(id) {
crate::tool_memory::select(app, tool);
// The tool's own brush now, not at the next frame, so a paint command right after uses
// it: a first Pencil pick its 1 px tip (#12200), any other tool its remembered brush.
crate::paint_mouse::sync_tool_brush(app);
return Some(Ok(json!({"tool": tool})));
}
if id == "layer.frame.convert" && params.as_object().is_none_or(|o| o.is_empty()) {
@@ -13,7 +13,7 @@ use crate::PhotocraftApp;
use crate::state::Tool;
/// The app with a new document and `tool` chosen.
fn harness(tool: Tool) -> Harness<'static, PhotocraftApp> {
pub(super) fn harness(tool: Tool) -> Harness<'static, PhotocraftApp> {
let mut h = Harness::builder().with_size(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());
@@ -26,12 +26,12 @@ fn harness(tool: Tool) -> Harness<'static, PhotocraftApp> {
}
/// The options bar's Mode dropdown: the highest one showing `Normal` (the Layers panel's is lower).
fn mode_dropdown(h: &Harness<'_, PhotocraftApp>) -> Rect {
pub(super) fn mode_dropdown(h: &Harness<'_, PhotocraftApp>) -> Rect {
h.query_all_by_role(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()
}
/// `lines` wheel lines at `at` in one event: negative is down.
fn wheel(h: &mut Harness<'_, PhotocraftApp>, at: Pos2, lines: f32) {
pub(super) fn wheel(h: &mut Harness<'_, PhotocraftApp>, at: Pos2, lines: f32) {
h.hover_at(at);
h.run_steps(1);
h.event(egui::Event::MouseWheel {
@@ -44,7 +44,7 @@ fn wheel(h: &mut Harness<'_, PhotocraftApp>, at: Pos2, lines: f32) {
h.run_steps(3);
}
fn brush_mode(h: &Harness<'_, PhotocraftApp>) -> BlendMode {
pub(super) fn brush_mode(h: &Harness<'_, PhotocraftApp>) -> BlendMode {
h.state().session.tools.brush.mode
}
@@ -127,6 +127,27 @@ fn the_pattern_stamp_mode_dropdown_has_behind() {
assert_eq!(h.state().ui.tool, Tool::PatternStamp);
}
/// The centre of a dropdown showing `value`.
fn combo(h: &Harness<'_, PhotocraftApp>, value: &str) -> Option<Pos2> {
h.query_all_by_role(Role::ComboBox).find(|n| n.value().as_deref() == Some(value)).map(|n| n.rect().center())
}
/// In an Indexed Color document the Pattern Stamp's Mode reads "Threshold" for Normal (#12887); the
/// other entries weren't measured there, so the list and the wheel stay as today.
#[test]
fn the_pattern_stamp_mode_reads_threshold_in_an_indexed_document() {
let mut h = harness(Tool::PatternStamp);
h.state_mut().run("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none"})).unwrap();
h.run_steps(4);
let at = combo(&h, "Threshold").expect("Mode reads Threshold");
wheel(&mut h, at, -1.0);
assert_eq!(brush_mode(&h), BlendMode::Dissolve);
assert!(combo(&h, "Dissolve").is_some() && combo(&h, "Threshold").is_none(), "Dissolve reads as itself");
wheel(&mut h, at, 1.0);
assert_eq!(brush_mode(&h), BlendMode::Normal);
assert!(combo(&h, "Threshold").is_some());
}
/// The Paint Bucket's Mode dropdown has Clear after Dissolve, as the Brush's does.
#[test]
fn the_paint_bucket_mode_dropdown_has_clear() {
@@ -0,0 +1,184 @@
//! #12530: with the Paint Bucket a plain right-click on the image opens its Mode list at the
//! pointer, the options bar's entries with none checked; picking one sets the Mode, adds no history
//! and fills nothing. The pasteboard keeps its colour menu, Shift+right-click keeps its checked
//! menu and other tools keep their right-click.
use egui::{Modifiers, PointerButton, Pos2};
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use photocraft_doc::BlendMode;
use serde_json::{Value, json};
use super::eraser_block_right_click_tests::{app, call, harness, right_click, steps};
use crate::PhotocraftApp;
use crate::state::Tool;
fn bucket() -> PhotocraftApp {
let mut app = app("brush");
app.ui.tool = Tool::PaintBucket;
app
}
/// The options bar's Mode list for the Paint Bucket, Clear included.
fn options_bar_modes() -> Vec<&'static str> {
crate::blend_keys::tool_modes(Tool::PaintBucket).unwrap().into_iter().map(|m| m.map_or("Clear", BlendMode::label)).collect()
}
fn checked_rows(inspect: &Value) -> Vec<Value> {
let items = inspect["result"]["brushModeMenu"]["items"].as_array().unwrap();
items.iter().filter(|i| i["checked"] == true).map(|i| i["label"].clone()).collect()
}
#[test]
fn a_plain_right_click_lists_the_options_bar_modes_with_none_checked() {
let ctx = egui::Context::default();
let mut app = bucket();
right_click(&mut app, &ctx, json!({}));
assert!(app.ui.brush_mode_menu.is_some(), "the Mode list opens");
assert!(app.ui.brush_picker.is_none() && app.ui.canvas_tool_menu.is_none());
let inspect = call(&mut app, &ctx, "ui.inspect", json!({}));
assert_eq!(inspect["result"]["brushModeMenu"]["choices"], json!(options_bar_modes()), "{inspect}");
assert_eq!(checked_rows(&inspect), Vec::<Value>::new(), "no entry is checked");
assert_eq!(inspect["result"]["brushModeMenu"]["mode"], "Normal", "the tool's mode is still reported");
}
#[test]
fn picking_an_entry_sets_the_mode_and_adds_no_history() {
let ctx = egui::Context::default();
let mut app = bucket();
let (n, journal) = (steps(&app), app.session.journal.len());
right_click(&mut app, &ctx, json!({}));
assert_eq!(call(&mut app, &ctx, "ui.context.choose", json!({"id": "Multiply"}))["ok"], true);
assert_eq!(app.ui.tool_options.bucket_blend_mode, BlendMode::Multiply);
assert!(!app.ui.tool_options.bucket_clear);
assert!(app.ui.brush_mode_menu.is_none());
assert_eq!((steps(&app), app.session.journal.len()), (n, journal), "nothing is filled");
}
#[test]
fn shift_right_click_still_checks_the_current_mode() {
let ctx = egui::Context::default();
let mut app = bucket();
app.ui.tool_options.bucket_blend_mode = BlendMode::Screen;
right_click(&mut app, &ctx, json!({"shift": true}));
let inspect = call(&mut app, &ctx, "ui.inspect", json!({}));
assert_eq!(checked_rows(&inspect), vec![json!("Screen")], "{inspect}");
}
#[test]
fn other_tools_keep_their_plain_right_click() {
let ctx = egui::Context::default();
for tool in [Tool::Brush, Tool::Pencil, Tool::CloneStamp, Tool::Gradient, Tool::Eraser] {
let mut app = bucket();
app.ui.tool = tool;
right_click(&mut app, &ctx, json!({}));
assert!(app.ui.brush_mode_menu.is_none(), "{tool:?}");
}
}
/// A real right-click at `at` with `mods` held.
fn mouse_right_click(h: &mut Harness<'static, PhotocraftApp>, at: Pos2, mods: Modifiers) {
h.event(egui::Event::ModifiersChanged(mods));
h.event(egui::Event::PointerMoved(at));
h.run_steps(1);
for pressed in [true, false] {
h.event(egui::Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed, modifiers: mods });
h.run_steps(2);
}
h.event(egui::Event::ModifiersChanged(Modifiers::NONE));
h.run_steps(1);
}
fn row_checked(h: &Harness<'static, PhotocraftApp>, label: &str) -> bool {
h.get_by_label(label).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True)
}
/// The real mouse: the menu opens at the pointer with no row checked; Escape and a click outside
/// close it without a change; a row sets the Mode. Nothing is filled.
#[test]
fn a_real_right_click_opens_the_unchecked_menu_at_the_pointer() {
let mut h = harness(bucket());
let (n, journal) = (steps(h.state()), h.state().session.journal.len());
let c = h.state().last_canvas_rect.center();
mouse_right_click(&mut h, c, Modifiers::NONE);
assert_eq!(h.state().ui.brush_mode_menu, Some([c.x, c.y]), "the menu at the pointer");
assert!(!row_checked(&h, "Normal"), "the current mode is not checked");
h.key_press(egui::Key::Escape);
h.run_steps(2);
assert!(h.state().ui.brush_mode_menu.is_none(), "Escape closes it");
mouse_right_click(&mut h, c, Modifiers::NONE);
let outside = c - egui::vec2(20.0, 0.0);
h.event(egui::Event::PointerMoved(outside));
for pressed in [true, false] {
h.event(egui::Event::PointerButton { pos: outside, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
h.run_steps(2);
}
assert!(h.state().ui.brush_mode_menu.is_none(), "a click outside closes it");
assert_eq!(h.state().ui.tool_options.bucket_blend_mode, BlendMode::Normal);
mouse_right_click(&mut h, c, Modifiers::NONE);
h.get_by_label("Multiply").click();
h.run_steps(2);
assert_eq!(h.state().ui.tool_options.bucket_blend_mode, BlendMode::Multiply);
assert!(h.state().ui.brush_mode_menu.is_none());
assert_eq!((steps(h.state()), h.state().session.journal.len()), (n, journal), "nothing is filled");
}
#[test]
fn a_real_shift_right_click_checks_the_current_mode() {
let mut h = harness(bucket());
let c = h.state().last_canvas_rect.center();
mouse_right_click(&mut h, c, Modifiers::SHIFT);
assert!(h.state().ui.brush_mode_menu.is_some());
assert!(row_checked(&h, "Normal"));
}
#[test]
fn a_real_right_click_on_the_pasteboard_opens_its_colour_menu() {
let mut h = harness(bucket());
let c = h.state().last_canvas_rect.center();
mouse_right_click(&mut h, c + egui::vec2(300.0, 0.0), Modifiers::NONE);
assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.pasteboard), "the pasteboard colour menu");
assert!(h.state().ui.brush_mode_menu.is_none(), "not the Mode list");
}
/// An open Free Transform box keeps its transform menu: the Mode list does not open over it.
#[test]
fn a_real_right_click_on_a_free_transform_box_opens_only_the_transform_menu() {
let mut app = bucket();
app.run("layer.new.layer", json!({})).unwrap();
app.run("select.rect", json!({"x": 4, "y": 6, "width": 10, "height": 8})).unwrap();
app.run("edit.fill", json!({"color": "#ff0000"})).unwrap();
app.run("select.deselect", json!({})).unwrap();
let mut h = harness(app);
let ctx = h.ctx.clone();
crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransform", json!({})).unwrap();
h.run_steps(2);
let c = h.state().last_canvas_rect.center();
mouse_right_click(&mut h, c, Modifiers::NONE);
assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.transform), "the transform menu");
assert!(h.state().ui.brush_mode_menu.is_none(), "not the Mode list");
}
/// Window › Arrange: each document's canvas is a cell, and a right-click is placed on the image or
/// the pasteboard by that cell's view, not by the whole work area's.
#[test]
fn arranged_cells_place_the_right_click_by_their_own_view() {
let mut h = harness(bucket());
h.state_mut().run("file.new", json!({"width": 64, "height": 64, "background": "white"})).unwrap();
h.state_mut().ui.view.arrange = "twoUpVertical".into();
h.run_steps(4);
let full = h.state().last_canvas_rect;
let active = h.state().session.active_index().unwrap();
let cell = crate::canvas::arranged_cells(h.state(), full).unwrap().into_iter().find(|(i, _)| *i == active).unwrap().1;
mouse_right_click(&mut h, cell.center(), Modifiers::NONE);
assert!(h.state().ui.brush_mode_menu.is_some(), "the image in the active cell: the Mode list");
assert!(h.state().ui.canvas_tool_menu.is_none());
h.key_press(egui::Key::Escape);
h.run_steps(2);
// The pasteboard at the cell's inner edge, where the whole work area's view has the image.
let edge = cell.clamp(full.center());
let pasteboard = edge + (cell.center() - edge).normalized() * 10.0;
mouse_right_click(&mut h, pasteboard, Modifiers::NONE);
assert!(h.state().ui.canvas_tool_menu.as_ref().is_some_and(|m| m.pasteboard), "the pasteboard colour menu");
assert!(h.state().ui.brush_mode_menu.is_none(), "not the Mode list");
}
+18 -4
View File
@@ -3,8 +3,19 @@ use super::{Align2, BlendMode, Color32, PhotocraftApp, Rect, Sense, Stroke, Stro
/// A painting tool's Mode dropdown over `modes` (`None` is Clear); the wheel over it steps the
/// mode. Returns the mode picked this frame. A list of every blend mode draws the Layers panel's
/// group lines (#5532; Clear starts none); a short one (the Healing Brush's) draws none.
pub(super) fn tool_mode_dropdown(ui: &mut egui::Ui, id: &str, modes: &[Option<BlendMode>], current: Option<BlendMode>) -> Option<Option<BlendMode>> {
let opts: Vec<(Option<BlendMode>, &str)> = modes.iter().map(|m| (*m, m.map_or("Clear", BlendMode::label))).collect();
/// `threshold` names Normal "Threshold", as the reference does in an Indexed Color document.
pub(super) fn tool_mode_dropdown(
ui: &mut egui::Ui,
id: &str,
modes: &[Option<BlendMode>],
current: Option<BlendMode>,
threshold: bool,
) -> Option<Option<BlendMode>> {
let label = |m: &Option<BlendMode>| match m {
Some(BlendMode::Normal) if threshold => tl!("Threshold"),
_ => m.map_or("Clear", BlendMode::label),
};
let opts: Vec<(Option<BlendMode>, &str)> = modes.iter().map(|m| (*m, label(m))).collect();
let grouped = BlendMode::LAYER_MODES.iter().all(|m| modes.contains(&Some(*m)));
let mut mode = current;
let chosen = widgets::dropdown_wheel_grouped(ui, id, tl!("Mode"), &mut mode, &opts, 96.0, |m| grouped && m.is_some_and(starts_blend_group)).0;
@@ -40,8 +51,11 @@ pub(super) fn paint_mode_dropdown(ui: &mut egui::Ui, id: &str, b: &mut photocraf
/// picking another mode leaves it. The wheel steps it as it steps the other Mode dropdowns.
/// 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();
pub(super) fn pattern_stamp_mode_dropdown(ui: &mut egui::Ui, id: &str, b: &mut photocraft_engine::BrushSettings, behind_enabled: bool, threshold: bool) {
let mut opts = crate::brush_mode_menu::pattern_stamp_choices();
if threshold && let Some(normal) = opts.iter_mut().find(|o| o.0 == (Some(BlendMode::Normal), false)) {
normal.1 = tl!("Threshold");
}
let before = if b.behind { (None, true) } else { (Some(b.mode), false) };
let mut mode = before;
let groups = |m: &(Option<BlendMode>, bool)| m.0.is_some_and(starts_blend_group);
+2 -2
View File
@@ -933,10 +933,10 @@ mod tests {
);
// The next live-property edit must still be accepted after resizing.
s.execute("shape.edit", json!({"layer": id.0, "arrowConcavity": 60.0})).unwrap();
s.execute("shape.edit", json!({"layer": id.0, "arrowConcavity": 40.0})).unwrap();
let layer = s.active().unwrap().doc.layer(id).unwrap();
let LayerContent::Shape(shape) = &layer.content else { panic!("expected shape layer") };
assert!(matches!(shape.live.as_ref(), Some(photocraft_doc::vector::LiveShape::ArrowLine { concavity, .. }) if (*concavity - 60.0).abs() < 1e-9));
assert!(matches!(shape.live.as_ref(), Some(photocraft_doc::vector::LiveShape::ArrowLine { concavity, .. }) if (*concavity - 40.0).abs() < 1e-9));
}
/// A stroked shape's Transform fields show its path, not the stroke's pixels, and a W edit
+24 -9
View File
@@ -148,19 +148,30 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
// Its list has Behind, greyed on the Background (#12879).
opt_label(ui, tl!("Mode"));
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);
// An Indexed Color document names Normal "Threshold" (#12887); the other
// entries weren't measured there.
let threshold = app.session.active().is_some_and(|st| st.doc.mode == photocraft_doc::ColorMode::Indexed);
super::brush_controls::pattern_stamp_mode_dropdown(ui, "retouch-mode", &mut brush, behind, threshold);
} else if let Some(modes) = crate::blend_keys::tool_modes(tool) {
opt_label(ui, tl!("Mode"));
if let Some(Some(m)) =
tool_mode_dropdown(ui, "retouch-mode", &modes, Some(crate::blend_keys::brush_tool_mode(tool, brush.mode)))
{
let mode = crate::blend_keys::brush_tool_mode(tool, brush.mode);
// Indexed Color names Normal "Threshold"; the other modes weren't measured.
let threshold = crate::retouch_ui::clone_stamp_indexed(app);
if let Some(Some(m)) = tool_mode_dropdown(ui, "retouch-mode", &modes, Some(mode), threshold) {
brush.mode = m;
}
}
if matches!(tool, Tool::CloneStamp | Tool::HistoryBrush) {
if matches!(tool, Tool::CloneStamp | Tool::PatternStamp | Tool::HistoryBrush) {
let width = if t.pro { 62.0 } else { 66.0 };
percent_field(ui, tl!("Opacity"), &mut brush.opacity, 1.0..=100.0, width);
percent_field(ui, tl!("Flow"), &mut brush.flow, 1.0..=100.0, width);
// The Pattern Stamp's are whole percents as measured; the Brush's tooltips (#12616).
let pattern = tool == Tool::PatternStamp;
let field = if pattern { whole_percent_field } else { percent_field };
let opacity = field(ui, tl!("Opacity"), &mut brush.opacity, 1.0..=100.0, width);
let flow = field(ui, tl!("Flow"), &mut brush.flow, 1.0..=100.0, width);
if pattern {
opacity.on_hover_text(tl!("Set opacity for stroke"));
flow.on_hover_text(tl!("Set flow rate for stroke"));
}
}
// Art History has no Mode (the engine paints Normal) and no Flow.
if tool == Tool::ArtHistoryBrush {
@@ -518,7 +529,7 @@ fn selection_specific_options(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool:
if let Some(modes) = crate::blend_keys::tool_modes(tool) {
let o = &mut app.ui.tool_options;
let current = if o.bucket_clear { None } else { Some(o.bucket_blend_mode) };
if let Some(m) = tool_mode_dropdown(ui, "bucket-mode", &modes, current) {
if let Some(m) = tool_mode_dropdown(ui, "bucket-mode", &modes, current, false) {
o.bucket_clear = m.is_none();
if let Some(m) = m {
o.bucket_blend_mode = m;
@@ -1014,7 +1025,7 @@ fn eraser_percent(ui: &mut egui::Ui, label: &str, value: &mut f32) -> bool {
}
/// Shows one of the range alerts as a modal with OK, once even if more than one pass asks.
fn range_alert(ui_state: &mut crate::state::UiState, text: &str) {
pub(crate) fn range_alert(ui_state: &mut crate::state::UiState, text: &str) {
let message = tl!(text).to_owned();
let shown =
ui_state.dialogs.iter().any(|d| d.kind == crate::state::DialogKind::Error && d.fields.get("message").and_then(|m| m.as_str()) == Some(&message));
@@ -1055,3 +1066,7 @@ mod sharpen_strength_alert_tests;
#[cfg(test)]
#[path = "../smudge_strength_alert_tests.rs"]
mod smudge_strength_alert_tests;
#[cfg(test)]
#[path = "../pattern_stamp_opacity_flow_tests.rs"]
mod pattern_stamp_opacity_flow_tests;
@@ -0,0 +1,177 @@
//! #12616: the Pattern Stamp's options bar has Opacity and Flow after Mode (whole percents 1..100,
//! default 100, the reference's tooltips, the Brush's silent clamp for a typed value past the
//! range), its strokes paint with them, live and committed alike, and Reset Tool puts both back
//! to 100.
use std::collections::BTreeSet;
use egui::accesskit::Role;
use egui::{Modifiers, Rect};
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::json;
use super::eraser_range_alert_tests::{alerts, bar, type_into};
use crate::PhotocraftApp;
use crate::canvas::{ToolEvent, display_doc, tool_event};
use crate::state::Tool;
/// The field named `label` ("Opacity", "Flow"), by its caption's name.
fn field<'a>(h: &'a Harness<'static, PhotocraftApp>, label: &str) -> egui_kittest::Node<'a> {
let label = format!("{label}:");
h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some(label.as_str())).unwrap_or_else(|| panic!("the {label} field"))
}
/// The live brush's Opacity and Flow in percent.
fn opacity_flow(app: &PhotocraftApp) -> (f32, f32) {
let b = &app.session.tools.brush;
((b.opacity * 100.0).round(), (b.flow * 100.0).round())
}
#[test]
fn the_bar_shows_opacity_and_flow_after_mode_at_100() {
let h = bar(Tool::PatternStamp);
let mode = h.query_all_by_role(Role::ComboBox).find(|n| n.value().as_deref() == Some("Normal")).expect("the Mode dropdown").rect();
let (opacity, flow) = (field(&h, "Opacity"), field(&h, "Flow"));
assert_eq!((opacity.accesskit_node().numeric_value(), flow.accesskit_node().numeric_value()), (Some(100.0), Some(100.0)));
assert_eq!(opacity.accesskit_node().description().as_deref(), Some("Set opacity for stroke"));
assert_eq!(flow.accesskit_node().description().as_deref(), Some("Set flow rate for stroke"));
let (opacity, flow) = (opacity.rect(), flow.rect());
assert!(mode.right() <= opacity.left() && opacity.right() <= flow.left(), "Mode, Opacity, Flow: {mode:?} {opacity:?} {flow:?}");
}
#[test]
fn typed_values_are_whole_percents_clamped_to_1_100_without_an_alert() {
let mut h = bar(Tool::PatternStamp);
for (opacity, flow, want) in [("50", "10", (50.0, 10.0)), ("37.6", "12.4", (38.0, 12.0)), ("150", "0", (100.0, 1.0))] {
type_into(&mut h, "Opacity", opacity);
type_into(&mut h, "Flow", flow);
assert_eq!(opacity_flow(h.state()), want, "typed {opacity} / {flow}");
assert!(alerts(&h).is_empty(), "the Brush's fields clamp silently");
}
let b = &h.state().session.tools.brush;
assert_eq!((b.opacity, b.flow), (1.0, 0.01), "stored as whole percents");
}
#[test]
fn reset_tool_puts_opacity_and_flow_back_to_100() {
let mut h = bar(Tool::PatternStamp);
type_into(&mut h, "Opacity", "40");
type_into(&mut h, "Flow", "25");
assert_eq!(opacity_flow(h.state()), (40.0, 25.0));
crate::burn_default_tip_tests::invoke(h.state_mut(), "tool.reset", json!({}));
h.run_steps(3);
assert_eq!(opacity_flow(h.state()), (100.0, 100.0));
assert_eq!(field(&h, "Opacity").accesskit_node().numeric_value(), Some(100.0));
assert_eq!(field(&h, "Flow").accesskit_node().numeric_value(), Some(100.0));
}
/// The issue's test document: 800 × 600 RGB 8 bit, white with its right half green (40,160,60),
/// a 20 × 20 pattern of 10 px quadrants (red, green / blue, white) and the Pattern Stamp with a
/// 40 px hard tip, Aligned on, at `opacity` and `flow` (fractions).
fn document(opacity: f32, flow: f32) -> PhotocraftApp {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 20, "height": 20})).unwrap();
for (x, y, color) in [(0, 0, "#ff0000"), (10, 0, "#00ff00"), (0, 10, "#0000ff"), (10, 10, "#ffffff")] {
app.run("select.rect", json!({"x": x, "y": y, "width": 10, "height": 10})).unwrap();
app.run("edit.fill", json!({"color": color})).unwrap();
}
app.run("select.deselect", json!({})).unwrap();
let pattern = app.run("edit.definePattern", json!({"name": "Quadrants", "rect": [0, 0, 20, 20]})).unwrap()["pattern"].clone();
app.run("pattern.presets.select", json!({"pattern": pattern})).unwrap();
app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap();
app.run("select.rect", json!({"x": 400, "y": 0, "width": 400, "height": 600})).unwrap();
app.run("edit.fill", json!({"color": "#28a03c"})).unwrap();
app.run("select.deselect", json!({})).unwrap();
app.ui.tool = Tool::PatternStamp;
app.ui.tool_options.pattern_stamp_aligned = true;
crate::paint_mouse::sync_tool_brush(&mut app);
let brush = json!({"size": 40, "hardness": 1.0, "opacity": opacity, "flow": flow, "pressureSize": false, "smoothing": {"amount": 0.0}});
app.run("tools.setBrush", json!({"brush": brush})).unwrap();
app
}
/// The distinct 8-bit colours inside the tip of a click at (600, 300), in `doc`.
fn colours(doc: &photocraft_doc::Document, app: &PhotocraftApp) -> BTreeSet<[u8; 3]> {
let surf = doc.layer(app.session.active().unwrap().active_layer.unwrap()).unwrap().surface().unwrap();
let inside = Rect::from_center_size(egui::pos2(600.0, 300.0), egui::vec2(24.0, 24.0));
let (x0, y0, x1, y1) = (inside.left() as i32, inside.top() as i32, inside.right() as i32, inside.bottom() as i32);
(y0..y1).flat_map(|y| (x0..x1).map(move |x| (x, y))).map(|(x, y)| surf.rgba(x, y)).map(|c| [c[0], c[1], c[2]].map(|v| (v * 255.0).round() as u8)).collect()
}
/// One click at (600, 300) on the green half: what the canvas showed before the release, and what
/// the release committed.
fn click(app: &mut PhotocraftApp) -> (BTreeSet<[u8; 3]>, BTreeSet<[u8; 3]>) {
tool_event(app, ToolEvent::Down { x: 600.0, y: 300.0, pressure: 1.0 }, Modifiers::NONE);
assert!(app.live_stroke.is_some(), "the stroke draws live");
// The canvas shows the second document; the first holds the pattern.
let idx = app.session.active_index().unwrap();
let shown = colours(&display_doc(app, idx).0, app);
tool_event(app, ToolEvent::Up { x: 600.0, y: 300.0 }, Modifiers::NONE);
assert!(!app.ui.status_error, "{}", app.ui.status);
let committed = colours(&app.session.active().unwrap().doc, app);
(shown, committed)
}
/// The reference's values for Opacity 50, and for Flow 50 (the same): half the pattern over green.
const HALF: [[u8; 3]; 4] = [[148, 80, 30], [20, 208, 30], [20, 80, 158], [148, 208, 158]];
#[test]
fn opacity_50_paints_the_reference_values_live_and_committed() {
let mut app = document(0.5, 1.0);
let (shown, committed) = click(&mut app);
assert_eq!(committed, BTreeSet::from(HALF));
assert_eq!(shown, committed, "the live preview and the commit agree");
let (_, params) = app.session.journal.iter().rev().find(|(name, _)| name == "paint.patternStamp").unwrap();
assert_eq!((params["opacity"].as_f64(), params["flow"].as_f64()), (Some(50.0), Some(100.0)), "{params}");
}
#[test]
fn flow_50_paints_the_same_values_as_opacity_50() {
let mut app = document(1.0, 0.5);
let (shown, committed) = click(&mut app);
assert_eq!(committed, BTreeSet::from(HALF));
assert_eq!(shown, committed);
}
#[test]
fn flow_10_paints_about_10_percent() {
let mut app = document(1.0, 0.1);
let (shown, committed) = click(&mut app);
assert_eq!(shown, committed);
// Red over green: the reference's 62,144,54.
let red = committed.iter().find(|c| c[0] > c[2] && c[1] < 150).copied().expect("the red cells");
assert!(red.iter().zip([62u8, 144, 54]).all(|(a, b)| a.abs_diff(b) <= 1), "{red:?} in {committed:?}");
}
/// A first pick doesn't carry the Brush's Opacity and Flow over: the Pattern Stamp starts at 100.
#[test]
fn a_first_pick_after_a_30_percent_brush_starts_at_100() {
let mut h = bar(Tool::Brush);
h.state_mut().run("tools.setBrush", json!({"brush": {"opacity": 0.3, "flow": 0.4}})).unwrap();
h.run_steps(3);
h.state_mut().ui.tool = Tool::PatternStamp;
h.run_steps(4);
assert_eq!(field(&h, "Opacity").accesskit_node().numeric_value(), Some(100.0));
assert_eq!(field(&h, "Flow").accesskit_node().numeric_value(), Some(100.0));
let app = h.state_mut();
assert!(crate::retouch_ui::finish_stroke(app, Tool::PatternStamp, &[[40.0, 40.0, 1.0]], Modifiers::NONE, false));
let (_, params) = app.session.journal.iter().rev().find(|(name, _)| name == "paint.patternStamp").unwrap();
assert_eq!((params["opacity"].as_f64(), params["flow"].as_f64()), (Some(100.0), Some(100.0)), "{params}");
}
/// Impressionist strokes take Opacity too (not measured: only that they paint with it, live and
/// committed alike).
#[test]
fn an_impressionist_stroke_paints_with_opacity_live_and_committed() {
let painted = |opacity: f32| {
let mut app = document(opacity, 1.0);
app.ui.tool_options.pattern_stamp_impressionist = true;
let (shown, committed) = click(&mut app);
assert_eq!(shown, committed, "opacity {opacity}: the live preview and the commit agree");
let (_, params) = app.session.journal.iter().rev().find(|(name, _)| name == "paint.patternStamp").unwrap();
assert_eq!(params["opacity"].as_f64(), Some(f64::from(opacity) * 100.0), "{params}");
committed
};
assert_ne!(painted(0.5), painted(1.0), "Opacity 50 paints differently from 100");
}
@@ -0,0 +1,154 @@
//! #12200: Reset Tool, Reset All Tools and a fresh first pick give the Pencil a 1 px hard round
//! tip (size 1, hardness 100 %, angle 0, roundness 100 %, spacing 25 %, both pressure overrides
//! off, options-bar chip "1"), and a default click at 100.2,100.2 paints only pixel 100,100.
use egui::{Context, Modifiers, Pos2, RawInput, Rect, Shape, vec2};
use serde_json::{Value, json};
use crate::PhotocraftApp;
use crate::canvas::{ToolEvent, tool_event};
use crate::control::{ControlRequest, handle};
use crate::state::Tool;
/// Creates a test app with a 200x200 document.
fn app() -> PhotocraftApp {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.sync_views();
app
}
/// Dispatches a control request and syncs document views.
fn control(app: &mut PhotocraftApp, method: &str, params: Value) {
let ctx = Context::default();
let (req, _rx) = ControlRequest::new(method, params);
let _ = handle(app, &ctx, &req);
app.sync_views();
}
/// Switches to `tool` and synchronizes its remembered brush.
fn pick(app: &mut PhotocraftApp, tool: Tool) {
app.ui.tool = tool;
crate::paint_mouse::sync_tool_brush(app);
app.sync_views();
}
/// Scrambles the active brush tip and pressure overrides away from defaults.
fn scramble(app: &mut PhotocraftApp) {
let b = &mut app.session.tools.brush;
(b.size, b.hardness, b.spacing, b.angle, b.roundness) = (42.0, 0.3, 0.6, 25.0, 0.5);
(b.pressure_size, b.pressure_opacity) = (true, true);
}
/// Asserts that `brush.get` reports the Pencil's 1 px hard round default tip.
fn assert_pencil_tip(app: &mut PhotocraftApp) {
let b = app.run("brush.get", json!({})).unwrap();
let tip = ["size", "hardness", "angle", "roundness", "spacing"].map(|k| (b[k].as_f64().unwrap() * 1e4).round() / 1e4);
assert_eq!(tip, [1.0, 1.0, 0.0, 1.0, 0.25], "{b}");
assert_eq!(b["pressureSize"], json!(false), "{b}");
assert_eq!(b["pressureOpacity"], json!(false), "{b}");
}
/// Renders the options bar and returns whether the brush preset chip displays `"1"`.
fn chip_shows_one(app: &mut PhotocraftApp) -> bool {
fn has_one(shape: &Shape, rect: Rect) -> bool {
match shape {
Shape::Text(t) => rect.contains(t.pos) && t.galley.text() == "1",
Shape::Vec(v) => v.iter().any(|s| has_one(s, rect)),
_ => false,
}
}
let ctx = Context::default();
PhotocraftApp::setup_context(&ctx, Default::default());
let screen_rect = Some(Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 300.0)));
let mut out = ctx.run_ui(RawInput { screen_rect, ..Default::default() }, |ui| crate::panels::options_bar(app, ui));
out.textures_delta.clear();
let chip = ctx.read_response(crate::brush_picker::chip_id()).unwrap().rect;
out.shapes.iter().any(|s| has_one(&s.shape, chip))
}
/// Verifies that `tool.reset` and `tool.resetAll` give the Pencil its 1 px hard tip and `"1"` chip.
#[test]
fn reset_tool_and_reset_all_give_the_pencil_a_one_pixel_hard_tip() {
let mut a = app();
pick(&mut a, Tool::Pencil);
scramble(&mut a);
a.session.tools.brush.opacity = 0.4;
control(&mut a, "ui.menu.invoke", json!({"id": "tool.reset"}));
assert_pencil_tip(&mut a);
assert_eq!(a.session.tools.brush.opacity, 1.0);
assert!(chip_shows_one(&mut a));
scramble(&mut a);
control(&mut a, "ui.menu.invoke", json!({"id": "tool.resetAll", "params": {"confirmed": true}}));
assert_pencil_tip(&mut a);
assert!(chip_shows_one(&mut a));
}
/// Verifies that first selecting the Pencil (including via `tools.select.pencil` before a UI pass)
/// uses its 1 px hard tip while preserving the outgoing brush opacity.
#[test]
fn pencil_starts_with_its_own_tip_whatever_the_brush_had() {
let mut a = app();
pick(&mut a, Tool::Brush);
scramble(&mut a);
a.session.tools.brush.opacity = 0.4;
control(&mut a, "ui.menu.invoke", json!({"id": "tools.select.pencil"}));
assert_pencil_tip(&mut a);
assert!((a.session.tools.brush.opacity - 0.4).abs() < 1e-5);
assert!(chip_shows_one(&mut a));
}
/// Selecting the Brush again by command, before a UI pass, gives back the Brush's own tip: the
/// Pencil's 1 px tip is not left for the next brush command, and the Brush's edit is not saved to
/// the Pencil.
#[test]
fn selecting_back_to_the_brush_by_command_restores_its_tip_at_once() {
let mut a = app();
pick(&mut a, Tool::Brush);
a.session.tools.brush.size = 42.0;
control(&mut a, "ui.menu.invoke", json!({"id": "tools.select.pencil"}));
assert_pencil_tip(&mut a);
control(&mut a, "ui.menu.invoke", json!({"id": "tools.select.brush"}));
assert_eq!(a.session.tools.brush.size, 42.0, "the Brush's own size, before any frame");
}
/// Verifies that a default Pencil click at `(100.2, 100.2)` paints only pixel `(100, 100)`.
#[test]
fn a_default_click_at_100_2_paints_only_pixel_100_100() {
let mut a = app();
a.run("layer.new.layer", json!({})).unwrap();
pick(&mut a, Tool::Pencil);
tool_event(&mut a, ToolEvent::Down { x: 100.2, y: 100.2, pressure: 1.0 }, Modifiers::NONE);
tool_event(&mut a, ToolEvent::Up { x: 100.2, y: 100.2 }, Modifiers::NONE);
let st = a.session.active().unwrap();
let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap();
assert_eq!(surf.content_bounds(), photocraft_geom::Rect::new(100, 100, 101, 101));
assert_eq!(surf.rgba(100, 100)[3], 1.0);
}
/// Verifies that `tool.resetAll` resets a saved Pencil brush even when invoked from another tool,
/// while preserving the Brush and Eraser reset tips.
#[test]
fn brush_and_other_painting_tools_keep_their_reset_tips() {
let mut a = app();
pick(&mut a, Tool::Eraser);
scramble(&mut a);
pick(&mut a, Tool::Pencil);
scramble(&mut a);
pick(&mut a, Tool::Brush);
scramble(&mut a);
control(&mut a, "ui.menu.invoke", json!({"id": "tool.resetAll", "params": {"confirmed": true}}));
let b = a.run("brush.get", json!({})).unwrap();
let brush_tip = ["size", "hardness", "spacing"].map(|k| (b[k].as_f64().unwrap() * 1e4).round() / 1e4);
assert_eq!(brush_tip, [13.0, 0.0, 0.25]);
pick(&mut a, Tool::Pencil);
assert_pencil_tip(&mut a);
assert!(chip_shows_one(&mut a));
pick(&mut a, Tool::Eraser);
let e = a.run("brush.get", json!({})).unwrap();
let eraser_tip = ["size", "hardness", "spacing"].map(|k| (e[k].as_f64().unwrap() * 1e4).round() / 1e4);
assert_eq!(eraser_tip, [20.0, 1.0, 0.1]);
}
+2 -3
View File
@@ -13,12 +13,11 @@ fn app() -> PhotocraftApp {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 120, "height": 80, "background": "transparent"})).unwrap();
app.run("tools.setColors", json!({"foreground": "#000000", "background": "#ffffff"})).unwrap();
app.run("tools.setBrush", json!({"brush": {"size": 3, "hardness": 0.0}})).unwrap();
// Each tool keeps its own brush (#218): switch first, then set the Pencil's options, as the
// options bar does (its first frame takes the Brush's tip at Photoshop's 10 % smoothing).
// options bar does.
app.ui.tool = Tool::Pencil;
crate::paint_mouse::sync_tool_brush(&mut app);
app.run("tools.setBrush", json!({"brush": {"smoothing": {"amount": 0.0}}})).unwrap();
app.run("tools.setBrush", json!({"brush": {"size": 3, "hardness": 0.0, "smoothing": {"amount": 0.0}}})).unwrap();
app
}
+1 -1
View File
@@ -109,7 +109,7 @@ fn shift_and_alt_constrain_and_centre_the_star_like_the_polygon_tool() {
app.ui.tool = Tool::Star;
drag(&mut app, [100.0, 100.0], [140.0, 120.0], Modifiers::SHIFT | Modifiers::ALT);
match live_shape(&app) {
Some(LiveShape::Polygon { rect, .. }) => assert_eq!(rect, [60.0, 60.0, 80.0, 80.0], "a square box drawn from the centre"),
Some(LiveShape::Polygon { rect, .. }) => assert_eq!(rect, [80.0, 80.0, 40.0, 40.0], "a square box of the shorter side drawn from the centre (#13222)"),
other => panic!("a live star shape, got {other:?}"),
}
}
+2
View File
@@ -77,6 +77,8 @@ mod gradient_refusal_messages_tests;
#[cfg(test)]
mod line_tool_defaults_tests;
#[cfg(test)]
mod path_selection_ctrl_direct_tests;
#[cfg(test)]
mod path_selection_shape_over_saved_path_tests;
#[cfg(test)]
+8 -1
View File
@@ -53,8 +53,15 @@ pub fn tool_name(app: &PhotocraftApp, tool: Tool) -> Option<&'static str> {
/// The alert a press with `tool` gets, if any. `hidden` is the press-time hidden-target refusal
/// (`canvas::tool_input`), which this only words; the lock and the group are checked here. Lock
/// transparent pixels is no refusal, and a group's targeted mask paints. A tool with a
/// [`mode_tool_name`] gets its colour-mode alert first, in an Indexed Color or Bitmap document.
/// [`mode_tool_name`] gets its colour-mode alert first, in an Indexed Color or Bitmap document; the
/// Pattern Stamp only the engine's, for any pattern in an Indexed Color document.
pub fn alert(app: &PhotocraftApp, tool: Tool, hidden: bool) -> Option<String> {
// The Pattern Stamp's colour-mode alert depends on its pattern too (#12887).
if tool == Tool::PatternStamp {
use photocraft_engine::retouch_cmds::{PATTERN_STAMP_INDEXED_REFUSAL, pattern_stamp_press_refusal};
let p = crate::retouch_ui::pattern_stamp_params(app, &[]);
return pattern_stamp_press_refusal(&app.session, &p).is_some().then(|| tl!(PATTERN_STAMP_INDEXED_REFUSAL).to_owned());
}
if let Some(name) = mode_tool_name(tool)
&& let Some(template) = match app.session.active()?.doc.mode {
photocraft_doc::ColorMode::Indexed => Some(INDEXED),
+7 -2
View File
@@ -319,9 +319,11 @@ impl Edit {
}
/// Is Direct Selection what the pointer does now: its own tool, or a Pen (the Pen, Freeform Pen
/// or Curvature Pen), an anchor point tool or Convert Point with ⌘/Ctrl held.
/// or Curvature Pen), an anchor point tool or Convert Point with ⌘/Ctrl held, or Path Selection
/// with ⌘/Ctrl alone (#13284; with ⌥ or ⇧ too, the reference was not measured, so as today).
fn direct(tool: Tool, mods: Modifiers) -> bool {
tool == Tool::DirectSelection
|| (tool == Tool::PathSelection && mods.command && !mods.alt && !mods.shift)
|| (matches!(tool, Tool::Pen | Tool::FreeformPen | Tool::CurvaturePen | Tool::AddAnchorPoint | Tool::DeleteAnchorPoint | Tool::ConvertPoint)
&& mods.command)
}
@@ -654,6 +656,7 @@ fn press(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers, convert: bool) -
let _ = app.run("layer.select", json!({"layer": id}));
}
let owner = Owner::current(app);
let tool_is_path_selection = app.ui.tool == Tool::PathSelection;
let ds = &mut app.ui.direct_selection;
if ds.target.as_ref() != Some(&target) {
*ds = DirectSelection { target: Some(target), ..Default::default() };
@@ -700,7 +703,9 @@ fn press(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers, convert: bool) -
return true;
}
ds.anchors.push(k);
} else if !ds.anchors.contains(&k) {
} else if !ds.anchors.contains(&k) || tool_is_path_selection {
// Path Selection's ⌘/Ctrl moves the anchor pressed alone, not the selected
// component it belongs to (#13284).
ds.anchors = vec![k];
}
Edit::Anchors(ds.anchors.clone())
@@ -170,6 +170,38 @@ fn mouse(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, kind: &str, x: f
h.run_steps(2);
}
#[test]
fn pasteboard_click_deselects_only_in_new_mode_and_is_undoable() {
for mods in [Modifiers::NONE, Modifiers::SHIFT, Modifiers::ALT, Modifiers::SHIFT | Modifiers::ALT] {
let mut h = harness();
h.state_mut().run("select.rect", json!({"x": 20, "y": 20, "width": 80, "height": 80})).unwrap();
let history = h.state().session.active().unwrap().history.past_len();
mouse(&mut h, "down", -20.0, 100.0, mods);
mouse(&mut h, "up", -20.0, 100.0, mods);
let state = h.state().session.active().unwrap();
if mods == Modifiers::NONE {
assert!(state.doc.selection.is_none(), "New-mode click deselects");
assert_eq!(state.history.past_len(), history + 1);
h.state_mut().run("edit.undo", json!({})).unwrap();
assert!(h.state().session.active().unwrap().doc.selection.is_some(), "undo restores the selection");
} else {
assert!(state.doc.selection.is_some(), "modified selection mode keeps the selection");
assert_eq!(state.history.past_len(), history);
}
}
}
#[test]
fn lasso_drag_from_pasteboard_still_creates_a_selection() {
let mut h = harness();
mouse(&mut h, "down", -20.0, 80.0, Modifiers::NONE);
mouse(&mut h, "move", 100.0, 80.0, Modifiers::NONE);
mouse(&mut h, "move", 100.0, 160.0, Modifiers::NONE);
mouse(&mut h, "up", -20.0, 160.0, Modifiers::NONE);
let selection = h.state().session.active().unwrap().doc.selection.as_ref().expect("a drag still selects");
assert!(selection.sample_channel(50, 120, 0) > 0.5);
}
fn freeform_harness() -> egui_kittest::Harness<'static, PhotocraftApp> {
let mut h = harness();
let app = h.state_mut();
@@ -63,6 +63,12 @@ pub(crate) fn selected(app: &PhotocraftApp) -> Option<(PathRef, Path, Vec<usize>
(!heads.is_empty()).then_some((r, path, heads))
}
/// Deselects every component (and anchor), leaving the path itself as it is. Shared with Direct
/// Selection's Enter (#13208).
pub(crate) fn deselect_components(app: &mut PhotocraftApp) {
app.ui.direct_selection = DirectSelection::default();
}
/// The operation every selected component has, for the menu's icon; `None` when they differ.
pub(crate) fn selected_op(app: &PhotocraftApp) -> Option<&'static str> {
let (_, path, heads) = selected(app)?;
@@ -283,3 +289,7 @@ pub fn handle_keys(app: &mut PhotocraftApp, ctx: &egui::Context) {
#[cfg(test)]
mod tests;
#[cfg(test)]
#[path = "path_selection_enter_escape_tests.rs"]
mod path_selection_enter_escape_tests;
@@ -0,0 +1,92 @@
//! #13284: with Path Selection and ⌘/Ctrl held, a press on an anchor acts as Direct Selection, as in
//! the reference application: only that anchor moves, in one History step. Without ⌘/Ctrl the tool
//! drags the whole component, and releasing ⌘/Ctrl goes back to that.
use egui::Modifiers;
use photocraft_doc::Path;
use serde_json::json;
use crate::PhotocraftApp;
use crate::canvas::{ToolEvent, tool_event};
use crate::state::Tool;
const SAVED: &str = "Path 1";
const SQUARE: [[f64; 2]; 4] = [[100.0, 300.0], [300.0, 300.0], [300.0, 500.0], [100.0, 500.0]];
/// The closed square 100,300–300,500 saved as "Path 1", targeted, with Path Selection.
fn setup() -> PhotocraftApp {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap();
let square = json!({"subpaths": [{"closed": true, "knots": SQUARE}]});
app.run("path.set", json!({"name": SAVED, "path": square})).unwrap();
app.ui.selected_path = Some(SAVED.into());
app.ui.tool = Tool::PathSelection;
app
}
fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], mods: Modifiers) {
tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, mods);
let mid = [(from[0] + to[0]) / 2.0, (from[1] + to[1]) / 2.0];
tool_event(app, ToolEvent::Move { x: mid[0], y: mid[1], pressure: 1.0 }, mods);
tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, mods);
tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, mods);
}
fn saved(app: &PhotocraftApp) -> Path {
app.session.active().unwrap().doc.paths.iter().find(|p| p.name == SAVED).unwrap().path.clone()
}
fn anchors(app: &PhotocraftApp) -> Vec<[f64; 2]> {
saved(app).subpaths[0].knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect()
}
fn undo_label(app: &PhotocraftApp) -> Option<String> {
app.session.active()?.history.undo_label().map(str::to_string)
}
fn moved_by(d: [f64; 2]) -> Vec<[f64; 2]> {
SQUARE.iter().map(|p| [p[0] + d[0], p[1] + d[1]]).collect()
}
/// "Drag Anchor Points" today; PR #13541 renames a one-anchor drag to the singular.
fn is_anchor_drag_label(label: Option<&str>) -> bool {
matches!(label, Some("Drag Anchor Points" | "Drag Anchor Point"))
}
#[test]
fn ctrl_drag_on_an_anchor_moves_only_that_anchor_in_one_step() {
let mut app = setup();
let before = undo_label(&app);
drag(&mut app, [100.0, 300.0], [80.0, 280.0], Modifiers::COMMAND);
assert_eq!(anchors(&app), vec![[80.0, 280.0], SQUARE[1], SQUARE[2], SQUARE[3]], "only the pressed anchor moved");
assert!(is_anchor_drag_label(undo_label(&app).as_deref()), "one anchor-drag step: {:?}", undo_label(&app));
app.run("edit.undo", json!({})).unwrap();
assert_eq!(anchors(&app), SQUARE.to_vec(), "one undo restores the square");
assert_eq!(undo_label(&app), before, "the drag was a single History step");
}
#[test]
fn ctrl_drag_on_an_anchor_of_a_selected_component_moves_only_that_anchor() {
let mut app = setup();
// A plain click selects the whole component first.
drag(&mut app, [200.0, 300.0], [200.0, 300.0], Modifiers::NONE);
drag(&mut app, [100.0, 300.0], [80.0, 280.0], Modifiers::COMMAND);
assert_eq!(anchors(&app), vec![[80.0, 280.0], SQUARE[1], SQUARE[2], SQUARE[3]]);
}
#[test]
fn a_drag_without_ctrl_still_moves_every_anchor() {
let mut app = setup();
drag(&mut app, [100.0, 300.0], [80.0, 280.0], Modifiers::NONE);
assert_eq!(anchors(&app), moved_by([-20.0, -20.0]), "the whole component moved");
}
#[test]
fn releasing_ctrl_returns_to_moving_the_whole_component() {
let mut app = setup();
drag(&mut app, [100.0, 300.0], [80.0, 280.0], Modifiers::COMMAND);
let after_ctrl = anchors(&app);
drag(&mut app, [200.0, 400.0], [210.0, 410.0], Modifiers::NONE);
let expected: Vec<[f64; 2]> = after_ctrl.iter().map(|p| [p[0] + 10.0, p[1] + 10.0]).collect();
assert_eq!(anchors(&app), expected, "a plain drag moves the whole component again");
}
@@ -0,0 +1,156 @@
//! #13287: with Path Selection and components of the saved path targeted in the Paths panel
//! selected, Esc deselects the components and keeps the path targeted, and Enter deselects them and
//! untargets the path. Neither adds a History step or moves a point.
use egui::{Key, Modifiers};
use photocraft_doc::vector::Path;
use serde_json::json;
use crate::PhotocraftApp;
use crate::direct_select::{DirectSelection, PathRef, active_paths};
use crate::state::Tool;
/// 800 x 600 with the saved path "Path 1" (a square and a triangle) targeted, and the square
/// selected as a component.
fn app() -> PhotocraftApp {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap();
let path = json!({"subpaths": [
{"closed": true, "knots": [[100, 300], [300, 300], [300, 500], [100, 500]]},
{"closed": true, "knots": [[400, 300], [600, 300], [500, 500]]}
]});
app.run("path.set", json!({"name": "Path 1", "path": path})).unwrap();
app.sync_views();
app.ui.tool = Tool::PathSelection;
app.ui.selected_path = Some("Path 1".into());
crate::path_components::press(&mut app, [300.0, 300.0], false);
let (target, ..) = crate::path_components::selected(&app).expect("the square is selected");
assert_eq!(target, PathRef::Saved(0));
app
}
fn press(app: &mut PhotocraftApp, key: Key, modifiers: Modifiers) {
let ctx = egui::Context::default();
let ev = egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers };
ctx.begin_pass(egui::RawInput { events: vec![ev], ..Default::default() });
crate::shortcuts::handle(app, &ctx);
ctx.end_pass().textures_delta.clear();
}
fn path_1(app: &PhotocraftApp) -> Path {
app.session.active().unwrap().doc.paths.iter().find(|p| p.name == "Path 1").unwrap().path.clone()
}
fn steps(app: &PhotocraftApp) -> usize {
app.session.active().unwrap().history.entries().len()
}
fn nothing_selected(app: &PhotocraftApp) {
assert!(crate::path_components::selected(app).is_none(), "no component is selected");
assert_eq!(app.ui.direct_selection, DirectSelection::default());
}
/// Until Path Selection has its own arrow-key nudge (#10920), an arrow key must move nothing once
/// the components are deselected.
fn arrow_moves_nothing(app: &mut PhotocraftApp) {
let (before, n) = (path_1(app), steps(app));
press(app, Key::ArrowRight, Modifiers::NONE);
assert_eq!(path_1(app), before, "the arrow key moves no point");
assert_eq!(steps(app), n, "and adds no History step");
}
#[test]
fn enter_deselects_the_components_and_untargets_the_path() {
let mut app = app();
let (before, n) = (path_1(&app), steps(&app));
press(&mut app, Key::Enter, Modifiers::NONE);
nothing_selected(&app);
assert_eq!(app.ui.selected_path, None, "Path 1 is no longer targeted");
assert!(!active_paths(&app).iter().any(|(r, _)| *r == PathRef::Saved(0)), "its outline is gone");
assert_eq!(path_1(&app), before);
assert_eq!(steps(&app), n, "Enter adds no History step");
arrow_moves_nothing(&mut app);
}
#[test]
fn escape_deselects_the_components_and_keeps_the_path_targeted() {
let mut app = app();
let (before, n) = (path_1(&app), steps(&app));
press(&mut app, Key::Escape, Modifiers::NONE);
nothing_selected(&app);
assert_eq!(app.ui.selected_path.as_deref(), Some("Path 1"));
assert!(active_paths(&app).iter().any(|(r, _)| *r == PathRef::Saved(0)), "its outline stays");
assert_eq!(path_1(&app), before);
assert_eq!(steps(&app), n, "Esc adds no History step");
arrow_moves_nothing(&mut app);
}
#[test]
fn enter_with_a_work_path_present_does_not_make_the_work_path_the_drawn_path() {
let mut app = app();
let line = json!({"subpaths": [{"knots": [[100, 100], [200, 100]]}]});
app.run("path.set", json!({"name": "work", "path": line})).unwrap();
// `path.set` of the Work Path changes the panel's target: target Path 1 and its component again.
app.ui.selected_path = Some("Path 1".into());
crate::path_components::press(&mut app, [300.0, 300.0], false);
assert!(crate::path_components::selected(&app).is_some());
press(&mut app, Key::Enter, Modifiers::NONE);
assert_eq!(app.ui.selected_path, None);
assert!(!crate::vector_ui::work_path_shown(&app), "the Work Path stays hidden");
assert!(active_paths(&app).is_empty(), "no path is drawn");
}
#[test]
fn escape_with_a_pixel_selection_deselects_the_pixels_and_keeps_the_components() {
let mut app = app();
app.run("select.all", json!({})).unwrap();
press(&mut app, Key::Escape, Modifiers::NONE);
assert!(app.session.active().unwrap().doc.selection.is_none(), "Esc deselects the pixels");
assert!(crate::path_components::selected(&app).is_some(), "the components stay selected");
}
#[test]
fn shift_or_alt_with_enter_or_escape_keeps_the_components_and_the_path() {
for key in [Key::Enter, Key::Escape] {
for modifiers in [Modifiers::SHIFT, Modifiers::ALT] {
let mut app = app();
press(&mut app, key, modifiers);
assert!(crate::path_components::selected(&app).is_some(), "{key:?} {modifiers:?}");
assert_eq!(app.ui.selected_path.as_deref(), Some("Path 1"), "{key:?} {modifiers:?}");
}
}
}
#[test]
fn enter_and_escape_with_no_component_selected_keep_the_path_targeted() {
for key in [Key::Enter, Key::Escape] {
let mut app = app();
crate::path_components::deselect_components(&mut app);
press(&mut app, key, Modifiers::NONE);
assert_eq!(app.ui.selected_path.as_deref(), Some("Path 1"), "{key:?}");
}
}
#[test]
fn free_transform_path_still_owns_enter_and_escape() {
let ctx = egui::Context::default();
let mut app = app();
let (before, n) = (path_1(&app), steps(&app));
crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({})).unwrap();
assert!(app.ui.transform.is_some());
press(&mut app, Key::Escape, Modifiers::NONE);
assert!(app.ui.transform.is_none(), "Esc cancels the transform");
assert_eq!(path_1(&app), before);
assert_eq!(steps(&app), n, "cancelling adds no History step");
let mut app = self::app();
let n = steps(&app);
crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({})).unwrap();
// 5 px down: an unchanged box commits nothing.
let t = app.ui.transform.as_mut().unwrap();
let [x0, y0, x1, y1] = t.rect;
t.quad = [[x0, y0 + 5.0], [x1, y0 + 5.0], [x1, y1 + 5.0], [x0, y1 + 5.0]];
press(&mut app, Key::Enter, Modifiers::NONE);
assert!(app.ui.transform.is_none(), "Enter commits the transform");
assert_eq!(steps(&app), n + 1, "one History step");
}
@@ -0,0 +1,186 @@
//! #13304: the Polygon tool's Sides takes whole numbers 3..100; a value typed past the range becomes
//! the closest one and, once the field is left, the reference's "Closest value inserted" alert with
//! OK says so. A scrub, arrow-key or wheel step past either end stops there without one.
use egui::accesskit::Role;
use egui::vec2;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::json;
use super::SIDES_RANGE_ALERT;
use crate::PhotocraftApp;
use crate::state::{DialogKind, Tool};
/// The options bar with the Polygon tool active.
fn bar() -> Harness<'static, PhotocraftApp> {
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::Polygon;
let mut h = Harness::builder().with_size(vec2(1800.0, 300.0)).build_ui_state(
|ui, app| {
// As the app's frame does: the wheel goes to the focused field.
crate::field_wheel::begin_frame(ui.ctx());
crate::panels::options_bar(app, ui);
},
app,
);
PhotocraftApp::setup_context(&h.ctx, Default::default());
h.run_steps(4);
h
}
/// Clicks into Sides and gives back where it sits.
fn click_sides(h: &mut Harness<'static, PhotocraftApp>) -> egui::Rect {
let field = h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some("Sides:")).expect("the Sides field");
let rect = field.rect();
field.click();
h.run_steps(1);
rect
}
/// Types `text` into Sides, then Tabs out of it.
fn type_sides(h: &mut Harness<'static, PhotocraftApp>, text: &str) {
click_sides(h);
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::Tab);
h.run_steps(3);
}
fn alerts(h: &Harness<'static, PhotocraftApp>) -> Vec<String> {
h.state().ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).filter_map(|d| d.fields.get("message")?.as_str().map(str::to_owned)).collect()
}
/// OK on the alert, as `ui.dialog.confirm` presses it (this harness draws only the bar).
fn ok(h: &mut Harness<'static, PhotocraftApp>) {
let id = h.state().ui.dialogs.iter().find(|d| d.kind == DialogKind::Error).map(|d| d.id).expect("an alert");
crate::dialogs::confirm(h.state_mut(), id).unwrap();
h.run_steps(3);
}
fn sides(h: &Harness<'static, PhotocraftApp>) -> u32 {
h.state().ui.tool_options.polygon_sides
}
#[test]
fn sides_past_the_range_takes_the_closest_value_and_alerts() {
for (typed, want) in [("0", 3), ("2", 3), ("-5", 3), ("101", 100), ("1000", 100)] {
let mut h = bar();
type_sides(&mut h, typed);
assert_eq!(sides(&h), want, "{typed}");
assert_eq!(alerts(&h), vec![SIDES_RANGE_ALERT.to_string()], "{typed}: one alert");
ok(&mut h);
assert!(alerts(&h).is_empty(), "{typed}: OK closes the alert");
assert_eq!(sides(&h), want, "{typed}: the closest value is kept");
}
}
#[test]
fn sides_in_range_are_stored_without_an_alert() {
for (typed, want) in [("3", 3), ("7", 7), ("100", 100)] {
let mut h = bar();
type_sides(&mut h, typed);
assert_eq!(sides(&h), want, "{typed}");
assert!(alerts(&h).is_empty(), "{typed} is in range");
}
}
#[test]
fn sides_that_are_no_number_keep_the_value_without_an_alert() {
let mut h = bar();
type_sides(&mut h, "abc");
assert_eq!(sides(&h), 5, "the previous value stays");
assert!(alerts(&h).is_empty(), "no number, no alert");
}
#[test]
fn arrow_steps_past_either_end_stop_there_without_an_alert() {
for (start, key, want) in [("99", egui::Key::ArrowUp, 100), ("4", egui::Key::ArrowDown, 3)] {
let mut h = bar();
type_sides(&mut h, start);
click_sides(&mut h);
for _ in 0..3 {
h.key_press(key);
h.run_steps(1);
}
h.key_press(egui::Key::Tab);
h.run_steps(3);
assert_eq!(sides(&h), want, "{start}: the steps reached the end");
assert!(alerts(&h).is_empty(), "{start}: an arrow step stops at the end without an alert");
}
}
#[test]
fn a_caption_scrub_past_either_end_does_not_alert() {
for (start, dx, want) in [("95", 50.0, 100), ("8", -50.0, 3)] {
let mut h = bar();
type_sides(&mut h, start);
// The field keeps the keyboard while its caption is scrubbed past the end.
let rect = click_sides(&mut h);
// The caption sits just left of the field.
let from = egui::pos2(rect.left() - 20.0, rect.center().y);
h.event(egui::Event::PointerMoved(from));
h.run_steps(1);
h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() });
h.run_steps(1);
for k in 1..=6 {
h.event(egui::Event::PointerMoved(from + vec2(dx * k as f32, 0.0)));
h.run_steps(1);
}
let to = from + vec2(dx * 6.0, 0.0);
h.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() });
h.run_steps(3);
h.key_press(egui::Key::Tab);
h.run_steps(3);
assert_eq!(sides(&h), want, "{start}: the scrub reached the end");
assert!(alerts(&h).is_empty(), "{start}: a scrub stops at the end without an alert");
}
}
fn wheel_event(unit: egui::MouseWheelUnit, dy: f32) -> egui::Event {
egui::Event::MouseWheel {
source: egui::MouseWheelSource::Unknown,
unit,
delta: vec2(0.0, dy),
phase: egui::TouchPhase::Move,
modifiers: Default::default(),
}
}
#[test]
fn wheel_steps_past_either_end_stop_there_without_an_alert() {
for (start, lines, want) in [("99", 1.0, 100), ("4", -1.0, 3)] {
let mut h = bar();
type_sides(&mut h, start);
click_sides(&mut h);
for _ in 0..3 {
h.event(wheel_event(egui::MouseWheelUnit::Line, lines));
h.run_steps(1);
}
h.key_press(egui::Key::Tab);
h.run_steps(3);
assert_eq!(sides(&h), want, "{start}: the wheel reached the end");
assert!(alerts(&h).is_empty(), "{start}: a wheel step stops at the end without an alert");
}
}
/// A wheel event that steps nothing (a trackpad's zero-delta start, or less than a notch) in the
/// frame a value is typed leaves it typed: it still alerts on the way out.
#[test]
fn a_wheel_event_that_steps_nothing_does_not_hide_a_typed_value() {
for (unit, dy) in [(egui::MouseWheelUnit::Point, 0.0), (egui::MouseWheelUnit::Point, 2.0)] {
let mut h = bar();
click_sides(&mut h);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.run_steps(1);
// Both in one pass, as a trackpad can deliver them (`event` hands the app one per pass).
h.input_mut().events.extend([egui::Event::Text("101".into()), wheel_event(unit, dy)]);
h.run_steps(1);
h.key_press(egui::Key::Tab);
h.run_steps(3);
assert_eq!(sides(&h), 100, "{dy} pt");
assert_eq!(alerts(&h), vec![SIDES_RANGE_ALERT.to_string()], "{dy} pt: the typed 101 alerts");
}
}
@@ -66,10 +66,11 @@ fn reset_all_tools_gives_it_19_px_active_or_picked_later() {
assert_eq!(tip(&mut app), REMOVE_TIP, "picked after the reset");
}
/// The Pencil resets to its 1 px hard round (#12200).
#[test]
fn other_tools_keep_their_reset_sizes() {
for (tool, want) in
[(Tool::Brush, 13.0), (Tool::Pencil, 20.0), (Tool::Eraser, 20.0), (Tool::SpotHealing, 20.0), (Tool::Healing, 19.0), (Tool::CloneStamp, 21.0)]
[(Tool::Brush, 13.0), (Tool::Pencil, 1.0), (Tool::Eraser, 20.0), (Tool::SpotHealing, 20.0), (Tool::Healing, 19.0), (Tool::CloneStamp, 21.0)]
{
let mut a = app();
pick(&mut a, tool);
@@ -0,0 +1,104 @@
//! #12546: the Remove tool's checkboxes read "Sample all layers", "Remove after each stroke",
//! "Create new layer", left to right, each with the reference tooltip.
use egui::accesskit::Role;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::json;
use super::burn_bar_tooltips_tests::{bar, control, hover};
use crate::PhotocraftApp;
use crate::canvas::{ToolEvent, tool_event};
use crate::i18n::Lang;
use crate::state::Tool;
const BOXES: [(&str, &str); 3] = [
("Sample all layers", "Sample content from all visible layers"),
("Remove after each stroke", "Remove area after a single stroke"),
("Create new layer", "Create new layer with results"),
];
fn remove_bar() -> Harness<'static, PhotocraftApp> {
bar(Tool::Remove, Lang::EN, 1600.0, 1.0, false)
}
fn checked(h: &Harness<'static, PhotocraftApp>, label: &str) -> bool {
control(h, Role::CheckBox, label).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True)
}
#[test]
fn the_checkboxes_read_the_reference_labels_left_to_right() {
let h = remove_bar();
let mut boxes: Vec<(f32, String)> =
h.query_all_by_role(Role::CheckBox).map(|n| (n.rect().left(), n.accesskit_node().label().unwrap_or_default())).collect();
boxes.sort_by(|a, b| a.0.total_cmp(&b.0));
let labels: Vec<&str> = boxes.iter().map(|(_, l)| l.as_str()).collect();
assert_eq!(labels, BOXES.map(|(label, _)| label));
}
#[test]
fn hovering_each_checkbox_shows_its_tooltip() {
for (label, tip) in BOXES {
let mut h = remove_bar();
assert!(h.query_by_label(tip).is_none(), "{label}: no tooltip before the hover");
let before = h.state().ui.tool_options.clone();
hover(&mut h, Role::CheckBox, label, tip);
let o = &h.state().ui.tool_options;
assert_eq!(
(o.sample_all.remove, o.remove_after_each_stroke, o.remove_new_layer),
(before.sample_all.remove, before.remove_after_each_stroke, before.remove_new_layer)
);
}
}
#[test]
fn defaults_show_only_remove_after_each_stroke_on_and_reset_tool_restores_them() {
let mut h = remove_bar();
let defaults = [false, true, false];
assert_eq!(BOXES.map(|(label, _)| checked(&h, label)), defaults);
for (label, _) in BOXES {
control(&h, Role::CheckBox, label).click();
h.run_steps(2);
}
assert_eq!(BOXES.map(|(label, _)| checked(&h, label)), defaults.map(|on| !on), "each click toggles its own box");
let ctx = h.ctx.clone();
crate::menus::invoke(h.state_mut(), &ctx, "tool.reset", json!({})).unwrap();
h.run_steps(2);
assert_eq!(BOXES.map(|(label, _)| checked(&h, label)), defaults);
}
#[test]
fn create_new_layer_greys_when_a_mask_or_colour_subset_is_targeted() {
let mut h = remove_bar();
assert!(!control(&h, Role::CheckBox, "Create new layer").accesskit_node().is_disabled());
let app = h.state_mut();
app.run("layer.new.layer", json!({})).unwrap();
app.run("layer.layerMask.revealAll", json!({})).unwrap();
app.ui.mask_target = true;
h.run_steps(2);
assert!(control(&h, Role::CheckBox, "Create new layer").accesskit_node().is_disabled(), "a targeted mask greys it");
let app = h.state_mut();
app.ui.mask_target = false;
app.run("channel.target", json!({"colors": [0, 2]})).unwrap();
h.run_steps(2);
assert!(control(&h, Role::CheckBox, "Create new layer").accesskit_node().is_disabled(), "a colour subset greys it");
for (label, _) in &BOXES[..2] {
assert!(!control(&h, Role::CheckBox, label).accesskit_node().is_disabled(), "{label} stays enabled");
}
}
#[test]
fn the_boxes_ticked_on_the_bar_reach_the_removal_options() {
let mut h = remove_bar();
for label in ["Sample all layers", "Create new layer"] {
control(&h, Role::CheckBox, label).click();
h.run_steps(2);
}
let app = h.state_mut();
let m = egui::Modifiers::NONE;
tool_event(app, ToolEvent::Down { x: 30.0, y: 18.0, pressure: 1.0 }, m);
tool_event(app, ToolEvent::Up { x: 30.0, y: 42.0 }, m);
assert!(!app.ui.status_error, "{}", app.ui.status);
let (id, p) = app.session.journal.last().cloned().unwrap();
assert_eq!((id.as_str(), p["sampleAllLayers"].as_bool(), p["newLayer"].as_bool()), ("paint.remove", Some(true), Some(true)));
}
+35 -12
View File
@@ -35,7 +35,8 @@ pub(crate) fn clone_params(app: &PhotocraftApp) -> Option<Value> {
// The options bar's Mode is the tool's own brush's.
let mode = crate::blend_keys::brush_tool_mode(app.ui.tool, app.session.tools.brush.mode);
// View › Pattern Preview: both tools carry a stroke on across the canvas edges (#8883).
let mut p = json!({"aligned": o.clone_aligned, "sampleLayer": o.clone_sample, "mode": mode.label(), "wrap": app.ui.view.pattern_preview});
let sample = if clone_stamp_indexed(app) { "current" } else { o.clone_sample.as_str() };
let mut p = json!({"aligned": o.clone_aligned, "sampleLayer": sample, "mode": mode.label(), "wrap": app.ui.view.pattern_preview});
if app.ui.tool == Tool::CloneStamp {
p["opacity"] = json!(app.session.tools.brush.opacity * 100.0);
p["flow"] = json!(app.session.tools.brush.flow * 100.0);
@@ -48,6 +49,12 @@ pub(crate) fn clone_params(app: &PhotocraftApp) -> Option<Value> {
Some(p)
}
/// The Clone Stamp in an Indexed Color document, where the reference greys Sample at Current Layer
/// and names the Normal Mode "Threshold" (#12613).
pub(crate) fn clone_stamp_indexed(app: &PhotocraftApp) -> bool {
app.ui.tool == Tool::CloneStamp && app.session.active().is_some_and(|st| st.doc.mode == photocraft_doc::ColorMode::Indexed)
}
/// History Brush params for the live preview and the commit (without `points` and `target`): the
/// options bar's Mode and the tool's own brush. For an Eraser with Erase to History they also
/// carry `eraseToHistory` and the Eraser's Pencil or Block tip.
@@ -173,6 +180,8 @@ pub(crate) fn pattern_stamp_params(app: &PhotocraftApp, points: &[[f64; 3]]) ->
"seed": stroke_seed(points),
// The options bar's Mode is the tool's own brush's; Behind is a mode of that list.
"mode": if app.session.tools.brush.behind { "Behind" } else { app.session.tools.brush.mode.label() },
"opacity": app.session.tools.brush.opacity * 100.0,
"flow": app.session.tools.brush.flow * 100.0,
});
if o.pattern_stamp_aligned
&& let Some(ph) = app.ui.pattern_stamp_phase
@@ -877,6 +886,17 @@ fn protect_tones_checkbox(ui: &mut egui::Ui, on: &mut bool) -> (egui::Response,
(resp, label_resp.id)
}
/// The Clone Stamp's and Healing Brush's Sample. `indexed` ([`clone_stamp_indexed`]) greys it at
/// Current Layer and leaves the stored choice for other documents.
fn clone_sample_dropdown(ui: &mut egui::Ui, stored: &mut String, indexed: bool) {
let opts = [("current", tl!("Current Layer")), ("currentAndBelow", tl!("Current & Below")), ("all", tl!("All Layers"))];
let mut sample = if indexed { "current" } else { stored.as_str() };
let changed = ui.add_enabled_ui(!indexed, |ui| crate::widgets::dropdown(ui, "clone-sample", tl!("Source"), &mut sample, &opts, 130.0)).inner;
if changed && !indexed {
*stored = sample.to_owned();
}
}
/// Options bar for the retouching and smart-selection tools. Returns false for other tools.
pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bool {
if !tool.is_brushlike() && !matches!(tool, Tool::QuickSelection | Tool::ObjectSelection | Tool::Patch | Tool::ContentAwareMove | Tool::RedEye)
@@ -889,6 +909,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo
return true;
}
let composite = crate::canvas::paint_target(app).as_str() == Some("pixels");
let indexed = clone_stamp_indexed(app);
let o = &mut app.ui.tool_options;
match tool {
Tool::SpotHealing => {
@@ -903,11 +924,14 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo
crate::widgets::checkbox(ui, &mut o.sample_all.spot_healing, tl!("Sample All Layers"));
}
Tool::Remove => {
// Photoshop's options bar: Sample All Layers, Create a new layer, Remove after each
// stroke; with strokes waiting, ✓ applies them and ⊘ drops them.
crate::widgets::checkbox(ui, &mut o.sample_all.remove, tl!("Sample All Layers"));
ui.add_enabled_ui(composite, |ui| crate::widgets::checkbox(ui, &mut o.remove_new_layer, tl!("Create a new layer")));
crate::widgets::checkbox(ui, &mut o.remove_after_each_stroke, tl!("Remove after each stroke"));
// Photoshop's options bar (#12546): Sample all layers, Remove after each stroke, Create
// new layer; with strokes waiting, ✓ applies them and ⊘ drops them.
crate::widgets::checkbox(ui, &mut o.sample_all.remove, tl!("Sample all layers")).on_hover_text(tl!("Sample content from all visible layers"));
crate::widgets::checkbox(ui, &mut o.remove_after_each_stroke, tl!("Remove after each stroke"))
.on_hover_text(tl!("Remove area after a single stroke"));
ui.add_enabled_ui(composite, |ui| {
crate::widgets::checkbox(ui, &mut o.remove_new_layer, tl!("Create new layer")).on_hover_text(tl!("Create new layer with results"));
});
if !app.remove_pending.is_empty() {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if crate::widgets::primary_button(ui, "✓", 32.0)
@@ -954,12 +978,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo
Tool::Healing | Tool::CloneStamp => {
crate::widgets::checkbox(ui, &mut o.clone_aligned, tl!("Aligned"));
opt(ui, tl!("Sample:"));
let opts = [
("current".to_string(), tl!("Current Layer")),
("currentAndBelow".to_string(), tl!("Current & Below")),
("all".to_string(), tl!("All Layers")),
];
crate::widgets::dropdown(ui, "clone-sample", tl!("Source"), &mut o.clone_sample, &opts, 130.0);
clone_sample_dropdown(ui, &mut o.clone_sample, indexed);
if app.ui.clone_source.is_none() {
crate::widgets::vline(ui, 22.0);
opt(ui, &crate::i18n::fmt(tl!("{key}-click to set the source"), &[("key", &crate::shortcuts::pretty("Alt"))]));
@@ -1221,3 +1240,7 @@ mod healing_indexed_alert_tests;
#[cfg(test)]
#[path = "../clone_stamp_no_source_alert_tests.rs"]
mod clone_stamp_no_source_alert_tests;
#[cfg(test)]
#[path = "remove_options_bar_labels_tests.rs"]
mod remove_options_bar_labels_tests;
+28 -10
View File
@@ -101,7 +101,7 @@ pub(crate) fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool
o.stroke_width = enabled_stroke_width(o.stroke_width);
}
}
let mut radius_alert = false;
let (mut radius_alert, mut sides_alert) = (false, false);
match tool {
Tool::Rectangle => {
crate::widgets::vline(ui, 22.0);
@@ -117,11 +117,9 @@ pub(crate) fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool
}
Tool::Polygon => {
crate::widgets::vline(ui, 22.0);
lbl(ui, tl!("Sides:"));
let mut s = o.polygon_sides as f32;
if crate::widgets::value_field(ui, &mut s, 3.0..=100.0, "", 48.0).changed() {
o.polygon_sides = s.round().clamp(3.0, 100.0) as u32;
}
let label = tl!("Sides:");
lbl(ui, label);
sides_alert = sides_field(ui, label, &mut o.polygon_sides);
}
Tool::Line => {
crate::widgets::vline(ui, 22.0);
@@ -196,7 +194,8 @@ pub(crate) fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool
if let Some(rgb) = recent {
crate::paint_picker::remember(app, rgb);
}
radius_range_alert(app, radius_alert);
range_alert(app, radius_alert, RADIUS_RANGE_ALERT);
range_alert(app, sides_alert, SIDES_RANGE_ALERT);
}
/// The Rectangle tool's corner radius in px, as the reference takes it (#13336).
@@ -205,12 +204,27 @@ pub(crate) const RADIUS_RANGE: std::ops::RangeInclusive<f32> = 0.0..=150_000.0;
/// The reference's alert for a Rectangle tool Radius typed past [`RADIUS_RANGE`] (#13336).
pub(crate) const RADIUS_RANGE_ALERT: &str = "A value between 0.000 pixel and 150000.000 Pixels is required. Closest value inserted.";
/// Shows [`RADIUS_RANGE_ALERT`] as a modal with OK when `owed`, once even if more than one pass asks.
fn radius_range_alert(app: &mut PhotocraftApp, owed: bool) {
/// The Polygon tool's Sides: whole numbers 3..100. Returns true once the field is left with a
/// value typed past them, so the caller shows [`SIDES_RANGE_ALERT`] (#13304).
fn sides_field(ui: &mut egui::Ui, label: &str, sides: &mut u32) -> bool {
let mut s = *sides as f32;
let (r, out_of_range) = crate::widgets::value_field_whole_alerting(ui, label, &mut s, 3.0..=100.0, "", 48.0);
if r.changed() {
*sides = s.round().clamp(3.0, 100.0) as u32;
}
out_of_range
}
/// The reference's alert for a Polygon Sides value typed past 3..100 (#13304).
pub(crate) const SIDES_RANGE_ALERT: &str = "An integer between 3 and 100 is required. Closest value inserted.";
/// Shows `alert` ([`RADIUS_RANGE_ALERT`], [`SIDES_RANGE_ALERT`]) as a modal with OK when `owed`,
/// once even if more than one pass asks.
fn range_alert(app: &mut PhotocraftApp, owed: bool, alert: &str) {
if !owed {
return;
}
let message = tl!(RADIUS_RANGE_ALERT).to_owned();
let message = tl!(alert).to_owned();
let shown = app.ui.dialogs.iter().any(|d| d.kind == crate::state::DialogKind::Error && d.fields.get("message").and_then(|m| m.as_str()) == Some(&message));
if !shown {
app.ui.open_dialog(crate::state::DialogKind::Error, json!({ "message": message }).as_object().cloned().unwrap_or_default());
@@ -225,6 +239,10 @@ mod rectangle_radius_range_tests;
#[path = "rectangle_radius_target_tests.rs"]
mod rectangle_radius_target_tests;
#[cfg(test)]
#[path = "polygon_sides_alert_tests.rs"]
mod polygon_sides_alert_tests;
/// Tool-bar paint changes affect the next shape; Properties edits the selected shape instead.
pub(crate) fn set_tool_paint(app: &mut PhotocraftApp, stroke: bool, change: PaintChange) -> Result<(), String> {
// A colour takes the place of a gradient; No Color keeps it for when the paint comes back.
+164 -17
View File
@@ -11,8 +11,12 @@
//! enlarged by the transform: the full-resolution level with nearest filtering, so pixels stay
//! crisp like the canvas around them.
//!
//! Levels and filter variants are uploaded on first use and cached for the session.
//! Levels and filter variants are uploaded on first use and cached for the session. A mip level
//! first needed mid-drag (the scale crossing ½, ¼…) is built, colour-converted and uploaded on a
//! helper thread, and the closest finer level already uploaded is shown until it is ready
//! (#11103): halving a 24 MP layer took a whole frame or more on the UI thread.
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use egui::{Color32, ColorImage, TextureHandle, TextureId, TextureOptions};
@@ -30,12 +34,36 @@ struct Level {
pub struct PreviewTextures {
name: String,
/// CPU copies of the levels built so far (level 0 = full resolution), premultiplied.
images: Mutex<Vec<Arc<ColorImage>>>,
images: Arc<Mutex<Vec<Arc<ColorImage>>>>,
/// uv extent of level 0 that covers the source exactly (< 1 when level 0 was padded).
base_uv: [f32; 2],
uploaded: Mutex<Vec<Level>>,
uploaded: Arc<Mutex<Vec<Level>>>,
/// Mip levels being built off the UI thread, as `(level, display key)`.
building: Arc<Mutex<Vec<(u32, u64)>>>,
/// Whether a mip level that has a finer level to stand in for it is built off the UI thread.
background: bool,
/// Cleared when the preview closes (under the `uploaded` lock): a level finishing after that is
/// neither converted nor uploaded. Workers only read it, so they never keep the preview alive.
alive: Arc<AtomicBool>,
/// Held by a test to pause the workers just before they check `alive`.
#[cfg(test)]
gate: Arc<Mutex<()>>,
/// How many levels the workers have uploaded, for tests.
#[cfg(test)]
uploads: Arc<std::sync::atomic::AtomicUsize>,
}
impl Drop for PreviewTextures {
fn drop(&mut self) {
let _uploads = self.uploaded.lock().unwrap_or_else(PoisonError::into_inner);
self.alive.store(false, Ordering::Release);
}
}
/// Off the UI thread on native builds; the web build has no threads to spare. Unit tests build
/// synchronously unless they ask (`set_background_builds`), so frames stay deterministic.
const BUILD_IN_BACKGROUND: bool = cfg!(not(any(test, target_arch = "wasm32")));
/// A source pixel shown at this many screen pixels or more counts as "zoomed in" (nearest).
const CRISP_ZOOM: f32 = 2.0;
@@ -47,12 +75,40 @@ impl PreviewTextures {
let base_uv = [base_uv[0].clamp(0.0, 1.0), base_uv[1].clamp(0.0, 1.0)];
Self {
name,
images: Mutex::new(vec![image]),
images: Arc::new(Mutex::new(vec![image])),
base_uv,
uploaded: Mutex::new(vec![Level { level: 0, display_key: 0, nearest: false, tex, uv: base_uv }]),
uploaded: Arc::new(Mutex::new(vec![Level { level: 0, display_key: 0, nearest: false, tex, uv: base_uv }])),
building: Arc::new(Mutex::new(Vec::new())),
background: BUILD_IN_BACKGROUND,
alive: Arc::new(AtomicBool::new(true)),
#[cfg(test)]
gate: Arc::new(Mutex::new(())),
#[cfg(test)]
uploads: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
}
}
/// Build mip levels off the UI thread (`true`) or in the frame that first needs them.
#[cfg(test)]
pub(crate) fn set_background_builds(&mut self, on: bool) {
self.background = on;
}
/// Whether a mip level is still being built off the UI thread.
#[cfg(test)]
pub(crate) fn is_building(&self) -> bool {
!self.building.lock().unwrap_or_else(PoisonError::into_inner).is_empty()
}
/// What a test locks to pause the workers just before they check that the preview is open,
/// what tells it they are all done, and how many levels they uploaded; the last two still work
/// once the preview is gone.
#[cfg(test)]
pub(crate) fn worker_hooks(&self) -> (Arc<Mutex<()>>, impl Fn() -> bool + use<>, Arc<std::sync::atomic::AtomicUsize>) {
let building = Arc::clone(&self.building);
(Arc::clone(&self.gate), move || building.lock().unwrap_or_else(PoisonError::into_inner).is_empty(), Arc::clone(&self.uploads))
}
/// Size of the full-resolution level in texels.
pub fn size(&self) -> [usize; 2] {
self.images.lock().unwrap_or_else(PoisonError::into_inner).first().map_or([0, 0], |i| i.size)
@@ -100,6 +156,19 @@ impl PreviewTextures {
if let Some(l) = up.iter().find(|l| l.level == level && l.nearest == nearest && l.display_key == display_key) {
return (l.tex.id(), l.uv);
}
// A level first needed mid-drag: show the closest finer level already uploaded for this
// display while a helper thread builds it (#11103).
if self.background
&& level > 0
&& let Some(finer) = up.iter().filter(|l| l.display_key == display_key && l.level < level).max_by_key(|l| (l.level, !l.nearest))
{
let shown = (finer.tex.id(), finer.uv);
drop(up);
if self.build_in_background(ctx, level, display, display_key) {
return shown;
}
up = self.uploaded.lock().unwrap_or_else(PoisonError::into_inner);
}
let Some((img, uv)) = self.level_image(level) else {
// Can't build it (shouldn't happen): fall back to the first upload.
return up.first().map_or((TextureId::default(), [1.0, 1.0]), |l| (l.tex.id(), l.uv));
@@ -114,24 +183,93 @@ impl PreviewTextures {
(id, uv)
}
/// Builds level `level` on a helper thread, uploads it and asks for a frame. False when no
/// thread could be started (the caller builds it in this frame instead).
fn build_in_background(&self, ctx: &egui::Context, level: u32, display: Option<&CanvasDisplay>, display_key: u64) -> bool {
{
let mut building = self.building.lock().unwrap_or_else(PoisonError::into_inner);
if building.contains(&(level, display_key)) {
return true;
}
building.push((level, display_key));
}
let (images, uploaded, building, alive) = (Arc::clone(&self.images), Arc::clone(&self.uploaded), Arc::clone(&self.building), Arc::clone(&self.alive));
let (ctx, base_uv, name) = (ctx.clone(), self.base_uv, format!("{}-{level}-linear", self.name));
let display = display.map(share_display);
#[cfg(test)]
let (gate, uploads) = (Arc::clone(&self.gate), Arc::clone(&self.uploads));
let job = move || {
let built = level_of(&images, base_uv, level);
#[cfg(test)]
drop(gate.lock().unwrap_or_else(PoisonError::into_inner));
// The box closed meanwhile: neither convert nor upload.
if let Some((img, uv)) = built.filter(|_| alive.load(Ordering::Acquire)) {
let img = display.as_ref().map_or_else(|| Arc::clone(&img), |d| Arc::new(display_image(&img, d)));
let mut up = uploaded.lock().unwrap_or_else(PoisonError::into_inner);
// Checked again under the lock the preview takes as it closes. A monitor profile
// change meanwhile released this display's uploads: drop it then too.
if alive.load(Ordering::Acquire) && up.iter().all(|l| l.display_key == display_key) && !up.iter().any(|l| l.level == level && !l.nearest) {
let tex = ctx.load_texture(name, img, TextureOptions::LINEAR);
#[cfg(test)]
uploads.fetch_add(1, Ordering::Relaxed);
up.push(Level { level, display_key, nearest: false, tex, uv });
}
}
building.lock().unwrap_or_else(PoisonError::into_inner).retain(|b| *b != (level, display_key));
ctx.request_repaint();
};
let started = std::thread::Builder::new().name("transform-mip".into()).spawn(job).is_ok();
if !started {
self.building.lock().unwrap_or_else(PoisonError::into_inner).retain(|b| *b != (level, display_key));
}
started
}
/// Level `n` of the mip chain (built on demand by 2×2 box filtering) and its uv extent.
pub(crate) fn level_image(&self, n: u32) -> Option<(Arc<ColorImage>, [f32; 2])> {
let mut imgs = self.images.lock().unwrap_or_else(PoisonError::into_inner);
while imgs.len() <= n as usize {
level_of(&self.images, self.base_uv, n)
}
}
/// Level `n` of `images` (built on demand by 2×2 box filtering) and its uv extent. Each level is
/// filtered with the lock released, so a helper thread building one doesn't stall the frame
/// reading another (the layer-style preview reads them too).
fn level_of(images: &Mutex<Vec<Arc<ColorImage>>>, base_uv: [f32; 2], n: u32) -> Option<(Arc<ColorImage>, [f32; 2])> {
loop {
let (prev, len) = {
let imgs = images.lock().unwrap_or_else(PoisonError::into_inner);
let prev = imgs.last()?;
if prev.size[0] <= 1 && prev.size[1] <= 1 {
if imgs.len() > n as usize || (prev.size[0] <= 1 && prev.size[1] <= 1) {
break;
}
let next = Arc::new(halve(prev));
(Arc::clone(prev), imgs.len())
};
let next = Arc::new(halve(&prev));
let mut imgs = images.lock().unwrap_or_else(PoisonError::into_inner);
// Another thread may have added this level meanwhile: keep the first.
if imgs.len() == len {
imgs.push(next);
}
let k = (imgs.len() - 1).min(n as usize);
let img = imgs.get(k)?.clone();
let base = imgs.first()?.size;
// Level k covers size·2^k base texels (the last row/column may be padding).
let f = (1u64 << k) as f32;
let uv = [self.base_uv[0] * base[0] as f32 / (img.size[0] as f32 * f).max(1.0), self.base_uv[1] * base[1] as f32 / (img.size[1] as f32 * f).max(1.0)];
Some((img, [uv[0].min(1.0), uv[1].min(1.0)]))
}
let imgs = images.lock().unwrap_or_else(PoisonError::into_inner);
let k = (imgs.len() - 1).min(n as usize);
let img = imgs.get(k)?.clone();
let base = imgs.first()?.size;
// Level k covers size·2^k base texels (the last row/column may be padding).
let f = (1u64 << k) as f32;
let uv = [base_uv[0] * base[0] as f32 / (img.size[0] as f32 * f).max(1.0), base_uv[1] * base[1] as f32 / (img.size[1] as f32 * f).max(1.0)];
Some((img, [uv[0].min(1.0), uv[1].min(1.0)]))
}
/// A copy of `d` for a helper thread (its profiles and transform are shared, not copied).
fn share_display(d: &CanvasDisplay) -> CanvasDisplay {
CanvasDisplay {
encode_srgb: d.encode_srgb,
source: Arc::clone(&d.source),
monitor: Arc::clone(&d.monitor),
transform: d.transform.clone(),
key: d.key,
texture_key: d.texture_key,
}
}
@@ -163,12 +301,21 @@ fn halve(img: &ColorImage) -> ColorImage {
let (nw, nh) = (w.div_ceil(2).max(1), h.div_ceil(2).max(1));
let mut out = vec![Color32::TRANSPARENT; nw * nh];
let px = |x: usize, y: usize| img.pixels.get(y.min(h.saturating_sub(1)) * w + x.min(w.saturating_sub(1))).copied().unwrap_or_default();
for (y, row) in out.chunks_mut(nw).enumerate() {
let row = |y: usize, row: &mut [Color32]| {
for (x, o) in row.iter_mut().enumerate() {
let q = [px(2 * x, 2 * y), px(2 * x + 1, 2 * y), px(2 * x, 2 * y + 1), px(2 * x + 1, 2 * y + 1)];
let avg = |c: fn(&Color32) -> u8| ((q.iter().map(|p| u32::from(c(p))).sum::<u32>() + 2) / 4) as u8;
*o = Color32::from_rgba_premultiplied(avg(Color32::r), avg(Color32::g), avg(Color32::b), avg(Color32::a));
}
};
#[cfg(not(target_arch = "wasm32"))]
{
use rayon::prelude::*;
out.par_chunks_mut(nw).enumerate().for_each(|(y, r)| row(y, r));
}
#[cfg(target_arch = "wasm32")]
for (y, r) in out.chunks_mut(nw).enumerate() {
row(y, r);
}
ColorImage::new([nw, nh], out)
}
+4 -1
View File
@@ -114,7 +114,7 @@ fn copy_arrow_to_tool_defaults(app: &mut PhotocraftApp, id: photocraft_doc::Laye
*end,
bounded(*width, 1.0, 4096.0),
bounded(*length, 1.0, 4096.0),
bounded(*concavity, 0.0, 100.0),
bounded(*concavity, -50.0, 50.0),
bounded(*weight, 1.0, 10000.0),
))
}
@@ -238,6 +238,9 @@ mod pen_enter_deselects_tests;
#[cfg(test)]
mod line_shift_snap_tests;
#[cfg(test)]
mod ellipse_shift_circle_tests;
#[cfg(test)]
mod pen_mode_menu_tests;
@@ -0,0 +1,76 @@
//! #13222: ⇧ while dragging with the Ellipse tool makes a circle from the shorter side of the
//! drag, as in the reference application, not the longer one; ⇧⌥ centres that circle on the
//! press. The drag preview (`shape_bounds`) shows the same box as the layer the drag makes.
use egui::Modifiers;
use photocraft_doc::{LayerContent, LiveShape};
use serde_json::json;
use super::shape_bounds;
use crate::PhotocraftApp;
use crate::canvas::{ToolEvent, tool_event};
use crate::state::Tool;
fn app() -> PhotocraftApp {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 800, "height": 600})).unwrap();
app.sync_views();
app.ui.tool = Tool::EllipseShape;
app
}
/// A drag pressed without modifiers, with `mods` pressed after the start (so the press picks no
/// path operation or eyedropper).
fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], mods: Modifiers) {
tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, Modifiers::NONE);
tool_event(app, ToolEvent::Move { x: (from[0] + to[0]) / 2.0, y: (from[1] + to[1]) / 2.0, pressure: 1.0 }, mods);
tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, mods);
tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, mods);
}
/// The active layer's live ellipse `[x, y, w, h]`.
fn ellipse_rect(app: &PhotocraftApp) -> [f64; 4] {
let st = app.session.active().unwrap();
match &st.doc.layer(st.active_layer.unwrap()).unwrap().content {
LayerContent::Shape(s) => match &s.live {
Some(LiveShape::Ellipse { rect }) => *rect,
other => panic!("a live ellipse, got {other:?}"),
},
_ => panic!("a shape layer"),
}
}
fn preview(app: &PhotocraftApp, from: [f64; 2], to: [f64; 2], mods: Modifiers) -> [f64; 4] {
shape_bounds(&app.ui.tool_options, Tool::EllipseShape, from, to, mods).expect("a box")
}
#[test]
fn shift_makes_a_circle_from_the_shorter_side() {
let mut app = app();
drag(&mut app, [400.0, 300.0], [600.0, 400.0], Modifiers::SHIFT);
assert_eq!(ellipse_rect(&app), [400.0, 300.0, 100.0, 100.0]);
assert_eq!(preview(&app, [400.0, 300.0], [600.0, 400.0], Modifiers::SHIFT), [400.0, 300.0, 500.0, 400.0]);
}
#[test]
fn shift_uses_the_shorter_side_when_the_drag_is_taller_than_wide() {
let mut app = app();
drag(&mut app, [400.0, 300.0], [450.0, 500.0], Modifiers::SHIFT);
assert_eq!(ellipse_rect(&app), [400.0, 300.0, 50.0, 50.0]);
assert_eq!(preview(&app, [400.0, 300.0], [450.0, 500.0], Modifiers::SHIFT), [400.0, 300.0, 450.0, 350.0]);
}
#[test]
fn shift_alt_centres_the_shorter_side_circle_on_the_press() {
let mut app = app();
let mods = Modifiers::SHIFT | Modifiers::ALT;
drag(&mut app, [400.0, 300.0], [600.0, 400.0], mods);
assert_eq!(ellipse_rect(&app), [300.0, 200.0, 200.0, 200.0]);
assert_eq!(preview(&app, [400.0, 300.0], [600.0, 400.0], mods), [300.0, 200.0, 500.0, 400.0]);
}
#[test]
fn shift_keeps_the_drag_direction_up_and_left() {
let app = app();
assert_eq!(preview(&app, [400.0, 300.0], [200.0, 200.0], Modifiers::SHIFT), [300.0, 200.0, 400.0, 300.0]);
}
@@ -0,0 +1,121 @@
//! #13258: arrowhead Concavity takes whole numbers from -50 % to 50 % in the Properties panel and
//! the Line tool's gear menu; a value typed past the range becomes the closest end and, once the
//! field is left, the reference's "Closest value inserted" alert with OK says so.
use egui::accesskit::Role;
use egui::vec2;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use photocraft_doc::{LayerContent, LayerId, LiveShape};
use serde_json::json;
use super::{CONCAVITY_RANGE_ALERT, shape_properties};
use crate::PhotocraftApp;
use crate::state::{DialogKind, Tool};
/// An 800 x 600 document with a weight 4 End arrow (5 x 10 px head) from 400,300 to 600,300.
fn app_with_arrow() -> (PhotocraftApp, LayerId) {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 800, "height": 600})).unwrap();
let made = app
.run("shape.create", json!({"kind": "line", "from": [400, 300], "to": [600, 300], "weight": 4, "arrowEnd": true, "arrowWidth": 5, "arrowLength": 10}))
.unwrap();
let id = LayerId(made["layer"].as_u64().unwrap());
(app, id)
}
/// True once `setup_context` installed the app's fonts (the first frame runs before it).
fn fonts_ready(ui: &egui::Ui) -> bool {
ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into())))
}
fn properties() -> (Harness<'static, PhotocraftApp>, LayerId) {
let (app, id) = app_with_arrow();
let mut h = Harness::builder().with_size(vec2(400.0, 900.0)).build_ui_state(
move |ui, app| {
if fonts_ready(ui) {
shape_properties(app, ui, id);
}
},
app,
);
PhotocraftApp::setup_context(&h.ctx, Default::default());
h.run_steps(4);
(h, id)
}
/// The options bar with the Line tool active, its arrowhead gear menu open.
fn gear() -> Harness<'static, PhotocraftApp> {
let (mut app, _) = app_with_arrow();
app.ui.tool = Tool::Line;
let mut h = Harness::builder().with_size(vec2(1800.0, 400.0)).build_ui_state(
|ui, app| {
if fonts_ready(ui) {
crate::panels::options_bar(app, ui);
}
},
app,
);
PhotocraftApp::setup_context(&h.ctx, Default::default());
h.run_steps(4);
h.query_by_label("Arrowhead options").expect("the arrowhead gear").click();
h.run_steps(3);
h
}
/// Types `text` into the Concavity field, then Tabs out of it.
fn type_concavity(h: &mut Harness<'static, PhotocraftApp>, text: &str) {
h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some("Concavity")).expect("the Concavity 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::Tab);
h.run_steps(3);
}
fn alerts(h: &Harness<'static, PhotocraftApp>) -> Vec<String> {
h.state().ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).filter_map(|d| d.fields.get("message")?.as_str().map(str::to_owned)).collect()
}
fn concavity(h: &Harness<'static, PhotocraftApp>, id: LayerId) -> f64 {
match h.state().session.active().and_then(|st| st.doc.layer(id)).map(|l| &l.content) {
Some(LayerContent::Shape(sh)) => match sh.live {
Some(LiveShape::ArrowLine { concavity, .. }) => concavity,
_ => panic!("expected a live arrow"),
},
_ => panic!("expected a shape layer"),
}
}
#[test]
fn properties_concavity_in_range_is_applied_without_an_alert() {
for (typed, want) in [("-50", -50.0), ("-12", -12.0), ("25", 25.0), ("50", 50.0)] {
let (mut h, id) = properties();
type_concavity(&mut h, typed);
assert_eq!(concavity(&h, id), want, "{typed}");
assert!(alerts(&h).is_empty(), "{typed} is in range");
}
}
#[test]
fn properties_concavity_past_the_range_takes_the_closest_value_and_alerts() {
for (typed, want) in [("-60", -50.0), ("60", 50.0)] {
let (mut h, id) = properties();
type_concavity(&mut h, typed);
assert_eq!(concavity(&h, id), want, "{typed}");
assert_eq!(alerts(&h), vec![CONCAVITY_RANGE_ALERT.to_string()], "{typed}: one alert");
}
}
#[test]
fn gear_concavity_past_the_range_takes_the_closest_value_and_alerts() {
for (typed, want) in [("-60", -50.0), ("60", 50.0), ("-20", -20.0)] {
let mut h = gear();
assert!(h.query_all_by_role(Role::SpinButton).any(|n| n.accesskit_node().label().as_deref() == Some("Concavity")), "the gear menu is open");
type_concavity(&mut h, typed);
assert_eq!(h.state().ui.tool_options.arrow_concavity, want, "{typed}");
let expected: Vec<String> = if typed == "-20" { vec![] } else { vec![CONCAVITY_RANGE_ALERT.to_string()] };
assert_eq!(alerts(&h), expected, "{typed}");
}
}
+34 -7
View File
@@ -147,7 +147,13 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo
// Photoshop-style arrowhead settings at the right of Line options.
if tool == Tool::Line {
crate::widgets::vline(ui, 22.0);
ui.menu_image_button(crate::icons::image("settings", 18.0, t.icon), |ui| {
let mut concavity_alert = false;
// Stays open on clicks inside, like the Pen's gear: a click into a field to type a value
// would otherwise close the menu before the value was entered (#13258).
let config = egui::containers::menu::MenuConfig::new().close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside);
let gear = egui::Button::image(crate::icons::image("settings", 18.0, t.icon));
let menu = egui::containers::menu::MenuButton::from_button(gear).config(config);
let (gear, _) = menu.ui(ui, |ui| {
let o = &mut app.ui.tool_options;
ui.set_min_width(170.0);
ui.label(tl!("Arrowheads"));
@@ -165,16 +171,25 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo
ui.add(egui::DragValue::new(&mut o.arrow_length).range(1.0..=4096.0).suffix(" px"));
});
ui.horizontal(|ui| {
ui.label(tl!("Concavity"));
ui.add(egui::DragValue::new(&mut o.arrow_concavity).range(0.0..=100.0).suffix(" %"));
let label = tl!("Concavity");
ui.label(label);
concavity_alert = crate::widgets::value_field_whole_alerting(ui, label, &mut o.arrow_concavity, CONCAVITY_RANGE, "%", 52.0).1;
});
})
.response
.on_hover_text(tl!("Arrowhead options"));
});
gear.on_hover_text(tl!("Arrowhead options"));
if concavity_alert {
crate::panels::options_bar::range_alert(&mut app.ui, CONCAVITY_RANGE_ALERT);
}
}
true
}
/// Arrowhead Concavity in percent of the head's length, as the reference takes it (#13258).
pub(crate) const CONCAVITY_RANGE: std::ops::RangeInclusive<f32> = -50.0..=50.0;
/// The reference's alert for a Concavity typed past [`CONCAVITY_RANGE`] (#13258).
pub(crate) const CONCAVITY_RANGE_ALERT: &str = "An integer between -50% and 50% is required. Closest value inserted.";
/// Path mode's "Make:" row, as in Photoshop's options bar: Selection… (#5703), Mask (#12904) and
/// Shape (#10934), from the path being drawn or the active path; all greyed without one.
fn make_buttons(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
@@ -281,6 +296,7 @@ pub fn shape_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: photocra
};
let t = Tokens::get(ui.ctx());
let mut edit: Option<Value> = None;
let mut concavity_alert = false;
// A swatch picked in a Fill/Stroke popover joins the Recently Used Colors once the edit took it.
let mut recent: Option<[f32; 3]> = None;
let doc_id = app.session.active().map(|st| st.doc.id);
@@ -459,8 +475,12 @@ pub fn shape_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: photocra
}
});
ui.horizontal(|ui| {
let label = tl!("Concavity");
ui.label(egui::RichText::new(label).color(t.text_dim).size(12.0));
let mut v = *concavity as f32;
if num(ui, "Concavity", &mut v, 0.0..=100.0, "%") {
let (r, out_of_range) = crate::widgets::value_field_whole_alerting(ui, label, &mut v, CONCAVITY_RANGE, "%", 64.0);
concavity_alert |= out_of_range;
if r.changed() {
edit = Some(json!({"arrowConcavity": v, "coalesce": key("arrow-concavity")}));
}
});
@@ -527,8 +547,15 @@ pub fn shape_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: photocra
});
}
}
if concavity_alert {
crate::panels::options_bar::range_alert(&mut app.ui, CONCAVITY_RANGE_ALERT);
}
}
#[cfg(test)]
#[path = "line_arrow_concavity_field_tests.rs"]
mod line_arrow_concavity_field_tests;
#[cfg(test)]
#[path = "pen_make_mask_tests.rs"]
mod pen_make_mask_tests;
+4 -2
View File
@@ -112,11 +112,13 @@ pub(super) fn shape_geometry(o: &ToolOptions, tool: Tool, start: [f64; 2], end:
json!({"kind": "line", "from": from, "to": to, "weight": weight,
"arrowStart": o.arrow_start, "arrowEnd": o.arrow_end,
"arrowWidth": o.arrow_width, "arrowLength": o.arrow_length,
"arrowConcavity": o.arrow_concavity})
// Settings saved with the old 0..100 range draw at the nearest value (#13258).
"arrowConcavity": if o.arrow_concavity.is_finite() { o.arrow_concavity.round().clamp(-50.0, 50.0) } else { 0.0 }})
} else {
let (mut w, mut h) = (end[0] - start[0], end[1] - start[1]);
if mods.shift {
let m = w.abs().max(h.abs());
// The drag's shorter side sets the square, as in the reference application (#13222).
let m = w.abs().min(h.abs());
(w, h) = (m * w.signum(), m * h.signum());
}
let (x0, y0) = if mods.alt { (start[0] - w, start[1] - h) } else { (start[0], start[1]) };
+4 -4
View File
@@ -491,7 +491,7 @@ fn shape_drag_creates_layers_with_modifiers() {
finish_shape(&mut app, Tool::Rectangle, [10.0, 10.0], [60.0, 30.0], egui::Modifiers::SHIFT);
let st = app.session.active().unwrap();
let b = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds();
assert_eq!((b.width(), b.height()), (50, 50), "shift = square");
assert_eq!((b.width(), b.height()), (20, 20), "shift = square of the shorter side (#13222)");
finish_shape(&mut app, Tool::EllipseShape, [100.0, 100.0], [120.0, 110.0], egui::Modifiers::ALT);
let st = app.session.active().unwrap();
let b = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds();
@@ -694,9 +694,9 @@ fn shift_pressed_during_a_shape_drag_constrains_it() {
let l = st.doc.layer(st.active_layer.unwrap()).unwrap();
assert!(matches!(l.content, LayerContent::Shape(_)), "{tool:?} ({sides} sides): a shape layer");
let b = l.surface().unwrap().content_bounds();
// The drag is 60 × 30; constrained, the shape's box is 60 × 60 (a hexagon is narrower
// than its box, so the height tells).
assert!(b.height().abs_diff(60) <= 1 && b.width() <= 61, "{tool:?}: ⇧ mid-drag keeps proportions: {b:?}");
// The drag is 60 × 30; constrained, the shape's box is 30 × 30, the shorter side (#13222)
// (a hexagon is narrower than its box, so the height tells).
assert!(b.height().abs_diff(30) <= 1 && b.width() <= 31, "{tool:?}: ⇧ mid-drag keeps proportions: {b:?}");
}
}
@@ -0,0 +1,304 @@
//! Free Transform drag stalls (#11103).
//!
//! - Start: an open box moves from the first pointer move after the press, not once egui
//! recognises a drag (past its click distance), so it never jumps to catch up. Clicks keep their
//! rules: a click on the box moves nothing, a jittery click outside it on the image leaves it as
//! it was, a double-click on it commits.
//! - Mip levels: a level first needed mid-drag is built off the UI thread while the closest finer
//! level already uploaded stands in for it.
use std::time::{Duration, Instant};
use egui::{Color32, ColorImage, Modifiers, PointerButton, Pos2, vec2};
use egui_kittest::Harness;
use photocraft_doc::LayerId;
use serde_json::json;
use crate::PhotocraftApp;
use crate::canvas::ViewXform;
use crate::state::Tool;
use crate::transform_tex::PreviewTextures;
/// An 800 × 600 document at 100 % with a red block (x 100..300, y 100..300) on layer "Paint" and
/// Free Transform open on it.
fn harness() -> Harness<'static, PhotocraftApp> {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap();
app.sync_views();
app.ui.extras.rulers = false;
app.ui.extras.snap = false;
app.ui.tool = Tool::Move;
let paint = LayerId(app.run("layer.new.layer", json!({"name": "Paint"})).unwrap()["layer"].as_u64().unwrap());
app.run("layer.select", json!({"layer": paint.0})).unwrap();
app.run("select.rect", json!({"x": 100, "y": 100, "width": 200, "height": 200})).unwrap();
app.run("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap();
app.run("select.deselect", json!({})).unwrap();
// Frames 1/60 s apart, so two clicks make a double-click.
let mut h = Harness::builder().with_size(vec2(1100.0, 800.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut PhotocraftApp| {
let ctx = ui.ctx().clone();
if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {
return;
}
crate::shortcuts::handle(app, &ctx);
egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui));
},
app,
);
PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);
h.run_steps(4);
let v = &mut h.state_mut().ui.views[0];
v.zoom = 1.0;
v.center = [400.0, 300.0];
v.fit_pending = false;
h.run_steps(2);
let ctx = h.ctx.clone();
crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransform", json!({})).unwrap();
h.run_steps(2);
assert!(h.state().ui.transform.is_some(), "Free Transform is open");
h
}
fn view_xform(h: &Harness<'static, PhotocraftApp>) -> ViewXform {
let app = h.state();
let v = &app.ui.views[0];
ViewXform {
rect: crate::rulers::content_rect(app, app.last_canvas_rect),
zoom: v.zoom,
center: v.center,
flip: app.ui.view.flip_horizontal,
rotation: v.rotation,
aspect: app.ui.view.display_aspect(),
}
}
fn screen(h: &Harness<'static, PhotocraftApp>, x: f32, y: f32) -> Pos2 {
view_xform(h).to_screen(x, y)
}
fn quad(h: &Harness<'static, PhotocraftApp>) -> [[f64; 2]; 4] {
h.state().ui.transform.as_ref().expect("the box is open").quad
}
fn steps(h: &Harness<'static, PhotocraftApp>) -> usize {
h.state().session.active().unwrap().history.past_len()
}
fn button(h: &mut Harness<'static, PhotocraftApp>, p: Pos2, down: bool) {
h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: down, modifiers: Modifiers::NONE });
h.run_steps(1);
}
/// Hover document point `(x, y)`, then press there.
fn press(h: &mut Harness<'static, PhotocraftApp>, x: f32, y: f32) {
let p = screen(h, x, y);
h.event(egui::Event::PointerMoved(p));
h.run_steps(1);
button(h, p, true);
}
/// One frame with the pointer at document point `(x, y)`.
fn move_to(h: &mut Harness<'static, PhotocraftApp>, x: f32, y: f32) {
let p = screen(h, x, y);
h.event(egui::Event::PointerMoved(p));
h.run_steps(1);
}
fn release(h: &mut Harness<'static, PhotocraftApp>, x: f32, y: f32) {
let p = screen(h, x, y);
button(h, p, false);
h.run_steps(1);
}
/// How far the box's top-left corner is from `from`.
fn offset(h: &Harness<'static, PhotocraftApp>, from: [[f64; 2]; 4]) -> [f64; 2] {
let q = quad(h);
[q[0][0] - from[0][0], q[0][1] - from[0][1]]
}
fn near(a: [f64; 2], b: [f64; 2]) -> bool {
(a[0] - b[0]).abs() < 1e-3 && (a[1] - b[1]).abs() < 1e-3
}
#[test]
fn the_box_moves_from_the_first_pointer_move_after_the_press() {
let mut h = harness();
let start = quad(&h);
press(&mut h, 200.0, 200.0);
assert!(near(offset(&h, start), [0.0, 0.0]), "the press alone moves nothing: {:?}", offset(&h, start));
// 3 px: inside egui's click distance, so no drag is recognised yet.
move_to(&mut h, 203.0, 200.0);
assert!(near(offset(&h, start), [3.0, 0.0]), "the first move moves the box: {:?}", offset(&h, start));
move_to(&mut h, 240.0, 220.0);
assert!(near(offset(&h, start), [40.0, 20.0]), "{:?}", offset(&h, start));
release(&mut h, 240.0, 220.0);
assert!(h.state().ui.transform.is_some(), "a drag doesn't close the box");
assert!(near(offset(&h, start), [40.0, 20.0]), "{:?}", offset(&h, start));
}
#[test]
fn the_box_keeps_up_with_every_move_with_no_jump_when_the_drag_is_recognised() {
let mut h = harness();
let start = quad(&h);
press(&mut h, 200.0, 200.0);
// One pixel a frame, through egui's click distance and past it.
for dx in 1..=16 {
move_to(&mut h, 200.0 + dx as f32, 200.0);
let got = offset(&h, start);
assert!(near(got, [f64::from(dx), 0.0]), "after a {dx} px move the box is {got:?} off");
}
release(&mut h, 216.0, 200.0);
assert!(near(offset(&h, start), [16.0, 0.0]), "{:?}", offset(&h, start));
}
#[test]
fn a_click_on_the_box_moves_nothing_and_keeps_it_open() {
let mut h = harness();
let (start, before) = (quad(&h), steps(&h));
press(&mut h, 200.0, 200.0);
release(&mut h, 200.0, 200.0);
assert!(h.state().ui.transform.is_some());
assert_eq!(quad(&h), start);
assert_eq!(steps(&h), before);
}
#[test]
fn a_jittery_click_outside_the_box_on_the_image_leaves_it_as_it_was() {
let mut h = harness();
let (start, pivot) = (quad(&h), h.state().ui.transform.as_ref().unwrap().pivot);
// Only the Background has pixels here (#11100): the box stays open.
press(&mut h, 600.0, 450.0);
move_to(&mut h, 601.0, 450.0);
release(&mut h, 601.0, 450.0);
let t = h.state().ui.transform.as_ref().expect("the box stays open");
assert_eq!((t.quad, t.pivot), (start, pivot), "the jitter's turn is put back");
}
#[test]
fn a_double_click_on_the_box_still_commits() {
let mut h = harness();
// Moved 10 px first: committing an unchanged box adds no History step.
let t = h.state_mut().ui.transform.as_mut().unwrap();
t.quad = t.quad.map(|[x, y]| [x + 10.0, y]);
t.pivot[0] += 10.0;
h.run_steps(1);
let before = steps(&h);
press(&mut h, 200.0, 200.0);
let p = screen(&h, 200.0, 200.0);
button(&mut h, p, false);
button(&mut h, p, true);
button(&mut h, p, false);
h.run_steps(2);
assert!(h.state().ui.transform.is_none(), "committed");
assert_eq!(steps(&h), before + 1);
}
/// Waits until `t` has no mip level building off the UI thread.
fn wait_for_builds(t: &PreviewTextures) {
let start = Instant::now();
while t.is_building() {
assert!(start.elapsed() < Duration::from_secs(10), "a mip level never finished building");
std::thread::sleep(Duration::from_millis(2));
}
}
/// A 5 × 3 white image with background builds on: level 1 is 3 × 2 texels covering 6 × 4 base
/// texels, level 3 is 1 × 1 covering 8 × 8.
fn textures(ctx: &egui::Context) -> PreviewTextures {
let mut t = PreviewTextures::new(ctx, "drag-mips".into(), ColorImage::new([5, 3], vec![Color32::WHITE; 15]), [1.0, 1.0]);
t.set_background_builds(true);
t
}
#[test]
fn a_mip_level_first_needed_mid_drag_is_built_off_the_ui_thread() {
let ctx = egui::Context::default();
let t = textures(&ctx);
let (full, full_uv) = t.pick(&ctx, 1.0, 1.0, false);
// Shrunk past ½: level 1 is wanted, level 0 shows until it is ready.
let (shown, uv) = t.pick(&ctx, 0.3, 1.0, false);
assert_eq!((shown, uv), (full, full_uv), "the full-resolution level stands in");
wait_for_builds(&t);
let (built, uv) = t.pick(&ctx, 0.3, 1.0, false);
assert_ne!(built, full, "level 1 has its own texture once built");
assert!((uv[0] - 5.0 / 6.0).abs() < 1e-6 && (uv[1] - 3.0 / 4.0).abs() < 1e-6, "{uv:?}");
assert_eq!(t.pick(&ctx, 0.3, 1.0, false).0, built, "cached");
ctx.tex_manager().write().take_delta().clear();
}
#[test]
fn the_closest_finer_level_stands_in_while_a_level_builds() {
let ctx = egui::Context::default();
let t = textures(&ctx);
let full = t.pick(&ctx, 1.0, 1.0, false).0;
let _ = t.pick(&ctx, 0.3, 1.0, false);
wait_for_builds(&t);
let level1 = t.pick(&ctx, 0.3, 1.0, false).0;
// log2(1 / 0.1) = 3.3: level 3 is wanted; level 1 is the closest one uploaded.
assert_eq!(t.pick(&ctx, 0.1, 1.0, false).0, level1);
wait_for_builds(&t);
let level3 = t.pick(&ctx, 0.1, 1.0, false).0;
assert!(level3 != level1 && level3 != full, "level 3 has its own texture once built");
ctx.tex_manager().write().take_delta().clear();
}
#[test]
fn a_level_with_nothing_finer_uploaded_for_the_display_is_built_at_once() {
let mut session = photocraft_engine::Session::new();
session.execute("file.new", json!({"width": 2, "height": 1})).unwrap();
let doc = session.active().unwrap().doc.clone();
session.color.settings.monitor_profile = "display-p3".into();
let p3 = session.color.canvas_display(&doc).unwrap();
assert!(!p3.is_identity());
let ctx = egui::Context::default();
let t = textures(&ctx);
let full = t.pick(&ctx, 1.0, 1.0, false).0;
// Only the unconverted level 0 is uploaded: nothing can stand in for this monitor.
let (shown, uv) = t.pick_display(&ctx, 0.3, 1.0, false, Some(&p3));
assert!(!t.is_building(), "built in this frame");
assert_ne!(shown, full);
assert!((uv[0] - 5.0 / 6.0).abs() < 1e-6 && (uv[1] - 3.0 / 4.0).abs() < 1e-6, "{uv:?}");
ctx.tex_manager().write().take_delta().clear();
}
/// A box closed while two levels were still building: neither worker converts or uploads its
/// level, though each still holds the preview's shared state (#13382 review). Counted as uploads,
/// not as textures left, which an upload freed again at once would also pass.
#[test]
fn levels_finishing_after_the_box_closed_are_not_uploaded() {
let ctx = egui::Context::default();
let t = textures(&ctx);
let _ = t.pick(&ctx, 1.0, 1.0, false);
let (gate, done, uploads) = t.worker_hooks();
let held = gate.lock().unwrap();
// Levels 1 and 3, each on its own worker, both paused before they check the box is open.
let _ = t.pick(&ctx, 0.3, 1.0, false);
let _ = t.pick(&ctx, 0.1, 1.0, false);
drop(t);
drop(held);
let start = Instant::now();
while !done() {
assert!(start.elapsed() < Duration::from_secs(10), "the workers finish");
std::thread::sleep(Duration::from_millis(2));
}
assert_eq!(uploads.load(std::sync::atomic::Ordering::Relaxed), 0, "nothing uploaded for the closed box");
ctx.tex_manager().write().take_delta().clear();
}
/// The same two workers with the box still open: both upload, so the count above means something.
#[test]
fn levels_finishing_while_the_box_is_open_are_uploaded() {
let ctx = egui::Context::default();
let t = textures(&ctx);
let _ = t.pick(&ctx, 1.0, 1.0, false);
let (_, done, uploads) = t.worker_hooks();
let _ = t.pick(&ctx, 0.3, 1.0, false);
let _ = t.pick(&ctx, 0.1, 1.0, false);
let start = Instant::now();
while !done() {
assert!(start.elapsed() < Duration::from_secs(10), "the workers finish");
std::thread::sleep(Duration::from_millis(2));
}
assert_eq!(uploads.load(std::sync::atomic::Ordering::Relaxed), 2);
ctx.tex_manager().write().take_delta().clear();
}
+17 -3
View File
@@ -68,11 +68,12 @@ fn value_field_alerting_in(
let draft = ui.ctx().data(|d| d.get_temp::<(f32, f32, Option<egui::Id>)>(draft_id));
let draft = draft.filter(|(_, stored, field)| *stored == *value && field.is_some_and(|f| ui.ctx().memory(|m| m.has_focus(f))));
let mut typed = draft.map_or(*value, |(typed, _, _)| typed);
// Read before the field: it consumes the arrow keys it steps with, and the wheel it steps
// with while focused never shows in the scroll delta. A step past the ends is no typing.
let stepped = ui.input(|i| i.key_pressed(egui::Key::ArrowUp) || i.key_pressed(egui::Key::ArrowDown)) || crate::field_wheel::focused_field_wheeled(ui.ctx());
// The field's own range is wide, so the typed value reaches here unclamped.
let r = value_field_named(ui, name, &mut typed, -1.0e9..=1.0e9, suffix, width);
// A step past the ends is no typed value (#13304). Only a step the field took counts: a wheel
// event that moves less than a notch (or not at all) steps nothing, and must not drop what was
// typed.
let stepped = stepped_this_pass(ui.ctx(), r.id);
let out_id = r.id.with("out-of-range");
if r.gained_focus() {
ui.ctx().data_mut(|d| d.remove_temp::<bool>(out_id));
@@ -350,6 +351,8 @@ fn value_field_box(
// The text stays selected, as in Photoshop: typing after a step replaces the value.
crate::field_tab::select_all(ui.ctx(), resp.id, &if fine { fmt_num2(f64::from(*value)) } else { fmt_num(f64::from(*value)) });
}
let pass = ui.ctx().cumulative_pass_nr();
ui.data_mut(|d| d.insert_temp(stepped_id(resp.id), pass));
resp.mark_changed();
}
if ui.memory(|m| m.has_focus(resp.id)) {
@@ -358,6 +361,17 @@ fn value_field_box(
(resp, rect)
}
/// Where a value field records the pass in which an arrow key or wheel notch last stepped it.
fn stepped_id(field: egui::Id) -> egui::Id {
field.with("stepped-pass")
}
/// Whether the value field `field` was stepped this pass by an arrow key or a wheel notch.
fn stepped_this_pass(ctx: &egui::Context, field: egui::Id) -> bool {
let pass = ctx.cumulative_pass_nr();
ctx.data(|d| d.get_temp::<u64>(stepped_id(field))) == Some(pass)
}
/// Width of the ▾ that opens a [`popup_value_field`]'s slider, inside the field's box.
pub const POPUP_ARROW_W: f32 = 14.0;
@@ -96,7 +96,7 @@ fn a_first_use_starts_with_the_tip() {
#[test]
fn other_tools_and_session_strokes_keep_their_tips() {
for tool in [Tool::Pencil, Tool::Eraser] {
for tool in [Tool::Eraser, Tool::Blur] {
let mut a = app();
pick(&mut a, tool);
scramble(&mut a);
@@ -85,7 +85,7 @@ fn reset_all_tools_from_the_brush_gives_the_other_tools_the_default_tip() {
let mut app = app();
pick(&mut app, Tool::Brush);
control(&mut app, "ui.menu.invoke", json!({"id": "tool.resetAll", "params": {"confirmed": true}}));
for tool in [Tool::Pencil, Tool::Eraser] {
for tool in [Tool::Eraser, Tool::Blur] {
pick(&mut app, tool);
assert_eq!(tip(&mut app), DEFAULT_TIP, "{tool:?}");
}
@@ -93,7 +93,7 @@ fn reset_all_tools_from_the_brush_gives_the_other_tools_the_default_tip() {
#[test]
fn other_painting_tools_keep_the_default_reset_tip() {
for tool in [Tool::Pencil, Tool::Eraser] {
for tool in [Tool::Eraser, Tool::Blur] {
let mut a = app();
pick(&mut a, tool);
scramble(&mut a);
+29 -1
View File
@@ -158,13 +158,41 @@ fn frames(h: &mut Harness, c: Case) -> (Pixels, Pixels, Pixels, bool) {
times.sort_by(f64::total_cmp);
// Pointer move → stroke rendered → frame built (canvas refresh and upload included).
eprintln!("{c:?}: move-to-frame median {:.2} ms, max {:.2} ms", times[times.len() / 2], times[times.len() - 1]);
let drawing = canvas(h);
// The pointer stays held at its last point, as a mouse held still repeats its position.
let held = |h: &mut Harness| {
control(h, "ui.pointer", json!({"events": [{"kind": "move", "x": last.0, "y": last.1, "pressure": pressure(1.0)}]}));
canvas(h)
};
let drawing = settled(h, held);
let gpu = h.state().perf.gpu && !c.flip;
control(h, "ui.pointer", json!({"events": [{"kind": "up", "x": last.0, "y": last.1}]}));
let done = canvas(h);
(before, drawing, done, gpu)
}
/// The canvas once the live stroke has stopped changing (#13477). The stroke paints on its own
/// thread and a frame waits only a few real ms for it, so on a slow machine its newest step
/// arrives late, and only a later pointer event shows it; release would then paint the rest.
/// `picture` holds the pointer still and takes a picture, with short real waits between them,
/// until the stroke is idle and three pictures in a row match (matching pixels alone don't prove
/// a slow step has finished): at most `TRIES` times, so a canvas that never settles fails
/// instead of hanging or comparing an unsettled picture.
fn settled(h: &mut Harness, picture: impl Fn(&mut Harness) -> Pixels) -> Pixels {
const TRIES: usize = 80;
let mut last = picture(h);
let mut unchanged = 0;
for _ in 0..TRIES {
std::thread::sleep(std::time::Duration::from_millis(25));
let next = picture(h);
unchanged = if next == last { unchanged + 1 } else { 0 };
last = next;
if unchanged >= 2 && !h.state().live_stroke_busy() {
return last;
}
}
panic!("the live stroke did not settle before release");
}
fn max_diff(a: &[[u8; 4]], b: &[[u8; 4]]) -> u8 {
assert_eq!(a.len(), b.len());
a.iter().zip(b).flat_map(|(p, q)| (0..3).map(move |i| p[i].abs_diff(q[i]))).max().unwrap_or(0)
@@ -0,0 +1,138 @@
//! Arrowhead Concavity is -50..50 % of the head's length, as in Photoshop (#13258): the middle of
//! the head's rear edge bends toward the tip for a positive value and away from it for a negative
//! one, and the shaft ends where that bent edge crosses the shaft's edge. Joining the shaft and
//! the heads into one outline is #13260; these tests check the anchors the reference outline has
//! and that the subpaths (each filled and combined, as the rasterizer does) cover what it covers.
use super::*;
/// The measured setup: weight 4, head width 5 and length 10, drag 400,300 to 600,300.
fn arrow(start: bool, end: bool, concavity: f64) -> Path {
arrow_line((400.0, 300.0), (600.0, 300.0), 4.0, start, end, 5.0, 10.0, concavity)
}
fn anchors(sp: &Subpath) -> Vec<[f64; 2]> {
sp.knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect()
}
fn close(a: [f64; 2], b: [f64; 2]) -> bool {
(a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9
}
fn same(sp: &Subpath, want: &[[f64; 2]], what: &str) {
let got = anchors(sp);
assert!(got.len() == want.len() && got.iter().zip(want).all(|(g, w)| close(*g, *w)), "{what}: {got:?} != {want:?}");
}
/// Whether `pt` is inside any subpath of `p` (each a polygon, combined as a union).
fn covers(p: &Path, pt: [f64; 2]) -> bool {
p.subpaths.iter().any(|sp| {
let a = anchors(sp);
let mut inside = false;
for i in 0..a.len() {
let (p0, p1) = (a[i], a[(i + 1) % a.len()]);
if (p0[1] > pt[1]) != (p1[1] > pt[1]) && pt[0] < p0[0] + (pt[1] - p0[1]) / (p1[1] - p0[1]) * (p1[0] - p0[0]) {
inside = !inside;
}
}
inside
})
}
/// Every anchor of the reference's one-outline result is an anchor of `p`.
fn has_reference_anchors(p: &Path, reference: &[[f64; 2]]) {
let all: Vec<[f64; 2]> = p.subpaths.iter().flat_map(anchors).collect();
for r in reference {
assert!(all.iter().any(|a| close(*a, *r)), "reference anchor {r:?} missing from {all:?}");
}
}
#[test]
fn minus_fifty_bends_the_base_away_from_the_tip_and_the_shaft_ends_where_it_crosses() {
let p = arrow(false, true, -50.0);
assert_eq!(p.subpaths.len(), 2);
same(&p.subpaths[0], &[[400.0, 302.0], [589.0, 302.0], [589.0, 298.0], [400.0, 298.0]], "shaft to 589");
// Tip, outer corners, and the base's middle 5 px (50 % of 10) behind the base at 590.
same(&p.subpaths[1], &[[600.0, 300.0], [590.0, 302.5], [585.0, 300.0], [590.0, 297.5]], "end head");
has_reference_anchors(&p, &[[400.0, 302.0], [400.0, 298.0], [589.0, 298.0], [590.0, 297.5], [600.0, 300.0], [590.0, 302.5], [589.0, 302.0]]);
}
#[test]
fn fifty_bends_both_bases_toward_their_tips_by_five_px() {
let p = arrow(true, true, 50.0);
assert_eq!(p.subpaths.len(), 3);
// The shaft's ends follow the bent bases to their middles, filling the wedge in front of them.
same(&p.subpaths[0], &[[409.0, 302.0], [591.0, 302.0], [595.0, 300.0], [591.0, 298.0], [409.0, 298.0], [405.0, 300.0]], "shaft 409..591");
same(&p.subpaths[1], &[[400.0, 300.0], [410.0, 302.5], [405.0, 300.0], [410.0, 297.5]], "start head");
same(&p.subpaths[2], &[[600.0, 300.0], [590.0, 302.5], [595.0, 300.0], [590.0, 297.5]], "end head");
has_reference_anchors(
&p,
&[
[409.0, 302.0],
[410.0, 302.5],
[400.0, 300.0],
[410.0, 297.5],
[409.0, 298.0],
[591.0, 298.0],
[590.0, 297.5],
[600.0, 300.0],
[590.0, 302.5],
[591.0, 302.0],
],
);
}
#[test]
fn zero_keeps_a_flat_base_and_the_shaft_ends_at_it() {
let p = arrow(false, true, 0.0);
assert!(close(anchors(&p.subpaths[0])[1], [590.0, 302.0]));
assert!(close(anchors(&p.subpaths[1])[2], [590.0, 300.0]));
}
#[test]
fn values_past_fifty_draw_as_fifty_so_older_documents_still_open() {
assert_eq!(arrow(true, true, 80.0), arrow(true, true, 50.0));
assert_eq!(arrow(true, true, 100.0), arrow(true, true, 50.0));
assert_eq!(arrow(true, true, -90.0), arrow(true, true, -50.0));
assert_eq!(arrow(true, true, f64::NAN), arrow(true, true, 0.0));
}
#[test]
fn a_head_no_wider_than_the_shaft_meets_it_at_the_base_whatever_the_concavity() {
for c in [-50.0, 0.0, 50.0] {
let p = arrow_line((400.0, 300.0), (600.0, 300.0), 6.0, false, true, 5.0, 10.0, c);
assert!(close(anchors(&p.subpaths[0])[1], [590.0, 303.0]), "concavity {c}");
}
}
#[test]
fn long_heads_bent_away_never_turn_the_shaft_inside_out() {
for (start, end) in [(true, true), (false, true), (true, false)] {
let p = arrow_line((0.0, 0.0), (20.0, 0.0), 4.0, start, end, 30.0, 50.0, -50.0);
let shaft = anchors(&p.subpaths[0]);
assert!(shaft[0][0] <= shaft[1][0], "{start} {end}: {shaft:?}");
assert!(p.subpaths.iter().flat_map(anchors).all(|a| a[0].is_finite() && a[1].is_finite()));
}
}
#[test]
fn a_base_bent_toward_the_tip_leaves_no_hole_and_nothing_past_the_flanks() {
let p = arrow(true, true, 50.0);
// The reference outline has no edge between the shaft's end and the bent base's middle.
for pt in [[593.0, 300.0], [594.5, 300.0], [592.0, 299.0], [407.0, 300.0], [405.5, 300.0], [408.0, 301.0]] {
assert!(covers(&p, pt), "{pt:?} is inside the reference outline");
}
// Between x 591 and 600 the flanks are inside the shaft's width (298.25 at x 593).
for pt in [[593.0, 298.1], [593.0, 301.9], [407.0, 298.1], [407.0, 301.9]] {
assert!(!covers(&p, pt), "{pt:?} is outside the reference outline");
}
// Outside the shaft's width, the notch stays open between the base and the flank's corner.
assert!(!covers(&p, [590.6, 297.9]));
}
#[test]
fn a_head_no_wider_than_the_shaft_still_fills_the_wedge_its_bent_base_leaves() {
let p = arrow_line((400.0, 300.0), (600.0, 300.0), 6.0, false, true, 5.0, 10.0, 50.0);
same(&p.subpaths[0], &[[400.0, 303.0], [590.0, 303.0], [590.0, 302.5], [595.0, 300.0], [590.0, 297.5], [590.0, 297.0], [400.0, 297.0]], "shaft");
assert!(covers(&p, [592.0, 300.0]));
}
+38 -25
View File
@@ -235,8 +235,10 @@ pub fn line(a: (f64, f64), b: (f64, f64), weight: f64) -> Path {
/// A filled vector line with optional arrowheads at its endpoints (#6408).
/// `width` and `length` measure the head in document pixels, independently of the shaft weight.
/// `concavity` is 0..100 percent: 0 has a flat rear edge, 100 a deep V-shaped notch.
/// The shaft stops at the notch, so a concave head remains concave after filling.
/// `concavity` is -50..50 percent of `length`: the middle of the head's rear edge bends that far
/// toward the tip (positive) or away from it (negative); 0 is flat. Values outside are clamped, so
/// documents saved with the old 0..100 range still open (#13258). The shaft stops where the bent
/// rear edge crosses the shaft's edge, so a concave head stays open after filling.
// The arguments correspond to the stored LiveShape::ArrowLine parameters.
#[allow(clippy::too_many_arguments)]
pub fn arrow_line(a: (f64, f64), b: (f64, f64), weight: f64, start: bool, end: bool, width: f64, length: f64, concavity: f64) -> Path {
@@ -256,34 +258,41 @@ pub fn arrow_line(a: (f64, f64), b: (f64, f64), weight: f64, start: bool, end: b
let (vx, vy) = (-uy, ux);
let size = (if length.is_finite() { length.max(1.0) } else { 1.0 }).min(distance * if start && end { 0.49 } else { 0.9 });
let half = (if width.is_finite() { width.max(1.0) } else { 1.0 }) / 2.0;
let requested_notch = concavity.clamp(0.0, 100.0) / 100.0;
// Preserve 0..50%. Beyond that compress the usable range so the head never collapses.
let max_notch = 0.75;
let notch = if requested_notch <= 0.5 { requested_notch } else { 0.5 + (requested_notch - 0.5) * (max_notch - 0.5) / 0.5 };
// Put the shaft up to the notch, leaving the head's concave edges visible.
let inner = size * (1.0 - notch);
// The rear edge's bend toward the tip as a fraction of `size` (negative: away from the tip).
let notch = if concavity.is_finite() { concavity.clamp(-50.0, 50.0) / 100.0 } else { 0.0 };
let hw = weight.max(0.1) / 2.0;
// The rear edge runs straight from each outer corner to its bent middle, so where it crosses
// the shaft's edge it is bent by `notch` times how far that edge is from the corner; a head no
// wider than the shaft meets it at its base. A head bent away from its tip reaches past its
// base, so the shaft is capped to never turn inside out.
let inner = (size * (1.0 - notch * (1.0 - (hw / half).min(1.0)))).min(if start && end { distance / 2.0 } else { distance });
let shaft_a = if start { (a.0 + ux * inner, a.1 + uy * inner) } else { a };
let shaft_b = if end { (b.0 - ux * inner, b.1 - uy * inner) } else { b };
let hw = weight.max(0.1) / 2.0;
let mut pieces = vec![Subpath::polygon(&[
(shaft_a.0 + vx * hw, shaft_a.1 + vy * hw),
(shaft_b.0 + vx * hw, shaft_b.1 + vy * hw),
(shaft_b.0 - vx * hw, shaft_b.1 - vy * hw),
(shaft_a.0 - vx * hw, shaft_a.1 - vy * hw),
])];
// The tip, both outer corners of the head and the recessed midpoint.
// Positive `sign` points towards the tail of the head (away from its tip).
let mut head = |tip: (f64, f64), sign: f64| {
let side = |p: (f64, f64), d: f64| (p.0 + vx * d, p.1 + vy * d);
// A head's tip, both outer corners and its rear edge's bent middle. Positive `sign` points
// toward the tail of the head (away from its tip).
let head = |tip: (f64, f64), sign: f64| {
let base = (tip.0 + ux * sign * size, tip.1 + uy * sign * size);
let rear_middle = (base.0 - ux * sign * size * notch, base.1 - uy * sign * size * notch);
pieces.push(Subpath::polygon(&[tip, (base.0 + vx * half, base.1 + vy * half), rear_middle, (base.0 - vx * half, base.1 - vy * half)]));
[tip, side(base, half), rear_middle, side(base, -half)]
};
if start {
head(a, 1.0);
}
if end {
head(b, -1.0);
}
let (start_head, end_head) = (start.then(|| head(a, 1.0)), end.then(|| head(b, -1.0)));
// A base bent toward the tip leaves a wedge between the shaft's end and the head that the
// reference fills: the shaft's end follows the bent base to its middle, so it fills the wedge
// without reaching past the head's flanks. A base bent away lies under the head already.
let wedge = |h: [(f64, f64); 4], from: usize, to: usize| -> Vec<(f64, f64)> {
if notch <= 0.0 {
return Vec::new();
}
let corners = hw > half;
[(corners, h[from]), (true, h[2]), (corners, h[to])].into_iter().filter_map(|(keep, p)| keep.then_some(p)).collect()
};
let mut shaft = vec![side(shaft_a, hw), side(shaft_b, hw)];
shaft.extend(end_head.map_or_else(Vec::new, |h| wedge(h, 1, 3)));
shaft.extend([side(shaft_b, -hw), side(shaft_a, -hw)]);
shaft.extend(start_head.map_or_else(Vec::new, |h| wedge(h, 3, 1)));
let mut pieces = vec![Subpath::polygon(&shaft)];
pieces.extend([start_head, end_head].into_iter().flatten().map(|h| Subpath::polygon(&h)));
// Never return non-finite arrow geometry.
// Large but valid scaled arrowheads remain unchanged.
if pieces.iter().flat_map(|sp| &sp.knots).any(|k| !k.anchor.x.is_finite() || !k.anchor.y.is_finite()) {
@@ -429,6 +438,10 @@ mod tests {
#[path = "star_outer_corner_radius_tests.rs"]
mod star_outer_corner_radius_tests;
#[cfg(test)]
#[path = "line_arrow_concavity_tests.rs"]
mod line_arrow_concavity_tests;
#[cfg(test)]
mod line_arrow_6408_tests {
use super::*;
+11 -9
View File
@@ -1,6 +1,6 @@
# Brush and painting parity
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** minor (Eraser's Erase to History, #10692; no estimate changed; Both Axes on Scatter headers, #3825 partial; Brush Tip Shape Spacing checkbox and percentage share one header, #3825 partial; Angle/Roundness fields left of the Brush Tip Shape widget, labels right-aligned, #3825 partial; the eraser end of the pen switches to the Eraser on Windows with Windows Ink on, #2285; no estimate changed; Art History Brush Opacity on the options bar, #10263; no estimate changed; Clone Stamp and Healing Brush clone from a source set in another open document; Shift+right-click menu for every painting tool: Edit Brush… and the tool's own Mode list; Brush Shift+right-click Mode picker and Escape dismissal; Art History Brush row added as partial, 8 of 10 styles, TOOL-213-20, #1610; hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; Mode for Clone Stamp, Pattern Stamp, History Brush, Healing and Paint Bucket; named, stateful Brush Settings locks and visible keyboard focus; independent Brush Pose tilt-axis overrides; Transfer Wetness/Mix tool applicability; dragged preset tip preview; Hue Jitter amount track; Brush Settings minimum fields follow their Control; checkbox-only rows and non-destructive Smoothing switch; shaped-tip cursor follows the view; Color Replacement is a live toolbar tool; no brush-feel estimate changed; 2026-10-11: Pattern Stamp and Background Eraser draw live, TOOL-213-7) · **Target:** Adobe Photoshop 2026
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-08 · **Change:** minor (Eraser's Erase to History, #10692; no estimate changed; Both Axes on Scatter headers, #3825 partial; parity refresh retains the expanded painting-menu limitations; right-click Brush Preset picker is partial while a pen barrel right-click with Windows Ink on still often paints a dot (#5364); Brush Tip Shape Spacing checkbox and percentage share one header, #3825 partial; Angle/Roundness fields left of the Brush Tip Shape widget, labels right-aligned, #3825 partial; the eraser end of the pen switches to the Eraser on Windows with Windows Ink on, #2285; no estimate changed; Art History Brush Opacity on the options bar, #10263; no estimate changed; Clone Stamp and Healing Brush clone from a source set in another open document; Shift+right-click menu for every painting tool: Edit Brush… and the tool's own Mode list; Brush Shift+right-click Mode picker and Escape dismissal; Art History Brush row added as partial, 8 of 10 styles, TOOL-213-20, #1610; hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; Mode for Clone Stamp, Pattern Stamp, History Brush, Healing and Paint Bucket; named, stateful Brush Settings locks and visible keyboard focus; independent Brush Pose tilt-axis overrides; Transfer Wetness/Mix tool applicability; dragged preset tip preview; Hue Jitter amount track; Brush Settings minimum fields follow their Control; checkbox-only rows and non-destructive Smoothing switch; shaped-tip cursor follows the view; Color Replacement is a live toolbar tool; no brush-feel estimate changed; 2026-10-11: Pattern Stamp and Background Eraser draw live, TOOL-213-7) · **Target:** Adobe Photoshop 2026
Painting is where Photoshop users notice differences first, so it gets its own checklist: the
brush engine (`crates/paint/src/brush.rs`), the Brush Settings UI
@@ -48,7 +48,7 @@ tablets against Photoshop side by side.
| Pressure drives size/opacity/flow per sample (no shared pressure within a frame) | done | #2112 |
| Global pressure curve in Preferences | done | #2195 |
| Per-control pressure curves | done | TOOL-213-11: each dynamic's own curve (`paint/src/brush.rs` `Dynamic::curve`, `paint/src/dynamics.rs` `dynamic_value`), behind each Control row's curve button (`brush_sections.rs`, `brush_panel/tests.rs` `a_dynamic_gets_its_own_response_curve`, #3294) |
| Quick taps keep their pressure | partial | #1967 fixed one case; tap paints a full blob (#1798), tap sensitivity (#1933) |
| Quick taps keep their pressure | partial | #1967 fixed one case; a tap paints at its own pressure (#1798, #2757); tap sensitivity still open (#1933) |
| Smooth pressure on Windows | partial | "jumpy" (#2046) |
| Tilt and rotation drive angle/roundness | partial | macOS, X11, web; not Windows; rotation not applied (#1301) |
| Eraser end of the pen switches to Eraser | partial | macOS, Windows (WinTab; Windows Ink not yet confirmed on hardware, #2285); X11 and web partial |
@@ -58,7 +58,7 @@ tablets against Photoshop side by side.
| Behaviour | Status | Evidence |
|---|---|---|
| No seams, hard edges stay hard, zero-scatter defaults, ABR tips never black | done | TOOL-213-13 |
| Smooth line weight along a pressure ramp | partial | stair-steps (#1776); 2026-10-23: the five hard-round built-in presets use 5% spacing (#8842), with rendered 150 px outline and pressure-opacity continuity regressions at 8/16/32-bit and 0/49% smoothing. Other brush-feel gaps remain open. |
| Smooth line weight along a pressure ramp | partial | stair-steps fixed by per-sample pressure (#1776, #2112); Windows still "jumpy" (#2046); 2026-10-23: the five hard-round built-in presets use 5% spacing (#8842), with rendered 150 px outline and pressure-opacity continuity regressions at 8/16/32-bit and 0/49% smoothing. Other brush-feel gaps remain open. |
| Interpolation and smoothing match Photoshop | partial | #2138, #2057 |
| Soft-edge falloff matches Photoshop's curve | partial | #2149, #1619 |
| Brush preview and cursor crisp, not pixelated | partial | #1433 |
@@ -80,8 +80,8 @@ tablets against Photoshop side by side.
| Hold `~` with the Brush or Pencil to erase with its brush: Clear mode while held (rebindable under Tools › Temporary) | done | `hold_keys.rs`, #3439 |
| Clear painting mode in the Brush and Pencil Mode menus | done | `paint_mode_dropdown` in `panels.rs`, `"mode": "clear"`, #3439 |
| Shift+right-click opens the painting tool's menu: Edit Brush… and its own Mode list (Brush/Pencil painting modes with Behind and Clear, stamps and History Brush blend modes, Eraser Brush/Pencil/Block, Dodge/Burn Range, Sponge mode, Healing Brush, Gradient and Paint Bucket modes); Behind and Clear greyed on the Background; Alt and Command/Ctrl keep their existing gestures | partial | #4929, `brush_mode_menu.rs`; rows set the options-bar state (`tools.setBrush` or the tool option); kittest and control regressions. Missing because the options bar lacks the setting: Behind for the stamps, History Brush, Gradient and Paint Bucket; the Blur/Sharpen/Smudge modes; the Spot Healing modes (no menu); the Healing Brush's Sampled/Pattern source and Replace; the History Brush source |
| Right-click opens the Brush Preset picker | done | [`context-menu-parity.md`](context-menu-parity.md); XP-Pen right-click not (#1980), macOS issue #2360 |
| Precise / normal / full-size tip cursors, crosshair in the tip | partial | Caps Lock precise cursor not audited; round Pencil cursor requested (#2662, #1057) |
| Right-click opens the Brush Preset picker | partial | [`context-menu-parity.md`](context-menu-parity.md); mouse right-click works; a pen barrel right-click (Wacom, XP-Pen) with Windows Ink on still often paints a dot instead (#5364 open; #1980 closed as a duplicate of #5905); macOS trackpad taps fixed (#2360, #2772) |
| Precise / normal / full-size tip cursors, crosshair in the tip | partial | Caps Lock precise cursor not audited; round Pencil cursor done (#2662, #2694), parity request open (#1057) |
| Brush choice kept per tool (Brush, Eraser, Blur each their own) | partial | #2542 |
## Symmetry
@@ -90,7 +90,7 @@ tablets against Photoshop side by side.
|---|---|
| Vertical, Horizontal, Dual axis, Diagonal | done |
| From a path (Make Symmetry Path) | done |
| Wavy, Circle, Spiral, Parallel Lines, Radial, Mandala | missing (#2659) |
| Wavy, Circle, Spiral, Parallel Lines, Radial, Mandala | missing (#2659 was closed after the existing symmetry control became available in every theme, #2704) |
## Brush-based tools
@@ -103,7 +103,7 @@ tablets against Photoshop side by side.
| Pattern Stamp (mode, aligned, impressionist) | done | |
| History Brush (mode) | done | |
| Art History Brush (styles, Area, Tolerance) | partial | 8 of 10 styles (no Tight Curl Long / Loose Curl Long); Area scales spacing, not Photoshop's coverage; no Mode on the options bar, no pen pressure (TOOL-213-20) |
| Spot Healing, Healing (Healing mode: Normal, Multiply, Screen, Darken, Lighten, Color, Luminosity) | partial | Healing's Replace mode and Spot Healing's Mode missing; grain not matched on flat colour (#2104), "horrible in general" (#1092), stops responding after switching (#1751) |
| Spot Healing, Healing (Healing mode: Normal, Multiply, Screen, Darken, Lighten, Color, Luminosity) | partial | Healing's Replace mode and Spot Healing's Mode missing; grain on flat colour kept by Create Texture (#2104, #2762); "horrible in general" (#1092), stops responding after switching (#1751) |
| Blur, Sharpen, Smudge (premultiplied, Sample All Layers, spacing) | done | BUG-207-2/3, #2171 |
| Dodge, Burn, Sponge | done | |
| Background Eraser, Magic Eraser | done | |
@@ -115,7 +115,7 @@ tablets against Photoshop side by side.
| Behaviour | Status | Evidence |
|---|---|---|
| .abr import (v1/v2/v6) and export, persistent presets, folders | done | `psd/src/abr.rs` |
| Brushes panel: drag a folder into a folder | missing | #2014 |
| Brushes panel: drag a folder into a folder | done | #2014, #3851 |
| Dragged brush preset preview | done | Cached, translucent tip thumbnail plus name in panel list/grid and the preset picker; `ui-egui/src/brushes_tab.rs`, real pointer-drag test in `brushes_tab_tests.rs` (#4225, partial) |
| Tool presets (.tpl) | partial | Tool Presets panel exists; .tpl import not found |
| Import 500 brushes without blocking the UI | not run | P24 |
@@ -127,7 +127,6 @@ tablets against Photoshop side by side.
| 2026-11-06 | minor | Eraser end of the pen switches to the Eraser on Windows with Windows Ink on (#2285); row stays partial (X11, web); no estimate changed |
| 2026-10-30 | minor | Art History Brush Opacity on the options bar, #10263; no estimate changed |
| 2026-10-25 | minor | Art History Brush row added as partial (8 of 10 styles, TOOL-213-20, #1610). No brush-feel estimate changed. |
| 2026-10-24 | minor | Stale rows corrected against main: Brush tip from an image file (TOOL-213-12, #3279) and per-control pressure curves (TOOL-213-11, #3294) are done; no brush-feel estimate changed |
| 2026-10-23 | minor | Hard-round built-in presets use 5% spacing (#8842); rendered large-tip outline and pressure-opacity continuity tests cover 8/16/32-bit and 0/49% smoothing. Other presets and user settings retain their spacing; percentages and estimates unchanged. |
| 2026-10-14 | minor | Brush Pose tilt overrides are independent end to end (#3825 partial); ABR flags, legacy JSON/commands, presets and three pixel depths covered; no readiness percentage or estimate changed |
| 2026-10-13 | minor | Stale "missing tool" row corrected against main: Color Replacement (`paint.colorReplacement`) is a live toolbar tool; no brush-feel estimate changed |
@@ -136,6 +135,7 @@ tablets against Photoshop side by side.
| 2026-10-11 | minor | `~` held with the Brush or Pencil erases with that tool's brush, and Clear joins their Mode menus (#3439) |
| 2026-10-12 | minor | Five Brush Settings switch rows toggle without selecting a properties pane; Smoothing has a default-on switch and retains its settings while disabled (#4283). No brush-feel estimate changed. |
| 2026-10-12 | minor | A shaped tip's cursor outline turns and flips with a rotated or flipped view, and follows pixel aspect correction |
| 2026-10-12 | minor | Rows refreshed against main: quick taps, pressure-ramp stair-steps, macOS right-click, round Pencil cursor, Clone Source W/H link, Spot Healing grain, brush-folder drag; the symmetry row no longer cites #2659 as the tracker |
| 2026-10-13 | minor | Shape Dynamics and Transfer minimum inputs follow their Control and retain their values while disabled (#3825, partial). No brush-feel estimate changed. |
| 2026-10-13 | minor | Hue Jitter uses the same themed amount slider as other jitter controls (#3825, partial). No brush-feel estimate changed. |
| 2026-10-13 | minor | Brush Tip Shape combines the Spacing checkbox and percentage into one header (#3825, partial), retaining the value while disabled. No brush-feel estimate changed. |
@@ -149,4 +149,6 @@ tablets against Photoshop side by side.
| 2026-10-23 | minor | Escape also consumes a held right-button release after a rapid second press, so the Brush Mode picker stays dismissed without painting or changing history (#4929). |
| 2026-10-30 | minor | Shift+right-click works for every painting tool as in the reference application: Edit Brush… opens the Brush Preset picker, then the tool's own Mode list from its options bar; Behind and Clear greyed on the Background. Row marked partial for the settings the options bar lacks. No brush-feel estimate changed. |
| 2026-10-30 | minor | Clone Stamp and Healing Brush clone from a source ⌥-clicked in another open document (the slot remembers its document and layer; its colour mode is converted as Paste converts; a closed source document is an error, not a silent sample of the painted one). No brush-feel estimate changed. |
| 2026-10-31 | minor | Merge keeps the expanded Shift+right-click painting-menu limitations alongside the refreshed macOS right-click and Pencil cursor evidence; brush-feel estimates unchanged |
| 2026-11-07 | minor | Eraser's Erase to History in Brush, Pencil and Block modes, with ⌥ at the press reversing it for that stroke; a layer missing from the source state paints from a single-layer state and is refused otherwise (#10692). No brush-feel estimate changed. |
| 2026-11-08 | minor | Right-click Brush Preset picker marked partial: a pen barrel right-click with Windows Ink on still often paints a dot (#5364) |
+1 -1
View File
@@ -28,7 +28,7 @@ The “PhotoCraft at branch point” column records behavior before this PR. Pic
| Brush, Pencil, Eraser, Background Eraser, Spot Healing, Healing, Clone Stamp, History Brush, Blur, Sharpen, Smudge, Dodge, Burn, Sponge | Brush preset, size and hardness where applicable | Picker | P0; [Adobe Brush Settings](https://helpx.adobe.com/photoshop/desktop/apply-painting-techniques/brushes-presets/create-brush-set-painting-options.html). Alt+secondary-drag on Windows and Control+Option-drag on macOS adjust size/hardness ([Adobe cursor shortcuts](https://helpx.adobe.com/in/photoshop/desktop/get-started/settings-and-preferences/change-tool-pointers.html)) |
| Gradient, Paint Bucket | Gradient preset/type/mode or fill source/tolerance **(inferred context placement)** | No tool menu | P1 |
| Type | In text: cut/copy/paste, spelling suggestions, text formatting; outside text: type-layer action **(inferred context placement)** | While editing text (canvas_tool_menu.rs `TYPE_EDIT_MENU`): Undo, Cut, Copy, Paste, Select All (on the text), Check Spelling…, Find and Replace Text…, Faux Bold/Italic (checked), Rasterize Type, Create Work Path, Convert to Shape, Horizontal/Vertical and the anti-alias modes (checked), Convert to Paragraph/Point Text, Warp Text…; Esc closes only the menu. Over a misspelled word the menu starts with up to 3 spelling suggestions (replace the word) and Add to Dictionary (#4370). Over committed type (no edit running, `TYPE_LAYER_MENU`, #7324): the same rows without Undo, Cut, Copy, Paste, Select All and Faux Bold/Italic; the clicked type becomes the active layer first (a layer multiselection stays). The Type Mask tools get no menu. Ignore / Ignore All remain open | P1; editing and nonediting states are separate; [Adobe type editing](https://helpx.adobe.com/photoshop/desktop/text-typography/get-started-with-text/edit-text.html) |
| Hand, Zoom | Fit on Screen, 100%, 200%, Print Size; zoom step choices **(inferred context placement)** | View menu (#3242, #6005): Fit on Screen, Fill Screen, 100%, 200%, Print Size, then Zoom In and Zoom Out after a separator. Zoom In/Out step about the right-clicked point (Preferences › Tools › Zoom Clicked Point to Center centres it). Outside the image the pasteboard menu still wins. | P1; view actions stay out of document history; row order still needs a dated Photoshop capture |
| Hand, Zoom | Fit on Screen, 100%, 200%, Print Size; zoom step choices **(inferred context placement)** | View menu (#3242, #6005): Fit on Screen, Fill Screen, 100%, 200%, Print Size, then Zoom In and Zoom Out after a separator. Zoom In/Out step about the right-clicked point (Preferences › Tools › Zoom Clicked Point to Center centres it). Outside the image the pasteboard menu still wins. Space's Hand over any tool opens it too, with the Hand's rows (#11271; the Hand's are the fixed zooms only since #12022), and outside the image the pasteboard menu. Under it a plain Esc closes only the menu and a plain Enter does nothing, so neither reaches a pending crop. A held zoom key opens none. | P1; view actions stay out of document history; row order still needs a dated Photoshop capture |
| Pen, Path Selection | Path/point actions, Make Selection, Fill/Stroke Path, Free Transform Path **(inferred context placement)** | Pen canvas right-click follows the user-provided 20-row Photoshop capture below. Paths rows offer Make Selection, Fill and Stroke. The Path Selection and Direct Selection tools open the same path menu for the selected path (#1056, 2026-10-15); node- and segment-specific rows remain open. | P1; distinguish node, segment, path, and blank canvas |
| Rectangle, Ellipse Shape, Triangle, Polygon, Line, Custom Shape | Shape/path operations, fill/stroke settings, transform **(inferred context placement)** | No tool menu | P2 |
| Slice, Slice Select | Slice properties, duplicate/delete, divide, guides **(inferred context placement)** | No tool menu | P2 |
+9 -7
View File
@@ -1,6 +1,6 @@
# Hardware parity
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Windows: flipping the pen to its eraser end selects the Eraser with Windows Ink on, #2285, not yet confirmed on a pen with an eraser end; optional WinTab backend on Windows: pressure and the eraser end; tilt on devices with orientation axes; rotation only with a pen and driver that report twist, with Windows Ink off) · **Target:** Adobe Photoshop 2026
> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-11-08 · **Change:** minor (Graphics Adapter choice on Linux, #1885; Camera Raw's preview develops its per-pixel stages on the GPU; GPU, Wayland (tilt and eraser end via Xwayland) and monitor-profile rows refreshed against main; Windows: flipping the pen to its eraser end selects the Eraser with Windows Ink on, #2285, not yet confirmed on a pen with an eraser end; previously minor: optional WinTab backend on Windows: pressure and the eraser end; tilt on devices with orientation axes; rotation only with a pen and driver that report twist, with Windows Ink off) · **Target:** Adobe Photoshop 2026
Each hardware feature Photoshop 2026 (27.11.0) uses, per platform, against PhotoCraft. Photoshop
side: its bundle (Metal and OpenCL paths, "Precise Color Management for HDR Display" and EDR
@@ -23,19 +23,19 @@ HDR display to verify.
| GPU compositing of layers, blend modes, effects | partial (Photoshop composites mostly on CPU) | wgpu compositor, ≤ 1/255 vs CPU oracle; Multichannel and > texture-limit regions fall back to CPU | done (ahead in places) |
| GPU compositor startup | available | Pipeline preparation runs in the background on native hardware; the CPU composites until ready. Windows WARP probe: 0.329 ms p95, 6.860 ms maximum device-work stall during two FXC builds; hardware measurements remain pending (#9157, #9364, #6419) | partial |
| GPU filters (Blur Gallery, Liquify, Smart Sharpen, Camera Raw) | yes | CPU (rayon) for filters; GPU for compose and effects. Camera Raw's preview runs its per-pixel stages (white balance to grain) in one wgpu pass, about 2-3 ms vs 11-28 ms on the CPU for the 858×572 proxy, depending on the machine, Shadows and Highlights (the local Laplacian filter) as fragment passes in front of it, 8.7-10.6 ms vs 147-300 ms, and Dehaze, Clarity and Texture (box, minimum and guided filters) as fragment passes too, 2.7-7.7 ms vs 7.6-17.7 ms each (Dehaze's dark channel opened as in the CPU develop, #9273); with all of them and every per-pixel stage 17-24 ms vs 222 ms on an RTX 5060 Ti. Detail, Calibration and OK still develop on the CPU (#6916) | partial |
| Documents larger than the GPU texture limit | yes (tiled) | CPU fallback; tiling in progress (#49) | partial |
| Documents larger than the GPU texture limit | yes (tiled) | paged GPU residency, composited page cell by page cell (`crates/gpu/src/lib.rs`, #49 closed) | done |
| CPU-only fallback when no GPU | yes, reduced | `cpu` canvas preference; fails to start without an adapter on some Linux systems (#2519, #2412) | partial |
| Choosing the GPU on a multi-GPU machine | Preferences › Performance › Use Graphics Processor | Linux only: Preferences › Performance › Advanced › GPU adapter and `PHOTOCRAFT_GPU_ADAPTER` (#1885); ignored on Windows and macOS | partial |
| Old / integrated GPUs | yes | black line on Intel HD (#2426), OpenCore Macs fail (#1859), Rgba32Float panic (#2020) | partial |
| Old / integrated GPUs | yes | black line on Intel HD (#2426), OpenCore Macs fail (#1859); the Rgba32Float panic is fixed (#2020) | partial |
## Pen tablets
| Feature | Photoshop | macOS | Windows | Linux X11 | Linux Wayland | Web |
|---|---|---|---|---|---|---|
| Pressure | yes | yes (AppKit monitor) | yes (WM_POINTER), jumpy (#2046) | yes (XInput2) | via Xwayland only; GNOME 50 pen doesn't click (#2622), KDE (#2297) | yes |
| Tilt | yes | yes | **no** (WinTab: with orientation axes, opt-in) | yes | no | yes |
| Pressure | yes | yes (AppKit monitor) | yes (WM_POINTER), jumpy (#2046) | yes (XInput2) | via Xwayland only; GNOME 50 pen doesn't click (#2622); KDE fixed in 0.6.0 (#2297, #1070) | yes |
| Tilt | yes | yes | **no** (WinTab: with orientation axes, opt-in) | yes | via Xwayland only (native Wayland: no) | yes |
| Barrel rotation | yes | yes (not applied to tip angle, #1301) | no (WinTab: with a twist-reporting pen and driver, opt-in) | partial | no | yes (twist) |
| Eraser end | yes | yes | yes with Windows Ink, not yet confirmed on hardware (#2285); WinTab: yes (opt-in) | partial | no | partial |
| Eraser end | yes | yes | yes with Windows Ink, not yet confirmed on hardware (#2285); WinTab: yes (opt-in) | partial | partial, via Xwayland only (native Wayland: no) | partial |
| WinTab driver mode | yes | – | yes (opt-in; Windows Ink off) | – | – | – |
| Pressure curve | Windows Ink / driver | global curve in Preferences (#2195) | same | same | same | same |
@@ -50,7 +50,7 @@ rotation; its eraser end comes from the pointer hooks (#2285).
| Feature | Photoshop | PhotoCraft | Status |
|---|---|---|---|
| Colour-managed canvas (document → monitor profile) | yes | yes, folded into the GPU 3D LUT | done |
| Monitor profile detection | per display, live | macOS per display at launch; others sRGB or a chosen .icc | partial |
| Monitor profile detection | per display, live | macOS and Linux X11 (per XRandR output, #2962) per display, following each window's display (#591); Windows and Wayland: sRGB or a chosen .icc | partial |
| HDR / EDR output for 32-bit and HDR images | yes ("Precise Color Management for HDR Display") | no; 8-bit sRGB-encoded canvas texture | missing |
| High-DPI, physical 100% | yes | yes (#1943) | done |
| Multiple monitors: documents in separate OS windows | yes | yes (`extra_windows`) | done |
@@ -75,7 +75,9 @@ rotation; its eraser end comes from the pointer hooks (#2285).
| 2026-11-05 | minor | Optional WinTab driver mode on Windows: pressure and eraser; tilt with orientation axes; rotation with a twist-reporting pen, with Windows Ink off |
| 2026-10-28 | minor | Build GPU compositor pipelines in the background; benchmark baseline pending (#9157) |
| 2026-10-10 | major | First version |
| 2026-10-12 | minor | GPU rows (documents past the texture limit, Rgba32Float panic), Wayland KDE pen and monitor-profile detection refreshed against main |
| 2026-10-17 | minor | GPU filters: Camera Raw's preview, per-pixel stages (#6916 step 1) |
| 2026-10-17 | minor | GPU filters: Camera Raw's preview, Shadows and Highlights (#6916 step 2) |
| 2026-10-17 | minor | GPU filters: Camera Raw's preview, Dehaze, Clarity and Texture (#6916 step 3) |
| 2026-10-19 | minor | Graphics Adapter choice on Linux (#1885) |
| 2026-11-08 | minor | Linux Wayland: tilt and the eraser end work through Xwayland, like pressure; native Wayland still has no pen |
+48 -37
View File
@@ -1,6 +1,6 @@
# Localization parity
> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-11-08 · **Change:** trivial (the catalogs moved to storytold/craft-i18n and are measured with `cargo xtask i18n-report`; Serbian is `sr-latn`; previously minor: Georgian interface catalog; previously minor: Azerbaijani UI catalog merged with current languages; native review pending; Bosnian UI catalog; previously minor: Swedish, Finnish, Danish and Norwegian Bokmål UI catalogs; previously minor: Arabic UI catalog) · **Target:** Adobe Photoshop 2026
> **Last reviewed:** 2026-11-08 · **Last updated:** 2026-11-08 · **Change:** minor (the catalogs moved to storytold/craft-i18n and are measured with `cargo xtask i18n-report`; Serbian is `sr-latn`; coverage re-measured on the merged tree, 2,449 keys; Arabic 92.1%; 35 registered languages; Hindi partial; Georgian, Azerbaijani, Hebrew, Romanian, Tamil, Thai and Urdu measured; previously minor: Swedish, Finnish, Danish and Norwegian Bokmål UI catalogs) · **Target:** Adobe Photoshop 2026
Per-language status of PhotoCraft's UI. How catalogs work and how to add one:
[`localization.md`](localization.md). Language notes: [Korean](localization-ko.md), [Spanish](localization-es.md),
@@ -9,11 +9,11 @@ Per-language status of PhotoCraft's UI. How catalogs work and how to add one:
**How measured.** `cargo xtask i18n-coverage` (now `cargo xtask i18n-report`, `xtask/src/i18n_report.rs`, which reads the craft-i18n catalogs in `CRAFT_I18N_DIR`) defines the key
universe: `tl!("…")` literals and `trn(` plurals in `ui-egui` (tests excluded), menu-catalog
labels and path segments, `menus.rs` UI commands, and engine `CommandSpec` labels and menu paths:
**1,608 English keys** on 2026-10-10. Each catalog (`crates/ui-egui/src/i18n/<code>.tsv`) was
checked against that universe by a source script replicating the xtask (no build). Catalogs hold
more rows than the universe because they also translate dynamic `tl!(expr)` strings (~159 call
**2,449 English keys** on 2026-11-08 after merging main (2,431 earlier that day, 2,428 on 2026-11-07, 2,400 on this branch before that day's merge, 2,389 earlier, 2,369 on main earlier that day, 2,272 on 2026-11-05, 2,199 on 2026-10-31, 2,202 on 2026-10-29, 1,982 on 2026-10-22, 1,918 on 2026-10-21, 1,772 on 2026-10-12, 1,608 on 2026-10-10). Each catalog (`locales/<code>/photocraft.tsv` in craft-i18n)
is checked against that universe by the xtask itself; "rows" are the non-comment, non-blank lines
of the `.tsv`. Catalogs hold more rows than the universe because they also translate dynamic `tl!(expr)` strings (~159 call
sites the tool can't enumerate). **Not covered anywhere:** engine error and status messages and
filter parameter help, which are English in every language; so no language is `full`. The report
filter parameter help, which are English in every language; so no translated language is `full`. The report
also lists, per language, the keys its catalog lacks; those show in English. `cargo xtask ci` prints
it as its last step and never fails on it.
@@ -23,58 +23,59 @@ installed per Creative Cloud install, here `en_US`). It has no Hindi, Arabic, In
Vietnamese UI; Arabic and Hebrew users get English "Middle East" builds with the World-Ready
composer, and its text engine handles RTL, Devanagari and Indic scripts.
**Summary.** 7 of the 12 key languages at 100% of measured keys (status `partial` because of the
engine messages), 2 absent (Hindi, Vietnamese), plus 18 other registered languages. Weighted by
speakers, ~55% ready. Remaining: 80–140 h, plus native-speaker review (recorded only for Italian,
**Summary.** 1 of the 12 key languages at 100% of measured keys (English), 10 at 92.1–93.7%
(Arabic at 92.1%, 194 keys in English; Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese,
German, Korean, Vietnamese at 93.3–93.7%, 155–164 keys each still show in English; status `partial` also
because of the engine messages), Hindi partial (400 of 2,449, 16.3%), plus the other shipped languages below. Weighted by
speakers, ~55% ready. Remaining: 90–143 h, plus native-speaker review (recorded only for Italian,
2026-10-12).
## The twelve key languages
| Language | Code | UI strings (measured keys) | Catalog rows | Dialogs / tooltips / help | Script support | Native review | Status | To `full` |
|---|---|---|---:|---|---|---|---|---:|
| English | `en` | 1,608 / 1,608 (100%) | source | all | Latin | – | full | 0 h |
| Simplified Chinese | `zh-hans` | 1,608 / 1,608 (100%) | 2,366 | dialogs, tooltips yes; engine messages English | CJK fonts (lazy loader), IME preedit/commit, vertical type | no | partial | 8–12 h |
| Spanish | `es` | 1,844 / 1,844 (100%) | 4,010 | as above; complete dynamic UI key set | Latin | no | partial | 6–10 h |
| Hindi | `hi` | partial | 448 | Top menus, toolbox tools, camera raw, dialogs, plurals | Devanagari shaping in the text engine (parley/HarfRust); no Devanagari fallback font (TYPE-218-3) | no | partial | 15–20 h |
| Arabic | `ar` | 2,175 / 2,175 (100%, 2026-10-28) | 3,410 | as above; combined from the community catalogs with one term per concept | Arabic shaping and bidi in the UI (egui 0.37) and the text engine, Arabic fallback font; RTL shell layout but not inside panels (DIST-220-4), paragraph direction buttons but no visual RTL caret (TYPE-218-2 partial) | no | partial | 15–25 h |
| French | `fr` | 1,608 / 1,608 (100%) | 2,766 | as above | Latin | no | partial | 6–10 h |
| Portuguese (Brazil) | `pt-br` | 1,608 / 1,608 (100%) | 2,788 | as above | Latin; every `pt` locale uses it | no | partial | 6–10 h |
| Indonesian | `id` | 1,608 / 1,608 (100%) | 2,764 | as above | Latin | no | partial | 6–10 h |
| Japanese | `ja` | 1,608 / 1,608 (100%) | 3,356 | as above | CJK fonts, IME (Windows IME broken, #590), vertical type (tategaki); installed Japanese fonts missing from the list (#2330) | no | partial | 10–16 h |
| German | `de` | 1,608 / 1,608 (100%) | 2,400 | as above | Latin | no | partial | 6–10 h |
| Korean | `ko` | 1,608 / 1,608 (100%) | 2,936 | as above; terminology from Photoshop's Korean UI ([notes](localization-ko.md)) | Hangul fonts, IME | no | partial | 6–10 h |
| Vietnamese | `vi` | 0 (0%) | – | – | Latin with stacked diacritics (shaping supported) | no | none | 12–18 h |
| English | `en` | 2,449 / 2,449 (100%) | source | all | Latin | – | full | 0 h |
| Simplified Chinese | `zh-hans` | 2,285 / 2,449 (93.3%) | 3,188 | dialogs, tooltips yes; engine messages English | CJK fonts (lazy loader), IME preedit/commit, vertical type | no | partial | 8–12 h |
| Spanish | `es` | 2,293 / 2,449 (93.6%) | 4,430 | as above; complete dynamic UI key set | Latin | no | partial | 6–10 h |
| Hindi | `hi` | 400 / 2,449 (16.3%) | 629 | Top menus, toolbox tools, Camera Raw, dialogs, plurals | Devanagari shaping in the text engine (parley/HarfRust); no Devanagari fallback font (TYPE-218-3) | no | partial | 15–20 h |
| Arabic | `ar` | 2,255 / 2,449 (92.1%) | 3,487 | as above; combined from the community catalogs with one term per concept | Arabic shaping and bidi in the UI (egui 0.37) and the text engine, Arabic fallback font; RTL shell layout but not inside panels (DIST-220-4), paragraph direction buttons but no visual RTL caret (TYPE-218-2 partial) | no | partial | 15–25 h |
| French | `fr` | 2,292 / 2,449 (93.6%) | 4,517 | as above | Latin | no | partial | 6–10 h |
| Portuguese (Brazil) | `pt-br` | 2,294 / 2,449 (93.7%) | 4,411 | as above | Latin; every `pt` locale uses it | no | partial | 6–10 h |
| Indonesian | `id` | 2,288 / 2,449 (93.4%) | 3,524 | as above | Latin | no | partial | 6–10 h |
| Japanese | `ja` | 2,291 / 2,449 (93.5%) | 4,141 | as above | CJK fonts, IME (Windows IME broken, #590), vertical type (tategaki) | no | partial | 10–16 h |
| German | `de` | 2,287 / 2,449 (93.4%) | 3,532 | as above | Latin | no | partial | 6–10 h |
| Korean | `ko` | 2,291 / 2,449 (93.5%) | 4,070 | as above; terminology from Photoshop's Korean UI ([notes](localization-ko.md)) | Hangul fonts, IME | no | partial | 6–10 h |
| Vietnamese | `vi` | 2,291 / 2,449 (93.5%) | 3,960 | as above | Latin with stacked diacritics (shaping supported) | no | partial | 6–10 h |
## Other shipped languages
18 registered languages are outside the twelve-language table. The following nine have
1,608 / 1,608 measured keys, status `partial` for the same reason: Traditional
Chinese `zh-hant` (2,329 rows), Russian `ru` (4,227 keys; also every dynamic label the
other catalogs translate, [notes](localization-ru.md)), Ukrainian `uk` (3,375), Czech `cs` (3,522),
Polish `pl` (3,366), Greek `el` (3,481), Dutch `nl` (3,568), Italian `it` (4,164; also every dynamic label the
other catalogs translate; reviewed by a native speaker, [notes](localization-it.md)). Hungarian
`hu` (4,347 rows) is also registered. Georgian `ka` (4,530 rows; every measured key on 2026-10-31;
Georgian UI fallback font: Noto Sans Georgian, Segoe UI, Sylfaen, SF Georgian, DejaVu Sans; on the web the first served font for `Geor`). Turkish `tr`
(3,731 rows) also covers every measured key. Serbian `sr` (4,022 rows, Latin script, Ekavian, added 2026-10-12) covers every
measured key and the union of the other catalogs' dynamic labels; its one/few/many plurals reuse
the Russian rule. Swedish `sv` (4,552 rows, added 2026-10-28) covers every measured key and the
23 more registered languages (35 with English), measured 2026-11-08, status `partial` for the same reason. Swedish, Finnish, Danish and Norwegian Bokmål miss 178 of the 2,449 measured keys, Bosnian 183, Georgian 176; the other eleven below miss 155–164:
Traditional Chinese `zh-hant` (3,143 rows), Russian `ru` (4,580; also every dynamic label the
other catalogs translate, [notes](localization-ru.md)), Ukrainian `uk` (4,122), Czech `cs` (4,205),
Polish `pl` (4,108), Greek `el` (4,216), Dutch `nl` (4,290), Hungarian `hu` (4,438), Italian `it` (4,580;
also every dynamic label the other catalogs translate; reviewed by a native speaker,
[notes](localization-it.md)), Turkish `tr` (4,294 rows). Georgian `ka` (4,642 rows, 2,273 of 2,449 measured keys; Georgian UI fallback font: Noto Sans Georgian, Segoe UI, Sylfaen, SF Georgian, DejaVu Sans; on the web the first served font for `Geor`; [notes](localization-ka.md)). Serbian `sr` (4,527 rows, Latin script,
Ekavian, added 2026-10-12) covers the union of the other catalogs' dynamic labels; its one/few/many plurals reuse
the Russian rule. Swedish `sv` (4,603 rows, added 2026-10-28) covers the
other catalogs' dynamic labels; combined from the community catalogs in #5985 and #9536 with one
term per concept; the contested terms follow a native speaker's questionnaire answers. Finnish
`fi` (4,552 rows, combined from #5666 and #6961), Danish `da` (4,552 rows, based on #7267 and
completed for the current UI) and Norwegian Bokmål `nb` (4,552 rows, combined from #8072 and #9025;
`fi` (4,603 rows, combined from #5666 and #6961), Danish `da` (4,603 rows, based on #7267 and
completed for the current UI) and Norwegian Bokmål `nb` (4,603 rows, combined from #8072 and #9025;
`no` and `nn` locales resolve to it), all added 2026-10-29, cover the same keys with one term per
concept; none has had a native-speaker review yet. Bosnian `bs` (4,552 rows, Latin script,
Ijekavian, added 2026-10-30) covers the same keys; its one/few/other plurals reuse the Russian
concept; none has had a native-speaker review yet. Bosnian `bs` (4,622 rows, Latin script,
Ijekavian, added 2026-10-30) covers the same dynamic labels; its one/few/other plurals reuse the Russian
rule, and Cyrillic `bs` locales read it too. It is AI-assisted, shares its wording with
storytold/craft-i18n `locales/bs/`, and has not had a native-speaker review yet.
Azerbaijani `az` (Latin script) brings the runtime registry to 29 languages including
English. Its catalog has 4,606 entries, including the initial dynamic-label key union, current OpenType menus and five frame labels
Azerbaijani `az` (Latin script, 2,269 of 2,449 measured keys) brought the runtime registry to 29 languages including
English when it landed; it now has 35. Its catalog has 4,623 entries, including the initial dynamic-label key union, current OpenType menus and five frame labels
and 32 plural messages. It uses one/other integer forms, with singular counted nouns.
Complete menu keys, regional locale matching and English fallback are covered by tests.
Native-speaker review remains pending; validation results and limits are recorded in the
[language notes](localization-az.md). Readiness estimates and G13 remain unchanged.
Hebrew `he`, Romanian `ro` and Urdu `ur` are measured at 2,334 of 2,449 keys (95.3%), Thai `th` at 2,211 (90.3%) and Tamil `ta` at 2,133 (87.1%).
Czech UI follow-up (2026-10-11): status and notice wrappers, hardware labels, brush and
transform accessibility names, rasterization prompts, profile mismatch messages and preset
counts now translate at their render/assignment sites. Navigator's zoom level uses a context
@@ -112,11 +113,21 @@ engine localization or native review is complete.
| 2026-10-12 | minor | Spanish: 1,276 runtime-only labels added (filter and adjustment parameters, Camera Raw, panels, dialogs and status wrappers); generated-label coverage test added |
| 2026-10-12 | minor | Italian native-speaker review: mistranslations (Trap, HDR Toning, Display Text) and phrasing fixed |
| 2026-10-12 | minor | Serbian (`sr`, Latin, Ekavian) catalog: every measured key plus the dynamic labels of the other catalogs |
| 2026-10-12 | minor | Re-measured with `cargo xtask i18n-coverage`: 1,772 keys; Vietnamese catalog shipped (100%, replaces "none"); Simplified Chinese, French, Indonesian and Korean at 1,758 of 1,772; plug-in menu rows stay in Filter › Plug-ins in every language (#2540, #2627) and installed Japanese fonts are listed on Linux (#2330, #2961) |
| 2026-10-13 | minor | Italian: the `Screen` blend mode read *Schermo* (the display) and is now *Scherma*; the Dodge/Burn/Sponge tool names were already Adobe's (*Scherma*, *Brucia*, *Spugna*) and stay. Pinned by a test |
| 2026-10-14 | minor | Re-measured with `cargo xtask i18n-coverage` after merging main: 1,871 keys; Simplified Chinese, French, Indonesian and Korean at 1,857, the other key languages at 100%; catalog rows re-counted; other shipped languages refreshed (Hungarian listed, Polish at 1,904) |
| 2026-10-18 | minor | Russian: 1,229 dynamic labels added (filter and adjustment parameters, Camera Raw, lighting, History/Layers/paths menus, metadata, System Info, status templates, dialogs) with a terminology note ([localization-ru](localization-ru.md)) |
| 2026-10-21 | minor | Re-measured current main: 1,918 keys, 1,904 for French, Indonesian, Korean, Polish and Simplified Chinese; catalog rows recounted |
| 2026-10-22 | minor | Arabic row: paragraph direction has Auto / Left-to-right / Right-to-left buttons in the Paragraph panel and Type options bar (#6793); the visual RTL caret is still missing (TYPE-218-2 partial) |
| 2026-10-22 | minor | Georgian (`ka`) catalog |
| 2026-10-28 | minor | Arabic (`ar`) UI catalog: every measured key, six plural forms; layer names and the title bar no longer reversed on egui 0.37 |
| 2026-10-29 | minor | Swedish (`sv`) UI catalog: every measured key plus the dynamic labels, combined from #5985 and #9536 |
| 2026-10-29 | minor | Finnish (`fi`), Danish (`da`) and Norwegian Bokmål (`nb`) UI catalogs: every measured key plus the dynamic labels, combined from #5666, #6961, #7267, #8072 and #9025 |
| 2026-10-30 | minor | Bosnian (`bs`, Latin, Ijekavian) catalog: the same 4,552 keys as the newest catalogs, `bs-*` locales (Cyrillic included) and one/few/other plurals |
| 2026-11-05 | minor | Re-measured the merged tree with the `xtask/src/i18n_coverage.rs` reporter: 2,272 keys; Arabic at 96.9% (2,202); Bosnian, Swedish, Finnish, Danish and Norwegian Bokmål at 2,216 (Bosnian) and 2,212; Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, German, Korean and Vietnamese at 2,195–2,203 (69–77 keys still in English); Hindi 328; catalog rows recounted |
| 2026-11-07 | minor | Re-measured current main with `cargo xtask i18n-coverage`: 2,369 keys; Arabic 2,241 (94.6%); Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, German, Korean and Vietnamese at 2,264–2,272 (97–105 keys still in English); Hindi 387; Azerbaijani, Hebrew, Romanian, Tamil, Thai and Urdu added to the measurements; catalog rows recounted |
| 2026-11-07 | minor | Re-measured the tree merged with main using `cargo xtask i18n-coverage`: 2,389 keys; Arabic 2,252 (94.3%); Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, German, Korean and Vietnamese at 2,275–2,284 (105–114 keys still in English); Hindi 398; Hebrew, Romanian and Urdu 2,332, Thai 2,209, Tamil 2,131; catalog rows recounted |
| 2026-11-07 | minor | Re-measured after merging current main (Georgian catalog) with `cargo xtask i18n-coverage`: 2,400 keys; Arabic 2,252 (93.8%); Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, German, Korean and Vietnamese at 2,277–2,286 (114–123 keys still in English); Hindi 398; Georgian 2,271; Hebrew, Romanian and Urdu 2,332, Thai 2,209, Tamil 2,131; catalog rows recounted |
| 2026-11-07 | minor | Re-measured the merged tree with `cargo xtask i18n-coverage`: 2,428 keys; Arabic 2,252 (92.8%); Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, German, Korean and Vietnamese at 2,282–2,291 (137–146 keys still in English); Hindi 398; Georgian 2,271; Hebrew, Romanian and Urdu 2,332, Thai 2,209, Tamil 2,131; catalog rows recounted |
| 2026-11-08 | minor | Re-measured the tree merged with main using `cargo xtask i18n-coverage`: 2,431 keys; Arabic 2,252 (92.6%); Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, German, Korean and Vietnamese at 2,282–2,291 (140–149 keys still in English); Hindi 399; Georgian 2,270; Azerbaijani 2,266; Hebrew, Romanian and Urdu 2,331, Thai 2,208, Tamil 2,130; 35 registered languages; catalog rows recounted |
| 2026-11-08 | minor | Re-measured again after merging current main using `cargo xtask i18n-coverage`: 2,449 keys; Arabic 2,255 (92.1%); Simplified Chinese, Spanish, French, Portuguese (Brazil), Indonesian, Japanese, German, Korean and Vietnamese at 2,285–2,294 (155–164 keys still in English); Hindi 400; Georgian 2,273; Azerbaijani 2,269; Hebrew, Romanian and Urdu 2,334, Thai 2,211, Tamil 2,133; catalog rows unchanged |
+3 -1
View File
@@ -6,7 +6,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js
| Area | Done | Partial | Missing | Key numbers |
|---|---:|---:|---:|---|
| [Performance](#performance) | 3 | 22 | 54 | 88 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 50 not run, 4 not measurable yet (baseline 2026-10-05) |
| [Performance](#performance) | 3 | 22 | 56 | 90 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 52 not run, 4 not measurable yet (baseline 2026-10-05) |
| [File compatibility](#file-compatibility) | 11 | 14 | 2 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 190/258, round trip ≥ 258/258 |
| [Tools](#tools) | 36 | 9 | 0 | |
| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 8 of 199 (target 0) |
@@ -110,6 +110,8 @@ Baseline: 2026-10-05, 1 run, commit `f5d2bcb54a`, Apple M4 Pro (48 GB), GPU Appl
| P87 | Toggle a masked adjustment mid-stack in the layered document + refresh | track only | – | – | – | – | – | not run | [#9329](https://github.com/storytold/photocraft/issues/9329) |
| P88 | Bring forward / send backward a small layer in the many-layer document + refresh | track only | – | – | – | – | – | not run | [#9329](https://github.com/storytold/photocraft/issues/9329) |
| P89 | App frame after Paste Into on 24 MP (CPU canvas) | track only | – | – | – | – | – | not run | [#9329](https://github.com/storytold/photocraft/issues/9329) |
| P90 | Free Transform begin, 2 layers on 24 MP (Ctrl+T + first preview frame) | ≤ 300 ms p95 | – | – | – | – | – | not run | [#11103](https://github.com/storytold/photocraft/issues/11103) |
| P91 | Free Transform drag update, 2 layers on 24 MP (scale through new mip levels) | ≤ 16 ms max | – | – | – | – | – | not run | [#11103](https://github.com/storytold/photocraft/issues/11103) |
**Not measurable yet** (the code can't do it yet; no number is recorded):
+46 -42
View File
@@ -12,8 +12,10 @@ Status: **done** (behaves as in Photoshop, with a test), **partial** (exists, di
**missing**. Evidence is a file under `crates/ui-egui/src/` unless another path is given, a
scorecard id, or an issue. Modifier names are macOS first (⌘ ⌥ ⇧); Windows/Linux use Ctrl and Alt.
**Summary (estimated, weights = how often the gesture is used):** ~40% ready. Tools 56/68
present (82%, measured). Free Transform modifiers and Crop are close to Photoshop; the gaps are
**Summary (estimated, weights = how often the gesture is used):** ~40% ready. Tools 68/68
present (100%, measured: the `Tool` enum has 69 variants, the 68 plus a separate Star tool, #11377;
Art History Brush is partial, TOOL-213-20).
Free Transform modifiers and Crop are close to Photoshop; the gaps are
in the long tail of modifiers, in-transform UI, spring-loaded tools, panels and preferences.
Remaining: 60–110 h for transforms and modifiers (gap G5), 60–100 h for tools (G6), 150–250 h
for panels and workspace (G9).
@@ -34,7 +36,7 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme
| Frame | Frame: persistent handles, frame/image/both selection, transforms, fitting, replacement, solid strokes, shape/type conversion and modern shapes ([behavior and limits](frame-tool.md), #8864, 2026-10-23) | Native Photoshop frame metadata and independent Photoshop replay remain open |
| Eyedropper | Eyedropper, Color Sampler, Ruler, Note, Count | |
| Retouch | Remove, Spot Healing, Healing, Patch, Content-Aware Move, Red Eye | |
| Brush | Brush, Pencil, Mixer Brush | |
| Brush | Brush, Pencil, Color Replacement, Mixer Brush | |
| Stamp | Clone Stamp, Pattern Stamp | |
| History | History Brush, Art History Brush (partial: 8 of 10 styles, TOOL-213-20) | |
| Eraser | Eraser, Background Eraser, Magic Eraser | |
@@ -43,7 +45,7 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme
| Pen | Pen, Freeform Pen, Curvature Pen (#1054), Convert Point (#3204; also ⌥ with Pen), Add Anchor Point, Delete Anchor Point (P cycles them; #4144 auto add/delete with the Pen itself) | |
| Type | Horizontal, Vertical, Vertical Type Mask, Horizontal Type Mask | |
| Path selection | Path Selection, Direct Selection | |
| Shapes | Rectangle, Ellipse, Triangle, Polygon, Line, Custom Shape | (Star is a Polygon option in Photoshop) |
| Shapes | Rectangle, Ellipse, Triangle, Polygon, Star (own tool, #11377), Line, Custom Shape | (Star is a Polygon option in Photoshop) |
| View | Hand, Rotate View, Zoom | |
| Toolbar controls | Edit Toolbar, colour chips, Quick Mask, Screen Mode | |
@@ -74,19 +76,19 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme
| Several layers selected: one box frames them all and moves every one (pixels, type, shapes, smart objects, groups), one history step; with a selection each pixel layer's selected pixels move; Transform Again repeats on them | partial | #6501, `transform_tool.rs` (`begin_several`), `transform_several_tests.rs`, engine `edit.transform` `layers` (`transform_multi_tests.rs`); the Background is left out, as Show Transform Controls leaves it; Warp and splits are greyed for several layers; the preview moves their styles past the frame and follows opacity, fill, visibility and style edits made while the box is open (`styles_past_the_frame_move_with_the_box`, `hiding_or_fading_a_moving_layer_shows_in_the_preview_at_once`), but draws the layers stacked between the moving ones under them (the commit keeps every layer's place) |
| Options bar H/V skew fields | done | `transform_tool.rs` (`Parts`, `skew_about_pivot`): W/H, angle and skew read as Photoshop decomposes the box; `skew_fields_lean_the_box_about_the_reference_point` |
| Interpolation in the options bar | partial | Bicubic/Bilinear/Nearest; no Bicubic Smoother/Sharper/Automatic, Preserve Details |
| Commit/cancel buttons in the options bar | missing | #2442 |
| Right-click menu during transform (Scale, Rotate, Skew, Distort, Perspective, Warp, flips, rotates) | missing | TOOL-214-5 |
| Commit/cancel buttons in the options bar | done | `transform_tool.rs` ("Commit transform", "Cancel transform"); #2442 |
| Right-click menu during transform (Scale, Rotate, Skew, Distort, Perspective, Warp, flips, rotates) | done | TOOL-214-5 (`canvas_tool_menu.rs`) |
| Arrow keys nudge the box 1 px, ⇧ 10 px | done | `move_mods.rs` |
| Preview keeps layer order, blend mode and mask | partial | mask yes (BUG-205-2); order/blend not (#2439) |
| Preview keeps layer order, blend mode and mask | partial | mask yes (BUG-205-2); plain Normal layers above keep their place (#2439, #2480), adjustment layers and other blend modes still draw under the box |
| Preview clipped to the canvas, follows edits while open | done | #2201, #2099 |
| Hand (space) mid-transform doesn't interrupt it | partial | #2302 |
| Hand (space) mid-transform doesn't interrupt it | done | `transform_undo_tests.rs::holding_space_still_pans_while_transforming`; the selected Hand no longer steals a resize drag (#2302, #2327) |
| Blend mode / opacity edits while transforming | missing | #1384 |
| Locked layer refused before the drag | missing | fails only at commit (#2585) |
| Locked layer refused before the drag | done | #2585, #2609 |
| Transform a copy (⌥⌘T), step and repeat (⌥⇧⌘T) | done | 2026-10-07 |
| Transform a targeted alpha channel | missing | BUG-207-4 |
| Transform a targeted alpha channel | done | BUG-207-4 (`edit.transform` follows the targeted channel) |
| Smart object perspective (non-affine) | done | FILE-215-6; #579 fixed by #426: Distort / Perspective keep a projective placement, re-rendered from the source, read and written as the PSD `nonAffineTransform` |
| Type-layer transform while editing (⌘ held), no ⌘-corner distort on type | done | `ui-design.md` |
| Puppet Warp mesh follows the outline | missing | block grid (TOOL-214-6) |
| Puppet Warp mesh follows the outline | done | TOOL-214-6 (`algo/puppet.rs` `build_mesh`, #3105) |
## Move tool and nudging
@@ -96,18 +98,18 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme
| Arrow nudge of a selection outline (selection tools) | done | #1502 |
| Arrow nudge of the crop box, X swaps orientation | done | TOOL-214-19 |
| Arrow nudge of path points with Direct Selection | partial | `direct_select.rs` `arrow_keys`: the selected anchors move 1 px, ⇧ 10 px, one History step per press (`direct_select/tests.rs` `arrow_keys_nudge_the_selected_anchors`, #4486); a selected segment is not nudged, which Photoshop's arrow keys also move |
| ⌘-arrow nudges the layer from any tool | missing | #2474 |
| ⌘-arrow nudges the layer from any tool | done | #2474, #2556 |
| ⌥-drag duplicates, ⇧ constrains to 45° | done | `move_mods.rs` |
| Dragging selected pixels shrinks the selection to them (the selection limited to where the layer has pixels, so moving again leaves no edge behind) as the drag starts, also with ⌥; the move box, snapping and Show Transform Controls use the moved pixels' bounds | done | #7538, `canvas.rs` `floating_outline` and `transform_controls_rect`, `snap_ui.rs` `follow_cut`, engine `float_cmds.rs` `CutParts::outline` |
| With several layers selected and a selection, the Move tool moves the layers whole and the selection with them (ants follow the drag; one Move step) | done | #7538, `move_ui.rs` `carries_selection`, engine `layer.translate` `selection` |
| Auto-Select with hover outline, box-select layers, double-click fit | missing | TOOL-214-4 |
| Auto-Select bounding box and snapping follow the picked layer | partial | follow the previous layer (#2666) |
| Auto-Select with hover outline, box-select layers, double-click fit | partial | hover outline and box-select done; double-click fit and drag to a tab open (TOOL-214-4) |
| Auto-Select bounding box and snapping follow the picked layer | done | #2666, #2675 |
| ⌘-drag temporary Move shows the box and snaps | done | #2681, #2684 |
| View › Extras (⌘H) hides the Move tool's transform controls; Show Transform Controls keeps its setting | done | `canvas.rs` `transform_controls_layers`, `hiding_extras_hides_the_move_transform_controls` (#6699) |
| Several layers selected (⇧-click adds, box-select): Show Transform Controls frames them all, with every selected shape's outline, and its handles transform them all | done | `canvas.rs` `transform_controls_layers`, `several_selected_layers_share_one_frame_that_transforms_them_all`; `move_auto_select_tests.rs`; #6501 |
| ⌘-drag temporary Move shows the box and snaps | partial | #2681 |
| ⌘-right-click layer list under the pointer | done | `layer_pick_ui.rs` |
| Double-click type to edit it (caret at the pointer, Type tool) | done | #1132, `type_tool::edit_at` |
| Moving a selection on a mask moves the mask, not the pixels | partial | #2468 |
| Moving a selection on a mask moves the mask, not the pixels | done | #2468, #2486 |
## Selection modifiers
@@ -116,10 +118,10 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme
| ⇧ square/circle, ⌥ from centre, live W × H readout (marquee) | done | `marquee_tests.rs` |
| ⇧ add, ⌥ subtract, ⇧⌥ intersect from modifiers at press | done | tested for the marquee (add, subtract, ⇧⌥ intersect: `marquee_tests.rs`), Lasso (all three: `lasso_ui/tests.rs`) and Polygonal Lasso (`polygon_lasso_tests.rs`) (BUG-208-4) |
| Space repositions the marquee while dragging | done | `hold_keys.rs` |
| Polygonal Lasso ⇧ snaps to 45° | missing | #2352 |
| Polygonal Lasso ⇧ snaps to 45° | done | #2352, #2396 |
| Autoscroll at the window edge while selecting | missing | #2231 |
| Single-pixel rows and columns kept on release | partial | #2391 |
| Esc deselects / ⌘Z undoes the last selection | partial | #2674, #1432 |
| Single-pixel rows and columns kept on release | done | #2391, #2562 |
| Esc deselects / ⌘Z undoes the last selection | partial | Esc deselects when nothing else needs cancelling (#2674, #2765); ⌘Z of a selection step not re-checked (#1432 was closed with a Pen-anchor answer) |
| Select › Modify live preview | missing | #1752 |
| Marching ants as Photoshop draws them: device pixels, every edge equally thick (1 px at 100 %, 2 px up to 200 %), black/white dashes 4× the thickness, slanted dash ends, same look for drag previews and committed selections | done | `ants.rs`, `tests/it/marching_ants_pixels.rs` (#7489) |
@@ -128,7 +130,7 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme
| Behaviour | Status | Evidence |
|---|---|---|
| Click corner, drag smooth, ⌥ breaks a handle, ⌘ direct-selects, ⇧ 45° | done | TOOL-214-10; `vector_ui.rs` (#3751) |
| Handle on the last point, close-drag handle | partial | #1482 |
| Handle on the last point, close-drag handle | done | `vector_ui.rs` (#1601, #3314); the rest of #1482 is a Make Selection dialog for paths |
| Pen Auto Add/Delete: click a segment of the active path, or of the path being drawn, to add, an anchor to delete; ⇧ suspends it | done | #4144, #6140 |
| Curvature Pen edits the active path with no modifier: drag an anchor (the curve reflows), click a segment to add an anchor, double-click smooth ↔ corner; cursor badge + on segments, four arrows on anchors | done: `direct_select.rs` (`curvature_press`, `curvature_hover`), `path.moveAnchors`/`path.convertPoint` with `curvature`, `direct_select_tests.rs` | |
| Path operations in the options bar (combine, subtract, intersect, exclude) | partial: the Pen, Freeform Pen and Curvature Pen have Photoshop's Path Operations menu (New Layer in Shape mode, Combine, Subtract Front Shape, Intersect, Exclude, Merge Shape Components) for the selected shape layer, a targeted vector mask, the selected path or the Work Path (`vector_ui.rs` `path_operations_menu`, `pen_path_ops_tests.rs`, `path.mergeShapeComponents`). Path Selection has it too and selects components (click, ⇧-click, drag moves the selected ones); with components selected the menu, `+` (Combine) and `-` (Subtract Front Shape) change their operation (`path.setOperation`, `path_components.rs`, `path_components_tests.rs`); the first component always combines and keeps its operation, the Pen tools' menu and keys set only the next path's, and dragging every component of a live rectangle or ellipse keeps it live. A Pen draft the document refuses (a locked layer) stays the draft on ↩ and becomes the Work Path on Esc or a tool switch. The Shape tools don't have the menu yet, and Intersect and Exclude have no key | `layer.combineShapes.*`; #1397 |
@@ -139,8 +141,8 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme
| Shape Fill/Stroke popover: No Color / Solid Color / Gradient / Pattern, Color Picker button, Recently Used Colors, swatch folders | partial: types, Color Picker (full dialog with hex, eyedropper and live preview), Recently Used Colors and swatch folders as Photoshop; Gradient opens the gradient tab; Pattern is off (shapes don't render pattern paint), no gear menu or resize grip (`tools/paint_picker.rs`, `tools/vector_ui/paint_tests.rs`, 2026-10-27) | [`shape-strokes.md`](shape-strokes.md) |
| Colour swatches in dialogs and panels open the Color Picker dialog | done: Photo Filter, Black & White tint, Gradient Map stop, Content-Aware Fill overlay, Filter Gallery glow and the Save for Web colour table; the swatch previews the picker's colour while it is open, Cancel restores the exact colour, OK is one history step (`widgets/color_button_tests.rs`, `adjust_editors/ui_tests.rs`, 2026-10-30) | |
| Shape options-bar Fill/Stroke hex input | done | #6176; typed in the Color Picker the popover opens (`color_picker_ui.rs`), `tools/vector_ui/paint_tests.rs`: typed and pasted hex, partial/invalid input, alpha retention, next-shape defaults and selected-shape Undo |
| Rotated shape selection hints correct | partial | #2512 |
| Curved shape bounds exact | partial | one pixel too wide (#2537) |
| Rotated shape selection hints correct | done | #2512, #2732 |
| Curved shape bounds exact | done | #2537, #2641 |
## Crop
@@ -172,11 +174,11 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme
| ⇧-drag a guide out of a ruler, or move one already placed: it lands on the nearest ruler tick, in a pixel ruler on whole pixels at least | done | `rulers.rs` `snap_to_tick`, `snap_tick`, `GuideDrag::follow_pointer` (#3770) |
| A dragged guide shows its position beside the pointer (X for vertical, Y for horizontal, in the ruler unit) | done | `rulers.rs` `guide_drag_readout` (#7680) |
| ⌥ while dragging a guide (out of a ruler, or with the Move tool) turns it; a guide dropped on either ruler is deleted | done | `rulers.rs` `GuideDrag::track`, `view.moveGuide` `toOrientation` (#5034) |
| Status bar follows the ruler unit | partial | #2602 |
| Ruler corner and gaps drawn as Photoshop | partial | #2600, #2601, #2551 |
| Guides stored as f64 | missing | `Vec<f32>` (UI-217-20) |
| Status bar follows the ruler unit | done | #2602, #2618 |
| Ruler corner and gaps drawn as Photoshop | partial | corner overlap fixed (#2600, #2617); the gap above the top ruler is open (#2551; #2601 closed as its duplicate) |
| Guides stored as f64 | done | `Vec<f64>`, kept through .pcraft and PSD (UI-217-20) |
| Geometry precision | partial | `geom::Point` f64, paths f64; paint internals mostly f32 |
| Numeric fields: arithmetic, scrubby labels | partial | units in expressions and double-click reset missing (UI-217-13) |
| Numeric fields: arithmetic, scrubby labels | done | arithmetic with units, scrubby labels, double-click reset (UI-217-13, #3099) |
| Wheel steps a value field, ⇧ ×10: clicked into, wherever the pointer is; not clicked, a gesture that starts over it | partial | `field_wheel.rs` (#5473, #4061). Photoshop: a field takes the wheel once clicked into (shortcut guides, user reports); whether the pointer must stay over it is unconfirmed. Stepping on hover alone is Photopea's, kept deliberately |
| Font-name field: click selects the full name; typing searches in place | done | `type_tool.rs` `family_picker_in`, `type_font_picker_tests.rs` (#9338): one editable name above the list; unmatched queries show a compact message; Enter or a row applies to the selected characters even when the family matches their representative; both controls show the selected span and leave mixed families blank; caret font choices affect subsequent typing; Ctrl/Cmd+Enter accepts a valid pending font query and commits from a focused field; Escape/outside click discards pending text; existing navigation and previews retained |
| Type options bar: drag the "T" icon to change the font size | done | `type_tool.rs` `options_bar`: the icon scrubs the size field like the Character panel's icons (Shift x10, Alt fine), at layer or selection scope, one history step per drag, within 1–1296 pt (#6437) |
@@ -192,14 +194,14 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme
| Scrubby zoom | done | `zoom_tool.rs` |
| Flick panning | done | `flick_pan.rs` (Preferences › Tools › Enable Flick Panning) |
| Animated zoom | done | `canvas.rs`, `zoom_tool.rs`, `zoom_hold.rs`; discrete Zoom clicks and View zoom controls ease over 220 ms with anchored transitions and immediate direct navigation (#566); holding a Zoom press still past 0.3 s zooms continuously about the press point (2 doublings a second, ⌥ out) until release (#6210); General › Animated Zoom (default on) controls both behaviors; off snaps discrete zoom immediately, including when disabled mid-transition |
| Double-click Zoom tool = 100%, double-click Hand = fit | partial | Zoom missing (#2508) |
| Double-click Zoom tool = 100%, double-click Hand = fit | done | #2508, #2527; `panels.rs::double_clicking_the_hand_tool_fits_on_screen` |
| ⌥-wheel zoom around the pointer | partial | ×1.1 per notch, measured on Photoshop (#1718; `wheel_nav.rs`, `input_tests.rs`); #217 asked for ~5 % steps (UI-217-18). Ctrl + Alt + wheel is accepted as the same gesture on Windows and Linux (2026-10-31, #10488): winit reports a held Ctrl as both ctrl and command, so `wheel_nav::alt_gesture` forgives `command` only together with `ctrl` and without `mac_cmd`; macOS ⌘ + ⌥ and ⌘ + ⌃ + ⌥ stay out of the gesture and keeps whatever scroll egui 0.37 gives it — with Alt held both scroll patterns match, so its delta is not folded sideways — and Ctrl + Alt + ⇧ + wheel is deliberately left as it was before #10488 (a plain vertical scroll with General › Zoom with Scroll Wheel off, nothing with it on; checked on origin/main and pinned in all four Zoom with Scroll Wheel / Animated Zoom combinations by tests in `wheel_nav/tests.rs`). Which Photoshop gesture that combination should map to is open on #10488 (the issue names only Ctrl + Alt, and nothing here has measured the combination), so no behaviour is claimed. AltGr does not arrive as Ctrl + Alt: winit's Windows `get_agnostic_mods` drops ctrl and alt from the modifier state while AltGr is down on a layout that has one, and X11/Wayland deliver it as ISO_Level3_Shift. It is not excluded from the Alt gesture, though: egui-winit also emits a `Key::AltRight` event for the physical key and `wheel_events` turns that into `alt`, so AltGr + wheel can zoom like ⌥ (not verified on a physical AltGr keyboard; same AltGr situation as in the Brush size/hardness keys row, Keyboard shortcuts) |
| Wheel, smooth scrolling and pinch as in Photoshop | partial | #2485, #2463, #1989; #10488 (Ctrl + Alt + wheel) |
| Trackpad rotate drives Rotate View | done | `rotate_view.rs:136` |
| Zoom levels to 3200% and beyond | partial | #1813 |
| Physical 100% at any display scale | done | #1943 |
| Filter dialogs with a preview window (Smart Sharpen, Unsharp Mask, Reduce Noise…): over the image the pointer is a small square, and a press there centres the dialog's preview on that point (clamped to the image), whatever the tool, while dragging on afterwards leaves it; a click or drag the locator starts never reaches the tool or the history, while a tool drag (a Brush stroke, a Crop frame) begun before the dialog opened still ends along its own path | done | `dialogs/filter_preview_ui.rs` `center_at`, `filter_preview_locator_tests.rs` (#9648); `ui.pointer` does the same |
| ⌃Tab / ⌃⇧Tab switch document tabs | missing | #2340 |
| ⌃Tab / ⌃⇧Tab switch document tabs | done | #2340, #2353 |
## Selected colour channels
@@ -241,8 +243,8 @@ Paragraph; the rest open as in-app floating windows.
|---|---|---|
| Character and Paragraph controls without a type target | done | #5556; persistent Type tool defaults feed new point, box and mask text; existing text still edits in its selected scope (`type_tool.rs`, `type_tool_tests.rs`) |
| Panel groups float and tear off into OS windows | missing | UI-217-5, #1828, #1213 |
| Drag panels to reorder and regroup | partial | #2272, #2305 |
| Docked resize pushes the neighbour | partial | #2573 |
| Drag panels to reorder and regroup | partial | dock tabs reorder within their group (#2272, #2774); regrouping open (#2305) |
| Docked resize pushes the neighbour | done | #2573, #2624 |
| Color panel modes from its panel menu (Hue Cube, Brightness Cube, Color Wheel, Grayscale/RGB/HSB/CMYK/Lab/Web Color sliders), colour ramp (RGB/CMYK Spectrum, Grayscale Ramp, Current Colors, Make Ramp Web Safe; Shift-click cycles, Alt-click picks the other colour), Copy Color as HTML / Hex Code; the out-of-gamut ⚠ with the nearest printable colour under the chips (sliders always; the cubes when the field is at least 53 pt tall); the same in every theme | done | `color_panel_ui.rs`, `color_panel_tests.rs`; UI-217-17, #2569, #6000, #8672 |
| A colour picked in the Color or Swatches panel or the Color Picker recolours the selection: selected characters while editing; every selected type layer with a Type tool; every selected shape's fill with a shape, Pen or path selection tool; only the foreground with other tools, the Move tool too; a swatch click recolours the selected type layers and shape fills whatever the tool (#9238); one history step (a Color panel drag too) | done: `apply_color.rs`, `apply_color_tests.rs` | |
| A Color Picker opened for another dialog's colour (Edit › Fill's Color…, Edit › Stroke, a filter's or adjustment's colour, Replace Color's Result, New Document, New Guide and guide layout colours, channel and spot colours, Preferences) or for the Crop shield's custom colour shows the colour under the cursor there before OK, as in Photoshop, so the dialog's swatch and its own preview follow it; Cancel puts back exactly what was there, OK keeps it without a history step of its own (the dialog's OK makes the one step), and the dialog's ⌘Z history records only the picker's OK (#9886) | partial | `dialogs/color_picker_ui/live_preview.rs`, `dialogs/color_picker_ui/live_preview/tests.rs`; differs: the pickers whose OK runs a command without a preview of its own (text colour and gradient stops, open in #9757; gradient preset stops, artboard background, count group colour) and the pasteboard's custom colour show the colour only after OK |
@@ -255,10 +257,10 @@ Paragraph; the rest open as in-app floating windows.
| Every preference takes effect | partial | 8 of 199 do nothing (scorecard, 2026-11-08); Column Size drives Image Size and Canvas Size's Columns width unit (#6214) |
| UI scale presets | done | UI-217-9; 75–125% in 5% steps (#2492, #3222) |
| History snapshots: camera button, New Snapshot dialog (⌥-click: Name, From), the first snapshot (the document as opened), snapshot rows (click returns and selects, rename, delete; the trash deletes the selected snapshot, and a snapshot or state dragged onto it, #5324), `history.*Snapshot` commands; History Options' snapshot options (Automatically Create First Snapshot, New Snapshot When Saving, Show New Snapshot Dialog by Default) | partial | `history_cmds.rs`, `history_options_cmds.rs`, `snapshot_rows` in `panels.rs`, `snapshot_dialog.rs`; History Brush sources to come (#2966) |
| Themes: Photoshop's four greys | partial | five themes; #2661 |
| Themes: Photoshop's four greys | done | `theme.rs` `Pro`, `ProMedium`, `ProLightGray`, `ProLight` (#2661, #2892) |
| Painting tools' options bar: Opacity right after Mode in every theme (Brush, Pencil, Eraser, Clone Stamp); the non-Pro themes keep Hardness beside Size | done | #9784, `tool_options_theme_tests.rs::every_theme_puts_opacity_right_after_mode` |
| Document tabs: overflow, context menu, reorder | done | UI-217-6; middle-click close #2570 |
| Layers panel: wheel steps blend modes, drop on New/Trash | partial | UI-217-14 |
| Layers panel: wheel steps blend modes, drop on New/Trash | done | UI-217-14 |
| Layers panel New Group button: click with 2+ layers selected groups them (CC 2014+), ⇧-click groups, one layer gives an empty group, ⌥-click opens the New Group dialog, ⌘-click adds the group below the active layer | done | #2561, `new_group_button_tests.rs` |
| New Group dialog (Name, Color, Mode, Opacity) for Layer › New › Group… / Group from Layers…, the Layers panel menu and the row menu; ⌘G stays immediate | done | `dialogs/new_group_ui.rs`, `dialogs/new_group_ui/tests.rs` |
| Groups made from layers (⌘G, New Group button, Group from Layers) start collapsed; selecting a layer inside opens the group | done | `group_options.rs` tests, `new_group_button_tests.rs` |
@@ -302,7 +304,6 @@ Paragraph; the rest open as in-app floating windows.
| 2026-10-24 | minor | Path Selection selects path components and has the Path Operations menu; the menu and `+` / `-` change the selected components' operation (`path.setOperation`); the Pen carries on an open shape layer or vector mask path from its endpoint (#1397 feedback); row stays partial until the Shape tools have the menu; no percentage changed |
| 2026-10-25 | minor | Every preference takes effect: 12 of 178 do nothing, the scorecard's count (it still said 46 of 149) |
| 2026-10-25 | minor | Art History Brush is in the History group of the Y flyout (partial, TOOL-213-20, #1610) |
| 2026-10-24 | minor | Stale rows corrected against main: the tool flyout row is done for press-and-hold or click-drag (#2324, #2301); Direct Selection arrow nudge of selected anchors is partial (#4486; a selected segment is not nudged); Smart Guides distances with ⌘ held are partial (#4946); no percentage changed |
| 2026-10-24 | minor | Hue/Saturation: dragging between a colour range's handles moves them as Photoshop 2025 does: the fully-on span moves all four, each fade its own two (#9252). Scores unchanged. |
| 2026-10-24 | minor | Color panel: Hue Cube and Brightness Cube show Photoshop's out-of-gamut ⚠ and the nearest printable colour under the chips when the field is at least 53 pt tall, as the slider modes did; a click takes it (#8672). No percentage changed |
| 2026-10-24 | minor | Swatches: a click recolours the selected type layers and shape fills whatever the tool, as Photoshop 2025 does (measured with the Move and Brush tools); the Color panel still recolours them only with a Type, shape or Pen tool (#9238). Scores unchanged. |
@@ -337,18 +338,15 @@ Paragraph; the rest open as in-app floating windows.
| 2026-10-11 | minor | Flick panning done: releasing a moving Hand drag (tool, Space or middle button) glides and decays, gated by Enable Flick Panning |
| 2026-10-11 | minor | History snapshots: the camera button takes one, snapshot rows return to it as a new state, rename and delete it (#2966) |
| 2026-10-11 | minor | Animated zoom done: 220 ms transitions per view for discrete Zoom clicks and View controls; GPU composites are reused, coordinates follow the displayed camera, and direct navigation interrupts immediately |
| 2026-10-14 | minor | History: a clicked snapshot stays selected and the trash deletes it; snapshot and state rows dragged onto the trash are deleted (#5324) |
| 2026-10-11 | minor | ⇧-drag a guide out of a ruler lands on the nearest ruler tick (#3770) |
| 2026-10-11 | minor | Layer and selection keys from Photoshop's shortcut set: ⌘, toggles, ⌘\, /, ⌘⌥2, ⌘⌥⌫, Tab rename-next, ⌥-click thumbnail to fit |
| 2026-10-11 | minor | Tool keys from Photoshop's shortcut set: ← / → rotate the brush tip, ⇧-click for new type, Space+F canvas colour |
| 2026-10-12 | minor | General › Animated Zoom is visible and gates every discrete zoom transition; disabling it snaps all views to their target on the next frame |
| 2026-10-11 | minor | Spring-loaded tool letters done (#2672): holding any tool letter (Z included) past 300 ms, or using the canvas while it is down, makes the tool temporary until release |
| 2026-10-11 | minor | Type formatting keys done: ⇧⌘K, U, B, I and /, ⌥↑/↓, ⇧⌥↑/↓, ⌥←/→ over a selection and ⌥⇧⌘H format the selected type while editing, and no longer reach Color Settings, Desaturate, Auto Color or Inverse |
| 2026-10-11 | minor | Selection modifiers at press: evidence now names the marquee, Lasso and Polygonal Lasso tests (still partial: no marquee ⇧⌥ intersect test). ⌥-wheel zoom: missing → partial (works at ×1.1 a notch; #217 asked for ~5 %) |
| 2026-10-21 | minor | Selection modifiers at press: partial → done; the marquee ⇧⌥ intersect test (`marquee_tests.rs` `shift_alt_before_the_drag_intersects_the_selection`) closed the gap the 2026-10-11 row names (BUG-208-4) |
| 2026-10-11 | minor | Pen ⇧ 45° done: ⇧-click puts the next anchor on the nearest 45° ray, ⇧-drag turns its handles in 45° steps (TOOL-214-10 done, #3751) |
| 2026-10-12 | minor | General › Animated Zoom is visible and gates every discrete zoom transition; disabling it snaps all views to their target on the next frame |
| 2026-10-12 | minor | Pen Auto Add/Delete on the active path, with its options-bar checkbox, hover feedback and + / − cursor badge (#4144) |
| 2026-10-15 | minor | Animated zoom partial: with Animated Zoom on, holding the Zoom tool's button zooms continuously about the press point, ⌥ out (#6210) |
| 2026-10-15 | minor | Pen Auto Add/Delete works on the path being drawn: a click on its segment adds an anchor, on a middle anchor deletes it, and drawing carries on (#6140) |
| 2026-10-12 | minor | Toolbar tool shortcuts can be reassigned, removed and reset in Keyboard Shortcuts (#4086); capture, restart, group cycling, conflict and text-focus regressions |
| 2026-10-12 | minor | Smart filter rows can be selected, and dragged (⌥: copied) onto another smart object or onto Delete (#4271) |
| 2026-10-12 | minor | Free Transform options bar: H and V skew fields; a sheared box reads as skew instead of a taller H |
@@ -356,22 +354,26 @@ Paragraph; the rest open as in-app floating windows.
| 2026-10-12 | minor | Crop tool Fill › Content-Aware Fill done (#3823); Delete Cropped Pixels off split into its own row, still partial |
| 2026-10-12 | minor | Layers panel: Clip Thumbnails to Layer Bounds frames each layer's pixels instead of the canvas (#4281) |
| 2026-10-12 | minor | Guides: ⌥-click turns a guide through the click; double-click opens Preferences › Guides, Grid & Slices |
| 2026-10-12 | minor | Rows refreshed against main (scorecard ids and merged PRs cited per row): transform commit/cancel, right-click menu, locked layer, alpha channel and Puppet Warp; Move, selection, Pen, Crop preset, ruler, numeric-field, navigation, dock and theme rows; the last-used tool per group |
| 2026-10-13 | minor | Smart filter rows can be dragged up or down their stack to reorder the filters |
| 2026-10-12 | minor | History snapshots: the New Snapshot dialog (⌥-click the camera), and the first snapshot of the document as opened as the panel's top row (#2966) |
| 2026-10-13 | minor | On-canvas corner radius widgets on live rectangles (TOOL-214-12) |
| 2026-10-13 | minor | Curvature Pen edits the active path: drag anchors, click a segment to add, double-click smooth/corner, cursor badges |
| 2026-10-11 | minor | Pen ⇧ 45° done: ⇧-click puts the next anchor on the nearest 45° ray, ⇧-drag turns its handles in 45° steps (TOOL-214-10 done, #3751) |
| 2026-10-14 | minor | Last selected tool restored across launches; temporary overrides excluded, explicit Eraser choices retained, and final selection flushed on normal exit |
| 2026-10-13 | minor | Free Transform with a selection: the box is the selection's rectangle, and the marching ants follow it while it is transformed (#5297) |
| 2026-10-14 | minor | History: a clicked snapshot stays selected and the trash deletes it; snapshot and state rows dragged onto the trash are deleted (#5324) |
| 2026-10-14 | minor | Last selected tool restored across launches; temporary overrides excluded, explicit Eraser choices retained, and final selection flushed on normal exit |
| 2026-10-14 | minor | Move › Show Transform Controls frames every selected layer and outlines the selected shapes |
| 2026-10-14 | minor | Rounded corners on live triangles, polygons and stars: Properties field and on-canvas widgets (TOOL-214-12) |
| 2026-10-15 | minor | Animated zoom partial: with Animated Zoom on, holding the Zoom tool's button zooms continuously about the press point, ⌥ out (#6210) |
| 2026-10-15 | minor | Pen Auto Add/Delete works on the path being drawn: a click on its segment adds an anchor, on a middle anchor deletes it, and drawing carries on (#6140) |
| 2026-10-15 | minor | ⌫/Delete with a smart filter row selected removes that filter (the Smart Filters row: all of them), as the Delete button does, instead of the smart object (#4751) |
| 2026-10-21 | minor | Crop rows corrected against the code and the scorecard: saved custom crop presets (TOOL-214-9, #2723) and Delete Cropped Pixels off are done (#6562); no percentage changed |
| 2026-10-20 | minor | Free Transform of an artboard child omits ancestor paper from the covering and isolated composites while retaining board clipping. The base canvas and whole-artboard backgrounds are preserved; synthetic regressions in `transform_tool.rs`. No parity percentage changed. |
| 2026-10-24 | minor | Layers panel filter row: Artboard lists only the artboards that hold the selected layers, and the unfiltered tree when nothing is selected or a selected layer is in no artboard; drivable by `ui.set {layerFilter: {by: "artboard"}}`; no percentage changed |
| 2026-10-18 | minor | Move tool: dragging selected pixels shrinks the marching ants to the moved pixels as the drag starts, and the dropped selection is theirs, as in Photoshop (#7538) |
| 2026-10-18 | minor | Marching ants drawn in device pixels like Photoshop's: equally thick on every edge at 125 %/150 % display scale, thicker on HiDPI, slanted dash ends (#7489) |
| 2026-10-21 | minor | Selection modifiers at press: partial → done; the marquee ⇧⌥ intersect test (`marquee_tests.rs` `shift_alt_before_the_drag_intersects_the_selection`) closed the gap the 2026-10-11 row names (BUG-208-4) |
| 2026-10-16 | minor | View › Extras (⌘H) hides the Move tool's transform controls and their handles stop responding; ⌘H again restores them, and Show Transform Controls keeps its setting (#6699) |
| 2026-10-15 | minor | ⌫/Delete with a smart filter row selected removes that filter (the Smart Filters row: all of them), as the Delete button does, instead of the smart object (#4751) |
| 2026-10-14 | minor | Rounded corners on live triangles, polygons and stars: Properties field and on-canvas widgets (TOOL-214-12) |
| 2026-10-14 | minor | A colour picked in the Color or Swatches panel or the Color Picker recolours the selected type layers (Type tool) or shape fills (shape, Pen and path selection tools) |
| 2026-10-15 | minor | Color panel: Photoshop's panel-menu modes, colour ramp and copy commands; the theme no longer picks the panel's layout (UI-217-17 done, #2569, #6000) |
| 2026-10-24 | minor | Layers panel filter row: Smart Object lists linked, missing or embedded smart objects, drivable by `ui.set {layerFilter: {by: "smartObject", smart}}`; no percentage changed |
@@ -386,6 +388,8 @@ Paragraph; the rest open as in-app floating windows.
| 2026-11-03 | minor | Tools › Overscroll off centres an image smaller than the window on that axis, so zooming out around the pointer keeps it in the middle instead of where the zoom left it (#10488, #4799); this overrides #1718's Photoshop 25.4 measurement on the strength of two Photoshop users' reports, and Overscroll on keeps the free view; no percentage changed |
| 2026-11-04 | minor | Each toolbar slot and tool key keeps its last tool across launches (`Preferences.groupTools`, #3569); the group row, stale since #2625, is done; no percentage changed |
| 2026-10-31 | minor | Ctrl + Alt + wheel over the canvas zooms like ⌥ + wheel (#10488): ×1.1 a notch around the pointer with Animated Zoom off, eased with it on, and it follows the ⌥ swap when General › Zoom with Scroll Wheel is on. Windows and Linux report a held Ctrl as ctrl AND command (`wheel_nav::alt_gesture`), macOS ⌘ + ⌥ is left alone, plain ⌘/Ctrl + wheel still scrolls sideways; the combination was a dead gesture, so nothing existing was replaced. The centred-zoom half of the report is still open: `canvas.rs:1737` re-clamps the view centre each frame only when Tools › Overscroll is off (it is on by default), so the drift the reporter saw is more likely the deliberate nearest-image-point anchor (`view_xform.rs:239`, #3720) or Zoom Clicked Point to Center, which needs its own repro; no percentage changed |
| 2026-11-08 | minor | Tool inventory: Color Replacement listed in the Brush group, Star (#11377) in Shapes; the `Tool` enum count is now 69; tools present 56/68 → 68/68 (Star counted separately) |
| 2026-11-04 | minor | Unsaved-changes prompt on macOS: ⌘D presses Don't Save, as in Photoshop (#11282); no percentage changed |
| 2026-11-11 | minor | Space's Hand view menu (#11271, after #11292): a plain Esc under it closes only the menu and a plain Enter does nothing, so neither reaches a pending crop (in Photoshop, Esc with a context menu open only closes the menu); outside the image Space's Hand opens the pasteboard menu over the selected tool, which stays open after Space is released; no percentage changed |
+28
View File
@@ -882,3 +882,31 @@ issue = 9329
bench = "perf_scenarios"
row = "app frame after Paste Into on 24 MP (CPU canvas)"
enforce = false # new; no baseline yet
# ---- #11103: Free Transform drag stalls -------------------------------------------------------
[[bench]]
name = "free_transform_bench"
package = "photocraft-ui-egui"
args = ["--reps", "9"]
quick_args = ["--size", "1200x800", "--reps", "3", "--steps", "20"]
note = "two selected layers on 24 MP: Ctrl+T + first preview frame, and drag updates (pointer move + preview frame) scaling through new mip levels or moving; CPU side, no GPU upload/present"
[[scenario]]
id = "P90"
title = "Free Transform begin, 2 layers on 24 MP (Ctrl+T + first preview frame)"
issue = 11103
bench = "free_transform_bench"
row = "Free Transform begin, 2 layers on 24 MP: Ctrl+T + first frame"
budget_ms = 300
enforce = true # #11103: 166 ms p50, 173 ms max (2026-11-11); a regression guard until the press frame is reworked
[[scenario]]
id = "P91"
title = "Free Transform drag update, 2 layers on 24 MP (scale through new mip levels)"
issue = 11103
bench = "free_transform_bench"
row = "Free Transform drag update, 2 layers on 24 MP: scale through mip levels"
metric = "max"
budget_ms = 16
enforce = true # #11103: max 43.2 ms before (a mip level built in the frame), 0.09 ms after (2026-11-11)