Merge pull request #18911

Co-authored-by: autocraft-bot[bot] <354215646+autocraft-bot[bot]@users.noreply.github.com>
This commit is contained in:
davidmann4andautocraft-bot[bot] authored and autocraft-bot[bot] committed 2026-12-02 08:06:59 +00:00
commit 9ce2ec2ada
6 files changed
+348 -22

No files matched your search

@@ -623,7 +623,7 @@ fn canvas_controls(
crate::slice_ui::canvas_controls(ui, app, rect);
crate::symmetry_ui::canvas_controls(ui, app, rect);
crate::perspective_crop_ui::body(app, ui, rect);
crate::analysis::canvas::body(app, ui, rect);
crate::analysis::canvas::body(app, ui, rect, host);
// The frame is the active document's: another document on screen shows none (#18368).
if primary && app.session.active_index() == Some(host.idx) {
reported.crop = super::tools::crop::show_frame(app, ui, rect);
+13 -3
View File
@@ -514,6 +514,7 @@ fn with_rig<R>(
) -> R {
let tool = app.ui.tool;
let fam = family(tool);
let scale_ruler = crate::analysis::canvas::scale_ruler_on(app, host);
let in_gesture = ToolHost::in_gesture(ctx, host.canvas_id());
// Tools that own state the app lends nobody are built before the scope takes the app. The Crop tool edits the active
// document's frame, so only that document's canvas runs it (#18368); a gesture keeps it to its cancel.
@@ -528,7 +529,7 @@ fn with_rig<R>(
// gesture another pick began leaves it in the app, where that tool edits it: the Frame tool's press on an image
// handle opens the session and its drag moves the box.
let transform_open = app.ui.transform.is_some();
let lends_transform = stand_ins && (!in_gesture || tools.gesture_pick == GesturePick::Transform);
let lends_transform = stand_ins && !scale_ruler && (!in_gesture || tools.gesture_pick == GesturePick::Transform);
let free_transform = if lends_transform { app.ui.transform.take() } else { None };
let BodyShown { crop: crop_shown, transform_snapped, .. } = shown;
let mut transform = free_transform.as_ref().map(|session| crate::transform_tool::canvas_tool(session, transform_snapped));
@@ -539,7 +540,7 @@ fn with_rig<R>(
(Some(tool), Some(run)) => Some(crop::pass(tool, run, ctx, crop_shown)),
_ => None,
};
let command_wanted = stand_ins && !transform_open && takes_command_stand_in(tool);
let command_wanted = stand_ins && !scale_ruler && !transform_open && takes_command_stand_in(tool);
let alt_wanted = stand_ins && !transform_open && super::cursor_policy::alt_eyedropper(tool);
let source_wanted = stand_ins && matches!(tool, Tool::CloneStamp | Tool::Healing);
@@ -653,7 +654,7 @@ fn with_rig<R>(
alt_t = Some(retouch::source_tool(&scope, state, host));
}
let alt_stand_in = alt_t.is_some();
let mut pre = Preflight { scope: &scope, inner: selected, tool, dialog: dialog_picked, outline_open, alt_stand_in };
let mut pre = Preflight { scope: &scope, inner: selected, tool, dialog: dialog_picked || scale_ruler, outline_open, alt_stand_in };
let mut tool_host = ToolHost::new().momentary(momentary);
if let Some(mover) = command_t.as_mut() {
tool_host = tool_host.stand_in(StandInKey::Command, dynamic(mover));
@@ -806,6 +807,15 @@ pub(crate) fn tool_changed(app: &mut PhotocraftApp, ctx: &egui::Context, host: C
app.canvas_tools = tools;
}
/// Cancels the gesture that belongs to `doc`, using its original canvas even if the document has closed.
pub(crate) fn cancel_document_gesture(app: &mut PhotocraftApp, ctx: &egui::Context, doc: photocraft_doc::DocId) {
let Some((_, host)) = app.canvas_tools.gesture_on.filter(|(owner, _)| *owner == doc.0) else { return };
app.canvas_tools.gesture_on = None;
if ToolHost::in_gesture(ctx, host.canvas_id()) {
tool_changed(app, ctx, host);
}
}
/// Whether the active document's own canvas has a gesture running, for the readers with no `Context` at hand.
pub(crate) fn in_gesture(app: &PhotocraftApp) -> bool {
let Some(idx) = app.session.active_index() else { return false };
+5 -1
View File
@@ -132,7 +132,11 @@ pub(crate) mod params {
check: Some(crate::canvas_tool_menu::pen_dialogs::check),
..ParamFamily::new(crate::canvas_tool_menu::pen_dialogs::owns, crate::canvas_tool_menu::pen_dialogs::run)
},
ParamFamily::new(crate::analysis::dialogs::owns, crate::analysis::dialogs::run),
ParamFamily {
cancel: Some(crate::analysis::dialogs::cancel),
document: Some(crate::analysis::dialogs::document),
..ParamFamily::new(crate::analysis::dialogs::owns, crate::analysis::dialogs::run)
},
ParamFamily::new(crate::layers_panel_ui::owns, crate::layers_panel_ui::run),
ParamFamily {
check: Some(image_processor_ui::check),
+82 -4
View File
@@ -26,6 +26,7 @@ use crate::state::Tool;
/// The family's state between passes, kept in `CanvasTools::analysis`.
pub(crate) struct AnalysisTools {
ruler: RulerTool,
scale: ScaleRuler,
sampler: ColorSamplerTool,
/// The document's points as the framework's collection, which the sampler pass borrows. It is rebuilt from the
/// document at every pass (`tool`); it is storage for that borrow, not state.
@@ -38,6 +39,7 @@ impl Default for AnalysisTools {
fn default() -> Self {
Self {
ruler: RulerTool::new(),
scale: ScaleRuler::default(),
sampler: ColorSamplerTool::new(),
samplers: ColorSamplers::new(),
count: CountTool::default(),
@@ -46,6 +48,72 @@ impl Default for AnalysisTools {
}
}
/// The scale form's temporary line and the draft value as they stood before a drag. Neither touches the document.
#[derive(Default)]
struct ScaleRuler {
tool: RulerTool,
line: Option<RulerLine>,
before: Option<(Option<RulerLine>, f64)>,
}
impl ScaleRuler {
fn restore_drag(&mut self, app: &mut PhotocraftApp) {
if let Some((line, length)) = self.before.take() {
self.line = line;
super::dialogs::set_pixel_length(app, length);
}
}
fn set_line(&mut self, app: &mut PhotocraftApp, line: Option<RulerLine>) {
self.line = line;
if let Some(line) = line {
let length = line.start.distance(line.end);
if length.is_finite() && length > 0.0 {
super::dialogs::set_pixel_length(app, length.round().clamp(1.0, super::dialogs::MAX_PIXEL_LENGTH));
}
}
}
fn drain(&mut self, app: &mut PhotocraftApp) {
if !super::dialogs::measuring(app) {
if self.before.is_some() {
self.restore_drag(app);
self.tool = RulerTool::new();
}
return;
}
for event in self.tool.take_events() {
match event {
EditEvent::Begin { .. } => {
self.before = super::dialogs::pixel_length(app).map(|length| (self.line, length));
}
EditEvent::Update { value, .. } => self.set_line(app, value),
EditEvent::Commit { after, .. } => {
if self.before.is_some_and(|(line, _)| after == line && self.line != after) {
// A click or short release kept the preceding line. Keep the draft length too.
self.restore_drag(app);
} else {
self.set_line(app, after);
self.before = None;
}
}
EditEvent::Set { after, .. } => self.set_line(app, after),
EditEvent::Cancel { .. } => self.restore_drag(app),
_ => {}
}
}
}
}
/// Whether this exact canvas may run the temporary scale ruler and paint its line.
pub(crate) fn scale_ruler_on(app: &PhotocraftApp, host: CanvasHost) -> bool {
app.session.active_index() == Some(host.idx) && host.is_primary(app) && super::dialogs::measuring(app)
}
pub(super) fn clear_scale_ruler(app: &mut PhotocraftApp) {
app.canvas_tools.analysis.scale = ScaleRuler::default();
}
/// The document's Color Sampler points as the framework's collection, with the document's size in pixels. The one
/// place the document's list becomes `ColorSamplers`.
pub(super) fn samplers_of(app: &PhotocraftApp) -> Option<(ColorSamplers, [u32; 2])> {
@@ -68,10 +136,11 @@ fn ruler_line(app: &PhotocraftApp) -> Option<RulerLine> {
}
/// The tool of `Tool::{Ruler, ColorSampler, Count, Note}` for one pass.
pub(crate) fn tool<'a>(scope: &'a ToolScope<'a>, state: &'a mut AnalysisTools, _host: CanvasHost) -> FamilyTool<'a> {
pub(crate) fn tool<'a>(scope: &'a ToolScope<'a>, state: &'a mut AnalysisTools, host: CanvasHost) -> FamilyTool<'a> {
let tool = scope.with_app(|app| app.ui.tool);
let AnalysisTools { ruler, sampler, samplers, count, note } = state;
let AnalysisTools { ruler, scale, sampler, samplers, count, note } = state;
match tool {
Tool::Ruler if scope.with_app(|app| scale_ruler_on(app, host)) => Box::new(scale.tool.pass(scale.line)),
Tool::Ruler => {
let line = scope.with_app(|app| ruler_line(app));
Box::new(ruler.pass(line))
@@ -97,6 +166,7 @@ pub(crate) fn tool<'a>(scope: &'a ToolScope<'a>, state: &'a mut AnalysisTools, _
/// Turns the events the tools reported into engine commands, in order.
pub(crate) fn drain(app: &mut PhotocraftApp, state: &mut AnalysisTools, _response: &ToolHostResponse) {
state.scale.drain(app);
for event in state.ruler.take_events() {
match event {
// A drag's updates are not applied: the pass shows the running line from the tool's own proposal, and the
@@ -220,7 +290,8 @@ fn pixel_centre(at: [f64; 2]) -> [f64; 2] {
/// The ruler line, the sampler marks, the count markers and the note cards over the document, in the canvas body over
/// `rect`. The marks show with every tool; the line with its handles only with the Ruler. View › Extras off hides the
/// line (View › Show has no Ruler entry, #11987) and the sampler marks, whose points and Info readouts stay (#11741).
pub(crate) fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, rect: Rect) {
pub(crate) fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, rect: Rect, host: CanvasHost) {
let scale = scale_ruler_on(app, host);
let view = &app.ui.view;
let (show_count, show_notes, extras) = (view.shows(view.show.count), view.shows(view.show.notes), view.extras);
let line = ruler_line(app).filter(|_| extras);
@@ -250,7 +321,10 @@ pub(crate) fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, rect: Rect) {
};
let selected = app.ui.analysis.note_selected;
let tools = &mut app.canvas_tools.analysis;
if app.ui.tool == Tool::Ruler {
if scale {
let scale = &mut tools.scale;
scale.tool.pass(scale.line.filter(|_| extras)).show_line(ui, rect);
} else if app.ui.tool == Tool::Ruler {
tools.ruler.pass(line).show_line(ui, rect);
} else if let Some(line) = line {
// The line and its arm stay drawn under every tool (#11987); only the Ruler tool has handles on them.
@@ -645,3 +719,7 @@ impl Component for NoteCards {
cx.response.clone()
}
}
#[cfg(test)]
#[path = "scale_ruler_while_open_tests.rs"]
mod scale_ruler_while_open_tests;
+102 -13
View File
@@ -1,19 +1,23 @@
//! The Set Measurement Scale, Select Data Points and Place Scale Marker dialogs: parameter forms hosted on the dialog
//! host, answered through the `ParamFamily` row of `dialogs.rs`.
use craft::behavior::IconId;
use craft::ui::choice::Checkbox;
use craft::ui::contract::{Bind, Props as _, Scroll, Show as _, ShowContainer as _};
use craft::ui::dialog::DialogId;
use craft::ui::display::{Divider, Elide, Text};
use craft::ui::layout_components::Stack;
use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamDialog, ParamKind, ParamResult};
use craft::ui::contract::{Bind, CanvasGesture, Props as _, Sampler as _, Scroll, Show as _, ShowContainer as _};
use craft::ui::dialog::{DialogId, dialog_id};
use craft::ui::display::{Divider, Elide, Icon, Text};
use craft::ui::layout_components::{Row, Stack};
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
use craft::ui::primitives::IconSpec;
use craft::ui::runtime::env::{Env, Label, UnitKind};
use photocraft_doc::Document;
use photocraft_doc::{DocId, Document};
use photocraft_engine::analysis_cmds;
use serde_json::{Value, json};
use crate::PhotocraftApp;
use crate::canvas::document_display::CanvasHost;
use crate::dialogs::params;
use crate::state::Tool;
/// The three analysis dialogs.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -58,9 +62,21 @@ fn suggested_length(d: &Document) -> f64 {
pub(crate) fn open(app: &mut PhotocraftApp, kind: Kind) -> Result<DialogId, String> {
let no_document = || tl!("No document is open.").to_owned();
let mut fields = DialogFields::new();
let mut captured = Value::Null;
match kind {
Kind::Scale => {
let id = scale_id();
if app.framework.dialogs.get_by_id::<HostedParamDialog>(id).is_some() {
return Ok(id);
}
let doc = app.session.active().ok_or_else(no_document)?.doc.clone();
let previous = crate::tool_memory::selected(app);
captured = json!({"document": doc.id.0, "previousTool": previous});
let ctx = app.ctx().clone();
crate::canvas::tools::cancel_document_gesture(app, &ctx, doc.id);
app.ui.spring = None;
app.stylus.tool_before_eraser = None;
app.ui.tool = Tool::Ruler;
let sc = &doc.measurement.scale;
fields.set("preset", "custom");
fields.set("pixelLength", sc.pixel_length);
@@ -82,7 +98,54 @@ pub(crate) fn open(app: &mut PhotocraftApp, kind: Kind) -> Result<DialogId, Stri
fields.set("color", "black");
}
}
Ok(params::open_param(app, kind.command(), fields, Value::Null, move |f: &mut DialogFields| form(kind, f)))
let scale_canvas = app.session.active_index().filter(|_| kind == Kind::Scale).map(|index| CanvasHost::primary(app, index).canvas_id());
Ok(params::open_param(app, kind.command(), fields, captured, move |f: &mut DialogFields| form(kind, f, scale_canvas)))
}
fn scale_id() -> DialogId {
dialog_id(Kind::Scale.command())
}
/// The document bound to the scale form, for the host's document-close and canvas-routing checks.
pub(crate) fn document(captured: &Value) -> Option<DocId> {
captured.get("document").and_then(Value::as_u64).map(DocId)
}
/// The top scale dialog can measure only the active document it opened on.
pub(super) fn measuring(app: &PhotocraftApp) -> bool {
app.framework.dialogs.stack().top() == Some(scale_id())
&& app.ui.tool == Tool::Ruler
&& app.framework.captured.get(Kind::Scale.command()).and_then(document).is_some_and(|id| app.session.active().is_some_and(|st| st.doc.id == id))
}
pub(super) fn pixel_length(app: &PhotocraftApp) -> Option<f64> {
app.framework.dialogs.get_by_id::<HostedParamDialog>(scale_id())?.fields().number("pixelLength")
}
pub(super) fn set_pixel_length(app: &mut PhotocraftApp, length: f64) {
if let Some(form) = app.framework.dialogs.get_mut_by_id::<HostedParamDialog>(scale_id())
&& form.fields().number("pixelLength") != Some(length)
{
form.set_field("pixelLength", FieldValue::Number(length));
}
}
/// OK and every cancellation path give the canvas and previous tool back together.
fn finish_scale(app: &mut PhotocraftApp, ctx: &egui::Context, captured: &Value) {
if let Some(doc) = document(captured) {
crate::canvas::tools::cancel_document_gesture(app, ctx, doc);
}
super::canvas::clear_scale_ruler(app);
if let Some(previous) = captured.get("previousTool").and_then(|tool| serde_json::from_value(tool.clone()).ok()) {
app.ui.tool = previous;
}
}
pub(crate) fn cancel(app: &mut PhotocraftApp, ctx: &egui::Context, id: DialogId) {
if id == scale_id() {
let captured = params::captured(app, Kind::Scale.command());
finish_scale(app, ctx, &captured);
}
}
/// Whether `key` is the key of one of these dialogs.
@@ -109,10 +172,20 @@ pub(crate) fn command(kind: Kind, f: &DialogFields) -> Option<(&'static str, Val
}
/// OK: runs the dialog's command; an engine refusal goes to the status line.
pub(crate) fn run(app: &mut PhotocraftApp, _ctx: &egui::Context, result: ParamResult) {
pub(crate) fn run(app: &mut PhotocraftApp, ctx: &egui::Context, result: ParamResult) {
let Some(kind) = Kind::of(&result.key) else { return };
let Some((id, params)) = command(kind, &result.fields) else { return };
if let Err(error) = app.run(id, params)
let Some((id, values)) = command(kind, &result.fields) else { return };
let outcome = if kind == Kind::Scale {
let captured = params::captured(app, id);
finish_scale(app, ctx, &captured);
match document(&captured) {
Some(doc) => app.with_document(doc, |app| app.run(id, values)),
None => Err(tl!("No document is open.").to_owned()),
}
} else {
app.run(id, values)
};
if let Err(error) = outcome
&& error != "cancelled"
{
app.ui.status = error;
@@ -123,6 +196,8 @@ pub(crate) fn run(app: &mut PhotocraftApp, _ctx: &egui::Context, result: ParamRe
/// The most characters of the scale readout that set its width: about the width of the dialog's fields.
const READOUT_CHARS: usize = 46;
pub(super) const MAX_PIXEL_LENGTH: f64 = 1e7;
/// The Measurement Scale readout: `<px> pixel(s) = <length, 4 decimals> <units>`, with `decimal` as the decimal mark,
/// as the reference shows it while the values are typed (#17414). The Default preset reads 1 pixel(s) = 1 pixels.
pub(crate) fn scale_readout(f: &DialogFields, decimal: char) -> String {
@@ -135,23 +210,36 @@ pub(crate) fn scale_readout(f: &DialogFields, decimal: char) -> String {
format!("{} pixel(s) = {} {units}", mark(pixels.to_string()), mark(format!("{length:.4}")))
}
fn scale_ruler_note(ui: &mut egui::Ui, canvas: Option<egui::Id>) {
Row::new().show(ui, |ui, cx| {
// The dialog runs every pass, even when the canvas replays its cached draw.
if let Some(canvas) = canvas {
cx.pass_canvas_gesture(canvas, CanvasGesture::PRIMARY);
}
Icon::new(IconSpec::svg(IconId::new("info"))).show(ui);
let note = tl!("The Ruler tool has been activated while this dialog is open. You may use it to measure the pixel length for use in your scale.");
let sample: String = note.chars().take(READOUT_CHARS).collect();
Text::new(note).sample(Label::from(sample)).show(ui);
});
}
fn options(pairs: &[(&str, &str)]) -> Vec<(String, Label)> {
pairs.iter().map(|(key, name)| ((*key).to_owned(), Label::from((*name).to_owned()))).collect()
}
/// The dialog of `kind` over `fields`.
fn form(kind: Kind, fields: &mut DialogFields) -> ParamDialog<'_> {
fn form(kind: Kind, fields: &mut DialogFields, scale_canvas: Option<egui::Id>) -> ParamDialog<'_> {
let key = kind.command();
let dialog = match kind {
Kind::Scale => {
let rows = vec![
Param::new("preset", tl!("Presets:"), ParamKind::choice(options(&[("custom", tl!("Custom"))]), Some("custom".into()))).not_remembered(),
// The dialog opens on its first text-entry field and selects its value.
Param::new("pixelLength", tl!("Pixel Length:"), ParamKind::number(Some(0.001), Some(1e7), 1.0, 1.0, 4)).not_remembered(),
Param::new("pixelLength", tl!("Pixel Length:"), ParamKind::number(Some(0.001), Some(MAX_PIXEL_LENGTH), 1.0, 1.0, 4)).not_remembered(),
Param::new("logicalLength", tl!("Logical Length:"), ParamKind::number(Some(0.0001), Some(1e7), 1.0, 1.0, 4)).not_remembered(),
Param::new("units", tl!("Logical Units:"), ParamKind::text("pixels")).not_remembered(),
];
ParamDialog::command(key, tl!("Measurement Scale"), rows).below(|ui, f| {
ParamDialog::command(key, tl!("Measurement Scale"), rows).below(move |ui, f| {
// One line: units too long for it are cut with "…", so the dialog keeps its width (#17414). The decimal
// mark is the one the fields above write: the system's (any mark, not only `.` or `,`) or the host's.
let text = scale_readout(f, Env::of(ui).format().separators().0);
@@ -159,6 +247,7 @@ fn form(kind: Kind, fields: &mut DialogFields) -> ParamDialog<'_> {
// and long units are cut with "…" instead of widening the dialog.
let sample: String = text.chars().take(READOUT_CHARS).collect();
Text::new(Label::from(text)).elide(Elide::End).sample(Label::from(sample)).show(ui);
scale_ruler_note(ui, scale_canvas);
})
}
Kind::DataPoints => {
@@ -0,0 +1,145 @@
//! #17415: the top Measurement Scale form keeps keyboard focus while a real Ruler drag edits its pixel length.
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog};
use egui::accesskit::Role;
use egui::{Key, Modifiers, PointerButton, Pos2, Rect};
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT as _, Queryable as _};
use serde_json::json;
use super::{CanvasHost, scale_ruler_on};
use crate::PhotocraftApp;
use crate::state::Tool;
type H = Harness<'static, Box<PhotocraftApp>>;
const COMMAND: &str = "image.analysis.setMeasurementScale";
const NOTE: &str = "The Ruler tool has been activated while this dialog is open. You may use it to measure the pixel length for use in your scale.";
fn fixture(tool: Tool) -> H {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 640, "height": 560})).unwrap();
app.run(COMMAND, json!({"preset": "custom", "pixelLength": 42, "logicalLength": 3.5, "units": "cm"})).unwrap();
app.sync_views();
app.ui.extras.rulers = false;
app.ui.tool = tool;
let mut h = Harness::builder().with_context(app.ctx().clone()).with_size(egui::vec2(1600.0, 1000.0)).with_max_steps(64).build_eframe(move |_cc| app);
h.run_steps(4);
let view = &mut h.state_mut().ui.views[0];
view.zoom = 1.0;
view.center = [320.0, 280.0];
view.clear_pending();
h.run_steps(2);
h
}
fn open(h: &mut H) {
let ctx = h.ctx.clone();
crate::menus::invoke(h.state_mut(), &ctx, COMMAND, json!({})).unwrap();
h.run_steps(4);
}
fn fields(h: &H) -> &DialogFields {
h.state().framework.dialogs.get_by_id::<HostedParamDialog>(craft::ui::dialog::dialog_id(COMMAND)).expect("Measurement Scale is open").fields()
}
fn length_has_focus(h: &H) -> bool {
h.query_all_by_role(Role::SpinButton).any(|n| n.is_focused() && n.accesskit_node().label().is_some_and(|s| s.trim_end_matches(':') == "Pixel Length"))
}
/// Finds the same 200 px drag in an exposed part of the bound image, away from the centred form.
fn points(h: &H) -> [Pos2; 2] {
let form = h
.query_all_by_role(Role::Window)
.chain(h.query_all_by_role(Role::Dialog))
.find(|n| n.accesskit_node().label().as_deref() == Some("Measurement Scale"))
.expect("the form's window")
.rect();
let canvas = crate::canvas::document_display::active_view(h.state()).expect("document canvas").rect;
[30.0, 95.0, 465.0, 530.0]
.into_iter()
.map(|y| [100.0, 300.0].map(|x| crate::canvas::testing::to_screen(h.state(), [x, y])))
.find(|[a, b]| canvas.contains(*a) && canvas.contains(*b) && !form.intersects(Rect::from_two_pos(*a, *b).expand(3.0)))
.expect("an exposed 200 px span of the image")
}
fn button(h: &mut H, pos: Pos2, pressed: bool) {
h.event(egui::Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
h.run_steps(2);
}
fn drag(h: &mut H, [start, end]: [Pos2; 2]) {
h.event(egui::Event::PointerMoved(start));
h.run_steps(2);
button(h, start, true);
h.event(egui::Event::PointerMoved(end));
h.run_steps(3);
}
#[test]
fn an_exposed_drag_updates_only_pixel_length_and_ok_restores_the_tool() {
let mut h = fixture(Tool::Move);
h.state_mut().run("image.analysis.rulerTool", json!({"start": [20, 30], "end": [60, 30]})).unwrap();
let original = h.state().session.active().unwrap().doc.measurement.ruler;
open(&mut h);
assert_eq!(h.state().ui.tool, Tool::Ruler);
assert!(length_has_focus(&h));
assert!(h.query_all_by_role(Role::Label).any(|n| n.accesskit_node().value().or_else(|| n.accesskit_node().label()).as_deref() == Some(NOTE)));
let primary = CanvasHost::primary(h.state(), 0);
assert!(scale_ruler_on(h.state(), primary));
assert!(!scale_ruler_on(h.state(), CanvasHost { idx: 0, window: Some(99) }));
// Let the canvas settle past the lifetime of any registration made when the form opened.
h.run_steps(4);
let span = points(&h);
drag(&mut h, span);
assert!(crate::canvas::tools::in_gesture(h.state()), "the visible canvas claims the modal ruler drag");
let f = fields(&h);
assert_eq!((f.number("pixelLength"), f.number("logicalLength"), f.text("units")), (Some(200.0), Some(3.5), Some("cm")));
assert!(length_has_focus(&h), "the admitted canvas press leaves keyboard focus in the form");
assert!(h.query_all_by_role(Role::Label).any(|n| {
n.accesskit_node().value().or_else(|| n.accesskit_node().label()).is_some_and(|t| t.starts_with("200 pixel(s) = ") && t.ends_with(" cm"))
}));
button(&mut h, span[1], false);
assert!(h.state().canvas_tools.analysis.scale.line.is_some(), "the temporary line stays while the form is open");
h.get_by_role_and_label(Role::Button, "OK").click();
h.run_steps(4);
assert!(!h.state().dialog_open());
assert_eq!(h.state().ui.tool, Tool::Move);
assert!(h.state().canvas_tools.analysis.scale.line.is_none());
let measurement = &h.state().session.active().unwrap().doc.measurement;
assert_eq!(measurement.ruler, original);
assert_eq!((measurement.scale.pixel_length, measurement.scale.logical_length, measurement.scale.units.as_str()), (200.0, 3.5, "cm"));
}
#[test]
fn a_nested_prompt_blocks_measurement_and_escape_discards_the_scale_draft() {
let mut h = fixture(Tool::Brush);
open(&mut h);
let span = points(&h);
let alert = crate::dialogs::alerts::alert(h.state_mut(), "Test prompt over Measurement Scale");
h.run_steps(4);
drag(&mut h, span);
assert!(!crate::canvas::tools::in_gesture(h.state()), "the nested prompt owns the pointer");
button(&mut h, span[1], false);
assert_eq!(fields(&h).number("pixelLength"), Some(42.0));
let ctx = h.ctx.clone();
assert!(h.state_mut().framework.dialogs.cancel_by_id(&ctx, alert));
h.run_steps(4);
drag(&mut h, span);
assert_eq!(fields(&h).number("pixelLength"), Some(200.0));
h.key_press(Key::Escape);
h.run_steps(4);
assert_eq!(fields(&h).number("pixelLength"), Some(42.0), "Escape cancels the held canvas drag before dismissing the form");
button(&mut h, span[1], false);
let span = points(&h);
drag(&mut h, span);
button(&mut h, span[1], false);
assert_eq!(fields(&h).number("pixelLength"), Some(200.0));
h.key_press(Key::Escape);
h.run_steps(4);
assert!(!h.state().dialog_open());
assert_eq!(h.state().ui.tool, Tool::Brush);
assert!(h.state().canvas_tools.analysis.scale.line.is_none());
let measurement = &h.state().session.active().unwrap().doc.measurement;
assert!(measurement.ruler.is_none());
assert_eq!(measurement.scale.pixel_length, 42.0);
}