From e23e6cfb3397775962e1f324151b66cada219541 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 1 Dec 2026 18:29:26 -0800 Subject: [PATCH 1/3] Use the Ruler while Measurement Scale is open --- crates/ui-egui/src/canvas/document_display.rs | 2 +- crates/ui-egui/src/canvas/tools/mod.rs | 16 ++- crates/ui-egui/src/dialogs.rs | 6 +- crates/ui-egui/src/tools/analysis/canvas.rs | 93 +++++++++++- crates/ui-egui/src/tools/analysis/dialogs.rs | 103 ++++++++++++-- .../analysis/scale_ruler_while_open_tests.rs | 134 ++++++++++++++++++ 6 files changed, 334 insertions(+), 20 deletions(-) create mode 100644 crates/ui-egui/src/tools/analysis/scale_ruler_while_open_tests.rs diff --git a/crates/ui-egui/src/canvas/document_display.rs b/crates/ui-egui/src/canvas/document_display.rs index e0c6df2c2e..9b73c01670 100644 --- a/crates/ui-egui/src/canvas/document_display.rs +++ b/crates/ui-egui/src/canvas/document_display.rs @@ -618,7 +618,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); diff --git a/crates/ui-egui/src/canvas/tools/mod.rs b/crates/ui-egui/src/canvas/tools/mod.rs index 9090424e21..0f9031be61 100644 --- a/crates/ui-egui/src/canvas/tools/mod.rs +++ b/crates/ui-egui/src/canvas/tools/mod.rs @@ -514,6 +514,7 @@ fn with_rig( ) -> 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( // 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( (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( 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 }; diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index c6488558ce..54e009bd0a 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -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), diff --git a/crates/ui-egui/src/tools/analysis/canvas.rs b/crates/ui-egui/src/tools/analysis/canvas.rs index 1c9953d725..57995867ee 100644 --- a/crates/ui-egui/src/tools/analysis/canvas.rs +++ b/crates/ui-egui/src/tools/analysis/canvas.rs @@ -9,10 +9,11 @@ use craft::behavior::{CancelReason, CountMark, Cursor, CursorBadge, CursorIcon, use craft::color_ui::ui::{ColorSamplerMarks, ColorSamplerTool, ColorSamplers, SamplerEvent}; use craft::draw::ui::{RulerLine, RulerTool}; use craft::ui::canvas::{CanvasTool, NoTool, ToolAction, ToolClaims, ToolContext, ToolHostResponse, ToolKey, ToolPath, ToolPointer, canvas_space}; -use craft::ui::contract::{Access, Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role, Show as _}; +use craft::ui::contract::{Access, CanvasGesture, Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role, Show as _}; use craft::ui::fonts::FontRef; use craft::ui::primitives::{DocRun, DocText, Draw, PaintShape, StrokeWidth}; use craft::ui::runtime::env::Label; +use craft::ui::runtime::sampler; use craft::ui::style::{ComponentStyle, DataColor, StyleColor, StyleCx}; use egui::{Color32, CornerRadius, Pos2, Rect, Response, Vec2, vec2}; use serde_json::json; @@ -26,6 +27,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 +40,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 +49,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, + before: Option<(Option, 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) { + 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 +137,15 @@ fn ruler_line(app: &PhotocraftApp) -> Option { } /// 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)) => { + // The modal's ParamDialog keeps this canvas open for navigation. Pass the ruler's primary drag too. + sampler::pass_tool_gesture(scope.ctx(), host.canvas_id(), CanvasGesture::PRIMARY); + 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 +171,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 +295,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 +326,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 +724,7 @@ impl Component for NoteCards { cx.response.clone() } } + +#[cfg(test)] +#[path = "scale_ruler_while_open_tests.rs"] +mod scale_ruler_while_open_tests; diff --git a/crates/ui-egui/src/tools/analysis/dialogs.rs b/crates/ui-egui/src/tools/analysis/dialogs.rs index c4e96430ee..d6bb2d2722 100644 --- a/crates/ui-egui/src/tools/analysis/dialogs.rs +++ b/crates/ui-egui/src/tools/analysis/dialogs.rs @@ -1,19 +1,22 @@ //! 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::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::dialogs::params; +use crate::state::Tool; /// The three analysis dialogs. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -58,9 +61,21 @@ fn suggested_length(d: &Document) -> f64 { pub(crate) fn open(app: &mut PhotocraftApp, kind: Kind) -> Result { 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::(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 +97,53 @@ pub(crate) fn open(app: &mut PhotocraftApp, kind: Kind) -> Result 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 { + 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 { + app.framework.dialogs.get_by_id::(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::(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 +170,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 +194,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: ` pixel(s) = `, 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,6 +208,15 @@ 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) { + Row::new().show(ui, |ui, _| { + 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() } @@ -147,7 +229,7 @@ fn form(kind: Kind, fields: &mut DialogFields) -> ParamDialog<'_> { 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(), ]; @@ -159,6 +241,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); }) } Kind::DataPoints => { diff --git a/crates/ui-egui/src/tools/analysis/scale_ruler_while_open_tests.rs b/crates/ui-egui/src/tools/analysis/scale_ruler_while_open_tests.rs new file mode 100644 index 0000000000..7ba50a15ca --- /dev/null +++ b/crates/ui-egui/src/tools/analysis/scale_ruler_while_open_tests.rs @@ -0,0 +1,134 @@ +//! #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::super::dialogs::Kind; +use super::{CanvasHost, scale_ruler_on}; +use crate::PhotocraftApp; +use crate::state::Tool; + +type H = Harness<'static, Box>; +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::(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 span = points(&h); + drag(&mut h, span); + 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); + 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); + button(&mut h, span[1], false); + 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); +} From 8fb77b763495e86beca7c9531ad5df7d77621726 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 1 Dec 2026 18:44:25 -0800 Subject: [PATCH 2/3] Remove unused Measurement Scale test import --- .../ui-egui/src/tools/analysis/scale_ruler_while_open_tests.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/ui-egui/src/tools/analysis/scale_ruler_while_open_tests.rs b/crates/ui-egui/src/tools/analysis/scale_ruler_while_open_tests.rs index 7ba50a15ca..2f605a70db 100644 --- a/crates/ui-egui/src/tools/analysis/scale_ruler_while_open_tests.rs +++ b/crates/ui-egui/src/tools/analysis/scale_ruler_while_open_tests.rs @@ -6,7 +6,6 @@ use egui_kittest::Harness; use egui_kittest::kittest::{NodeT as _, Queryable as _}; use serde_json::json; -use super::super::dialogs::Kind; use super::{CanvasHost, scale_ruler_on}; use crate::PhotocraftApp; use crate::state::Tool; From fffecde82acc9b142d781f0bb79b3798393de03c Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 1 Dec 2026 19:16:41 -0800 Subject: [PATCH 3/3] Keep the Scale Ruler gesture registered by the open dialog --- crates/ui-egui/src/tools/analysis/canvas.rs | 9 ++------- crates/ui-egui/src/tools/analysis/dialogs.rs | 20 ++++++++++++------- .../analysis/scale_ruler_while_open_tests.rs | 12 +++++++++++ 3 files changed, 27 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/tools/analysis/canvas.rs b/crates/ui-egui/src/tools/analysis/canvas.rs index 57995867ee..a64e782242 100644 --- a/crates/ui-egui/src/tools/analysis/canvas.rs +++ b/crates/ui-egui/src/tools/analysis/canvas.rs @@ -9,11 +9,10 @@ use craft::behavior::{CancelReason, CountMark, Cursor, CursorBadge, CursorIcon, use craft::color_ui::ui::{ColorSamplerMarks, ColorSamplerTool, ColorSamplers, SamplerEvent}; use craft::draw::ui::{RulerLine, RulerTool}; use craft::ui::canvas::{CanvasTool, NoTool, ToolAction, ToolClaims, ToolContext, ToolHostResponse, ToolKey, ToolPath, ToolPointer, canvas_space}; -use craft::ui::contract::{Access, CanvasGesture, Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role, Show as _}; +use craft::ui::contract::{Access, Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role, Show as _}; use craft::ui::fonts::FontRef; use craft::ui::primitives::{DocRun, DocText, Draw, PaintShape, StrokeWidth}; use craft::ui::runtime::env::Label; -use craft::ui::runtime::sampler; use craft::ui::style::{ComponentStyle, DataColor, StyleColor, StyleCx}; use egui::{Color32, CornerRadius, Pos2, Rect, Response, Vec2, vec2}; use serde_json::json; @@ -141,11 +140,7 @@ pub(crate) fn tool<'a>(scope: &'a ToolScope<'a>, state: &'a mut AnalysisTools, h let tool = scope.with_app(|app| app.ui.tool); let AnalysisTools { ruler, scale, sampler, samplers, count, note } = state; match tool { - Tool::Ruler if scope.with_app(|app| scale_ruler_on(app, host)) => { - // The modal's ParamDialog keeps this canvas open for navigation. Pass the ruler's primary drag too. - sampler::pass_tool_gesture(scope.ctx(), host.canvas_id(), CanvasGesture::PRIMARY); - Box::new(scale.tool.pass(scale.line)) - } + 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)) diff --git a/crates/ui-egui/src/tools/analysis/dialogs.rs b/crates/ui-egui/src/tools/analysis/dialogs.rs index d6bb2d2722..2537c846e0 100644 --- a/crates/ui-egui/src/tools/analysis/dialogs.rs +++ b/crates/ui-egui/src/tools/analysis/dialogs.rs @@ -3,7 +3,7 @@ use craft::behavior::IconId; use craft::ui::choice::Checkbox; -use craft::ui::contract::{Bind, Props as _, Scroll, Show as _, ShowContainer as _}; +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}; @@ -15,6 +15,7 @@ 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; @@ -97,7 +98,8 @@ pub(crate) fn open(app: &mut PhotocraftApp, kind: Kind) -> Result DialogId { @@ -208,8 +210,12 @@ 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) { - Row::new().show(ui, |ui, _| { +fn scale_ruler_note(ui: &mut egui::Ui, canvas: Option) { + 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(); @@ -222,7 +228,7 @@ fn options(pairs: &[(&str, &str)]) -> Vec<(String, Label)> { } /// The dialog of `kind` over `fields`. -fn form(kind: Kind, fields: &mut DialogFields) -> ParamDialog<'_> { +fn form(kind: Kind, fields: &mut DialogFields, scale_canvas: Option) -> ParamDialog<'_> { let key = kind.command(); let dialog = match kind { Kind::Scale => { @@ -233,7 +239,7 @@ fn form(kind: Kind, fields: &mut DialogFields) -> ParamDialog<'_> { 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); @@ -241,7 +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_ruler_note(ui, scale_canvas); }) } Kind::DataPoints => { diff --git a/crates/ui-egui/src/tools/analysis/scale_ruler_while_open_tests.rs b/crates/ui-egui/src/tools/analysis/scale_ruler_while_open_tests.rs index 2f605a70db..4eeff3d3ff 100644 --- a/crates/ui-egui/src/tools/analysis/scale_ruler_while_open_tests.rs +++ b/crates/ui-egui/src/tools/analysis/scale_ruler_while_open_tests.rs @@ -86,8 +86,11 @@ fn an_exposed_drag_updates_only_pixel_length_and_ok_restores_the_tool() { 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"); @@ -114,6 +117,7 @@ fn a_nested_prompt_blocks_measurement_and_escape_discards_the_scale_draft() { 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(); @@ -123,7 +127,15 @@ fn a_nested_prompt_blocks_measurement_and_escape_discards_the_scale_draft() { 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());