mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge pull request #11825 from kirubhakaran12/fix/11786-wand-tolerance-integer
Round the Magic Wand's Tolerance field to whole numbers (#11786)
This commit is contained in:
7 files changed
+256
-7
No files matched your search
@@ -352,3 +352,6 @@ sync_github_name = true
|
||||
|
||||
[people.slafebre]
|
||||
real_name = "Sven Lafebre"
|
||||
|
||||
[people.kirubhakaran12]
|
||||
sync_github_name = true
|
||||
@@ -1064,6 +1064,8 @@ mod export_quality_tests;
|
||||
mod options_hit_area_tests;
|
||||
#[cfg(test)]
|
||||
mod select_and_mask_button_tests;
|
||||
#[cfg(test)]
|
||||
mod wand_tolerance_field_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod saved_path_edit_tests;
|
||||
|
||||
@@ -508,7 +508,9 @@ fn selection_specific_options(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool:
|
||||
selection_mode_buttons(&mut app.ui.selection_mode, ui);
|
||||
widgets::vline(ui, 22.0);
|
||||
opt_label(ui, tl!("Tolerance"));
|
||||
widgets::value_field(ui, &mut app.ui.tool_options.tolerance, 0.0..=255.0, "", 58.0);
|
||||
// The wand reads a whole-number tolerance (#11786): the field rounds a typed decimal
|
||||
// and never keeps a fraction, so it shows the number the wand uses.
|
||||
widgets::value_field_int(ui, &mut app.ui.tool_options.tolerance, 0.0..=255.0, "", 58.0);
|
||||
widgets::checkbox(ui, &mut app.ui.tool_options.anti_alias, tl!("Anti-alias"));
|
||||
widgets::checkbox(ui, &mut app.ui.tool_options.contiguous, tl!("Contiguous"));
|
||||
widgets::checkbox(ui, &mut app.ui.tool_options.sample_all.magic_wand, tl!("Sample All Layers"));
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
//! #11786: the Magic Wand's Tolerance is a whole number 0–255, and the wand floors what it is
|
||||
//! given (`wand_region`: `(tolerance + 1e-3).floor()`). A field that keeps a fraction therefore
|
||||
//! shows a number the tool does not use, and a decimal typed with the decimal comma (the UI
|
||||
//! language's separator) is rejected outright. Typing `12.5` or `12,5` must leave 13 behind, so the
|
||||
//! field and the wand agree; 300 and -5 clamp, as today.
|
||||
|
||||
use egui::accesskit::Role;
|
||||
use egui::{PointerButton, Pos2, vec2};
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::{NodeT, Queryable};
|
||||
use photocraft_color::{ColorMode, SampleType};
|
||||
use photocraft_doc::{Document, Layer, LayerContent};
|
||||
use photocraft_geom::{Rect, Size};
|
||||
use photocraft_raster::Surface;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::PhotocraftApp;
|
||||
use crate::state::Tool;
|
||||
|
||||
/// The Magic Wand's options bar, with a document open, after a few settled frames.
|
||||
fn wand_bar() -> Harness<'static, PhotocraftApp> {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({"width": 64, "height": 64})).unwrap();
|
||||
app.sync_views();
|
||||
app.ui.tool = Tool::MagicWand;
|
||||
let mut h = Harness::builder().with_size(vec2(1000.0, 60.0)).build_ui_state(
|
||||
|ui, app: &mut PhotocraftApp| {
|
||||
if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {
|
||||
return;
|
||||
}
|
||||
crate::panels::options_bar(app, ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);
|
||||
h.run_steps(4);
|
||||
h
|
||||
}
|
||||
|
||||
/// The number the Tolerance field shows, as a person reads it off the screen.
|
||||
fn shown_tolerance(h: &Harness<'_, PhotocraftApp>) -> f32 {
|
||||
let node = h.get_by_role(Role::SpinButton);
|
||||
node.accesskit_node().value().unwrap_or_default().parse().unwrap_or(f32::NAN)
|
||||
}
|
||||
|
||||
/// Types `text` over the field's number and presses Enter, as a person would, and returns the
|
||||
/// option the edit left behind.
|
||||
fn type_tolerance(h: &mut Harness<'_, PhotocraftApp>, text: &str) -> f32 {
|
||||
h.get_by_role(Role::SpinButton).click();
|
||||
h.run();
|
||||
h.event(egui::Event::Text(text.into()));
|
||||
h.run_steps(2);
|
||||
h.key_press(egui::Key::Enter);
|
||||
h.run_steps(2);
|
||||
h.state().ui.tool_options.tolerance
|
||||
}
|
||||
|
||||
/// A typed decimal rounds to the nearest whole number, whichever separator it was typed with: the
|
||||
/// wand's option is never a fraction for it to floor differently from what the field shows.
|
||||
#[test]
|
||||
fn typed_decimals_round_to_the_nearest_whole_number() {
|
||||
for (text, want) in [("12.5", 13.0), ("12,5", 13.0), ("12.4", 12.0), ("12.6", 13.0)] {
|
||||
let mut h = wand_bar();
|
||||
assert_eq!(type_tolerance(&mut h, text), want, "typing {text}");
|
||||
assert_eq!(shown_tolerance(&h), want, "the field shows the number it kept ({text})");
|
||||
}
|
||||
}
|
||||
|
||||
/// Each operand of a typed expression is its own number: `1.5+2.5` adds up to 4, while a number
|
||||
/// with two separators (`1,5,2`) is not one and leaves the option as it was.
|
||||
#[test]
|
||||
fn typed_expressions_take_decimal_operands() {
|
||||
let mut h = wand_bar();
|
||||
assert_eq!(type_tolerance(&mut h, "1.5+2.5"), 4.0, "typing 1.5+2.5");
|
||||
let mut h = wand_bar();
|
||||
let before = h.state().ui.tool_options.tolerance;
|
||||
assert_eq!(type_tolerance(&mut h, "1,5,2"), before, "typing 1,5,2");
|
||||
}
|
||||
|
||||
/// A typed number outside the range clamps, as in any value field.
|
||||
#[test]
|
||||
fn typed_values_outside_the_range_clamp() {
|
||||
for (text, want) in [("300", 255.0), ("-5", 0.0)] {
|
||||
let mut h = wand_bar();
|
||||
assert_eq!(type_tolerance(&mut h, text), want, "typing {text}");
|
||||
assert_eq!(shown_tolerance(&h), want, "the field shows the clamped number ({text})");
|
||||
}
|
||||
}
|
||||
|
||||
/// The reference application has no 0.1 step for this whole number: Ctrl/Cmd+arrow leaves 13 as
|
||||
/// 13 on every pass, instead of writing 12.9 for the next pass to round back. A plain arrow still
|
||||
/// steps by one.
|
||||
#[test]
|
||||
fn command_arrows_leave_the_whole_number_as_it_is() {
|
||||
// The field's value after every pass, so a fraction that only lives until the next pass shows.
|
||||
// A bare field has no caption to name it; the options bar gives it one.
|
||||
let mut h = Harness::builder().with_size(vec2(200.0, 40.0)).with_accessibility_check(false).build_ui_state(
|
||||
|ui, (value, seen): &mut (f32, Vec<f32>)| {
|
||||
crate::widgets::value_field_int(ui, value, 0.0..=255.0, "", 58.0);
|
||||
seen.push(*value);
|
||||
},
|
||||
(13.0_f32, Vec::new()),
|
||||
);
|
||||
h.run();
|
||||
h.get_by_role(Role::SpinButton).click();
|
||||
h.run();
|
||||
for key in [egui::Key::ArrowDown, egui::Key::ArrowDown, egui::Key::ArrowUp] {
|
||||
h.state_mut().1.clear();
|
||||
h.key_press_modifiers(egui::Modifiers::COMMAND, key);
|
||||
h.run_steps(2);
|
||||
assert!(h.state().1.iter().all(|&v| v == 13.0), "after Command+{key:?}: {:?}", h.state().1);
|
||||
}
|
||||
h.key_press(egui::Key::ArrowUp);
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().0, 14.0, "a plain arrow still steps by one");
|
||||
}
|
||||
|
||||
/// The Paint Bucket's plain field shares this option and keeps today's behaviour, and a restored
|
||||
/// preference file can hold a fraction: the wand's field takes whatever it finds as the whole
|
||||
/// number it shows, so the wand can never floor a value the field is displaying.
|
||||
#[test]
|
||||
fn a_fractional_option_becomes_the_whole_number_the_field_shows() {
|
||||
let mut h = wand_bar();
|
||||
h.state_mut().ui.tool_options.tolerance = 12.5;
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().ui.tool_options.tolerance, 13.0);
|
||||
assert_eq!(shown_tolerance(&h), 13.0);
|
||||
}
|
||||
|
||||
/// Six white pixels whose second one is 13 levels darker: inside the wand's reach at Tolerance 13,
|
||||
/// outside it at 12, so one click tells the two numbers apart.
|
||||
fn wand_canvas() -> Harness<'static, PhotocraftApp> {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
let mut doc = Document::new("Wand", Size::new(6, 1), ColorMode::Rgb, SampleType::U8);
|
||||
let mut pixels = Surface::with_default(doc.pixel_format(), &[1.0, 1.0, 1.0, 1.0]);
|
||||
pixels.write_pixel(1, 0, &[242.0 / 255.0, 242.0 / 255.0, 242.0 / 255.0, 1.0]);
|
||||
doc.layers.push(Layer::new("Layer 1", LayerContent::Raster(pixels)));
|
||||
let layer = doc.layers[0].id;
|
||||
app.session.add_document(doc, None);
|
||||
app.session.select_layer(layer).unwrap();
|
||||
app.ui.tool = Tool::MagicWand;
|
||||
app.ui.extras.rulers = false;
|
||||
app.sync_views();
|
||||
let mut h = Harness::builder().with_size(vec2(1000.0, 700.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;
|
||||
}
|
||||
// The options bar is a panel of its own; the canvas takes the height that is left.
|
||||
crate::panels::options_bar(app, ui);
|
||||
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);
|
||||
// 40× zoom on a one-pixel-tall document: the pixels are 40 pt apart and easy to hit.
|
||||
let v = &mut h.state_mut().ui.views[0];
|
||||
v.zoom = 40.0;
|
||||
v.center = [3.0, 0.5];
|
||||
v.fit_pending = false;
|
||||
h.run_steps(2);
|
||||
h
|
||||
}
|
||||
|
||||
/// Where document point `(x, y)` lands on screen, as the canvas' own transform maps it.
|
||||
fn screen(h: &Harness<'static, PhotocraftApp>, x: f32, y: f32) -> Pos2 {
|
||||
let app = h.state();
|
||||
let v = &app.ui.views[0];
|
||||
crate::canvas::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(),
|
||||
}
|
||||
.to_screen(x, y)
|
||||
}
|
||||
|
||||
/// Starts from `option` in the shared tool state, clicks the first pixel with the Magic Wand, and
|
||||
/// returns the area selected.
|
||||
fn wand_click(option: f32) -> Rect {
|
||||
let mut h = wand_canvas();
|
||||
h.state_mut().ui.tool_options.tolerance = option;
|
||||
h.run_steps(2);
|
||||
let p = screen(&h, 0.5, 0.5);
|
||||
h.event(egui::Event::PointerMoved(p));
|
||||
h.run();
|
||||
for pressed in [true, false] {
|
||||
h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE });
|
||||
h.run_steps(2);
|
||||
}
|
||||
h.state().session.active().unwrap().doc.selection.as_ref().map_or(Rect::EMPTY, |s| s.content_bounds())
|
||||
}
|
||||
|
||||
/// The wand selects by the whole number the field holds, so a typed `12.5` selects what 13 selects,
|
||||
/// not what the 12 it would have floored to selects.
|
||||
#[test]
|
||||
fn the_wand_selects_by_the_number_the_field_shows() {
|
||||
let (at_12, at_13) = (wand_click(12.0), wand_click(13.0));
|
||||
assert_ne!(at_12, at_13, "Tolerance 12 and 13 must select different areas for this test to mean anything");
|
||||
assert_eq!(wand_click(12.5), at_13, "a typed 12.5 gives the 13 the field shows");
|
||||
}
|
||||
@@ -75,7 +75,7 @@ pub use text_field::{
|
||||
};
|
||||
pub use units::{
|
||||
FieldUnits, fmt_num, fmt_num_prec, fmt_num2, parse_num, set_field_resolution, unit_decimals, unit_of_key, value_field_extent, value_field_fixed,
|
||||
value_field_len, value_field_prec, value_field_prec_blank, value_field_units,
|
||||
value_field_int, value_field_len, value_field_prec, value_field_prec_blank, value_field_units,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -171,6 +171,11 @@ pub(super) struct FieldOpts {
|
||||
/// keystroke (the zoom fields: typing `150` over `50` must not zoom to 1 % on the way). Esc,
|
||||
/// Tab and Alt do not apply it (`zoom_field`).
|
||||
pub(super) hold_typed: bool,
|
||||
/// Whole numbers only ([`super::value_field_int`], #11786): a typed decimal rounds to the
|
||||
/// nearest one, `12.5` and `12,5` both giving `13`, and the value the field holds is never a
|
||||
/// fraction, whichever path wrote it (a drag, another field on the same option, a preference
|
||||
/// file). The number the field shows is therefore the number its caller reads.
|
||||
pub(super) integer: bool,
|
||||
/// Show an unset value as an empty field rather than `0` (the Crop tool's free ratio sides,
|
||||
/// #10888). Editing, scrubbing and parsing are unchanged.
|
||||
pub(super) blank_when_zero: bool,
|
||||
@@ -221,7 +226,7 @@ fn value_field_box(
|
||||
opts: FieldOpts,
|
||||
name: Option<&str>,
|
||||
) -> (Response, Rect) {
|
||||
let FieldOpts { decimals, step_from_decimals, units, extent, .. } = opts;
|
||||
let FieldOpts { decimals, step_from_decimals, units, extent, integer, .. } = opts;
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let (rect, slot) = ui.allocate_exact_size(size, Sense::hover());
|
||||
let last_editor = ui.data(|d| d.get_temp::<egui::Id>(slot.id));
|
||||
@@ -272,7 +277,7 @@ fn value_field_box(
|
||||
let (lo, hi) = (*range.start(), *range.end());
|
||||
// The field's id is only known once it's drawn: last frame's, saved under `slot` below.
|
||||
let focused = ui.data(|d| d.get_temp::<egui::Id>(slot.id)).filter(|id| ui.memory(|m| m.has_focus(*id)));
|
||||
let (step, grid) = arrow_step(ui, slot.id, unit);
|
||||
let (step, grid) = arrow_step(ui, slot.id, unit, integer);
|
||||
// The wheel steps it as the arrow keys do (#5473), focused or under the pointer.
|
||||
let notches = crate::field_wheel::notches(ui, slot.id, focused.is_some(), rect);
|
||||
if notches != 0.0
|
||||
@@ -531,7 +536,7 @@ fn number_edit(
|
||||
units: crate::numeric_expression::Units,
|
||||
opts: FieldOpts,
|
||||
) -> Response {
|
||||
let FieldOpts { decimals, wrap_drag, hold_typed, blank_when_zero, keep_zeros, .. } = opts;
|
||||
let FieldOpts { decimals, wrap_drag, hold_typed, integer, blank_when_zero, keep_zeros, .. } = opts;
|
||||
let (id, ctx) = (ui.next_auto_id(), ui.ctx().clone());
|
||||
// Focused before the DragValue is drawn, so it gains focus this frame and selects its text.
|
||||
if ui.data_mut(|d| d.remove_temp::<bool>(first_field_id())).unwrap_or(false) {
|
||||
@@ -622,6 +627,15 @@ fn number_edit(
|
||||
return lead.and_then(|lead| zoom_number(&lead, units));
|
||||
}
|
||||
}
|
||||
} else if integer {
|
||||
// A whole-number field takes the decimal comma too (`12,5` is `12.5`); a number
|
||||
// with two separators (`1,5,2`) is not one, as in any other field. Each operand
|
||||
// of an expression is its own number, so `1.5+2.5` still adds up.
|
||||
let is_sep = |c: char| matches!(c, '.' | ',');
|
||||
if s.split(|c: char| !(c.is_ascii_digit() || is_sep(c))).any(|n| n.chars().filter(|&c| is_sep(c)).count() > 1) {
|
||||
return None;
|
||||
}
|
||||
s.replace(',', ".")
|
||||
} else {
|
||||
s.to_owned()
|
||||
};
|
||||
@@ -635,6 +649,10 @@ fn number_edit(
|
||||
} else {
|
||||
parse_num_in(s, units)
|
||||
};
|
||||
// A whole-number field already rounds what it reads here, in the parser: the value
|
||||
// it holds while the number is being typed is then the one it keeps, where rounding
|
||||
// it after the DragValue wrote it down would rewrite the text under the typist.
|
||||
let v = if integer { v.map(|v| v.round()) } else { v };
|
||||
// Whether the text being typed is a number at all, for [`typed_text_parses`].
|
||||
ctx.data_mut(|d| d.insert_temp(id.with("parses"), v.is_some()));
|
||||
if ctx.memory(|m| m.has_focus(id)) && !blank && plain(s).is_none() {
|
||||
@@ -665,6 +683,12 @@ fn number_edit(
|
||||
if *value != before && lo <= hi {
|
||||
*value = value.clamp(lo, hi);
|
||||
}
|
||||
// A whole-number field keeps whole numbers whatever wrote one: a drag between two values, a
|
||||
// plain field on the same option, a preference file. The number it shows is then the number
|
||||
// its caller reads, and rounding a whole number changes nothing.
|
||||
if integer && lo <= hi && value.is_finite() && *value != value.round() {
|
||||
*value = value.round().clamp(lo, hi);
|
||||
}
|
||||
resp.flags.set(egui::response::Flags::CHANGED, *value != before);
|
||||
resp
|
||||
}
|
||||
@@ -685,8 +709,10 @@ fn zoom_number(text: &str, units: crate::numeric_expression::Units) -> Option<f6
|
||||
}
|
||||
|
||||
/// Increments a numerical field with the up/down arrow keys. Increments by 1 by default, 10 with shift, and 0.1 with ctrl/cmd.
|
||||
/// Returns the amount to add, and what to round the value to first.
|
||||
fn arrow_step(ui: &mut Ui, slot: egui::Id, step: f32) -> (f32, f32) {
|
||||
/// Returns the amount to add, and what to round the value to first. A whole-number field has no
|
||||
/// 0.1 step: Ctrl/Cmd+arrow leaves its value as it is, as the reference application's Magic Wand
|
||||
/// Tolerance does, instead of writing a fraction the field rounds back next frame (#11786).
|
||||
fn arrow_step(ui: &mut Ui, slot: egui::Id, step: f32, integer: bool) -> (f32, f32) {
|
||||
use egui::{Key, Modifiers};
|
||||
// The field's id is only known once it's drawn, so `value_field` saves it under `slot` for the next frame.
|
||||
let Some(id) = ui.data(|d| d.get_temp::<egui::Id>(slot)).filter(|id| ui.memory(|m| m.has_focus(*id))) else {
|
||||
@@ -698,6 +724,9 @@ fn arrow_step(ui: &mut Ui, slot: egui::Id, step: f32) -> (f32, f32) {
|
||||
for (mods, k) in [(Modifiers::COMMAND, (step / 10.0).max(0.01)), (Modifiers::SHIFT, 10.0 * step), (Modifiers::NONE, step)] {
|
||||
let presses = i.count_and_consume_key(mods, Key::ArrowUp) as f32 - i.count_and_consume_key(mods, Key::ArrowDown) as f32;
|
||||
if presses != 0.0 && mods == Modifiers::COMMAND {
|
||||
if integer {
|
||||
continue;
|
||||
}
|
||||
grid = k;
|
||||
}
|
||||
n += k * presses;
|
||||
|
||||
@@ -28,6 +28,14 @@ pub fn value_field_prec(ui: &mut Ui, value: &mut f32, range: std::ops::RangeIncl
|
||||
value_field_in(ui, value, range, suffix, width, 0.0, FieldOpts { decimals: Some(decimals), ..Default::default() }, None).0
|
||||
}
|
||||
|
||||
/// A [`value_field`] of whole numbers with no decimal places: the Magic Wand's Tolerance, an
|
||||
/// integer 0–255 that its tool floors (#11786). A typed decimal rounds to the nearest whole number,
|
||||
/// `12.5` and `12,5` both giving `13`, and the value the field holds is never a fraction, so the
|
||||
/// number it shows is the number the tool uses. Out-of-range entries clamp, as in any value field.
|
||||
pub fn value_field_int(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive<f32>, suffix: &str, width: f32) -> Response {
|
||||
value_field_in(ui, value, range, suffix, width, 0.0, FieldOpts { decimals: Some(0), integer: true, ..Default::default() }, None).0
|
||||
}
|
||||
|
||||
/// A [`value_field_prec`] that keeps its trailing zeros (`50.0`, `0.0`): Warp's Bend, H and V,
|
||||
/// which the reference shows to one decimal (#12503).
|
||||
pub fn value_field_fixed(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive<f32>, suffix: &str, width: f32, decimals: u32) -> Response {
|
||||
|
||||
Reference in new issue
Block a user