diff --git a/crates/draw/src/ui/transform/session_overlay.rs b/crates/draw/src/ui/transform/session_overlay.rs index de65d190e..f5414abac 100644 --- a/crates/draw/src/ui/transform/session_overlay.rs +++ b/crates/draw/src/ui/transform/session_overlay.rs @@ -160,6 +160,7 @@ impl<'a, W: TransformWarp> TransformOverlay<'a, W> { .reference_point(session.reference_point()) .reach(self.reach) .rotate_zone(self.rotate_zone) + .own_context_menu(self.reach == TransformReach::Box) .id_source(self.id); if let Some(mods) = self.mods { tbox = tbox.mods(mods); diff --git a/crates/draw/src/ui/transform/transform_box.rs b/crates/draw/src/ui/transform/transform_box.rs index c5605959c..837fe4dee 100644 --- a/crates/draw/src/ui/transform/transform_box.rs +++ b/crates/draw/src/ui/transform/transform_box.rs @@ -509,6 +509,10 @@ pub struct TransformBox<'a> { /// and an open drag's Escape still cancels the drag. #[prop] session_commit: bool, + /// The caller hangs a context menu of its own on the box (`Menu::context` over its response): every part takes the + /// right click, so it does not reach the tool under the box. + #[prop] + own_context_menu: bool, /// Whether this pass holds a drag of the reference point, so the hidden point is drawn while it moves. pivot_held: bool, /// Whether this pass holds a drag that began, so a live line's box shows as it scales. @@ -538,6 +542,7 @@ impl<'a> TransformBox<'a> { reach: TransformReach::Box, color: None, session_commit: true, + own_context_menu: false, pivot_held: false, dragging: false, report: Report::default(), @@ -1098,11 +1103,11 @@ fn paint_frame(draw: &Draw<'_>, style: &TransformBoxStyle, line: StrokeColor, co /// The move reach outside the box whose corners are `quad` on the screen: every point within `points` of its border, /// as a strip along each side and a round sector outside each corner (PhotoCraft's type move reach measures the /// distance to the nearest side, pc-prod-e76 type_transform.rs:156-196). -fn declare_ring(cx: &mut PartsCx<'_, TransformBox<'_>>, quad: &[Pos2; 4], points: f32) { +fn declare_ring(cx: &mut PartsCx<'_, TransformBox<'_>>, quad: &[Pos2; 4], points: f32, context: Sense) { let outward = outward_normals(quad); let mut declare = |part: usize, shape: Vec| { cx.part(MOVE_RING.at(part as u64), HitShape::Polygon(shape)) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Inside)) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Inside) | context) .priority(HitPriority::new(HitLevel::Body, RING_SUB)) .pointer_only(MOVE_BY_KEY); }; @@ -1250,9 +1255,10 @@ impl Component for TransformBox<'_> { let style = cx.style; let screen = on_screen(&space.view, &state); let quad: [Pos2; 4] = screen.quad.map(pos); + let context = if self.own_context_menu { Sense::CONTEXT_CLICK } else { Sense::empty() }; if self.move_only().is_some() { if let Some(points) = self.ring_reach() { - declare_ring(cx, &quad, points); + declare_ring(cx, &quad, points, context); } return; } @@ -1279,13 +1285,13 @@ impl Component for TransformBox<'_> { ) } }; - cx.part(BOX.at(part.index()), shape).sense(sense | slop_sense(part)).priority(priority).focus_shape(focus).focusable(); + cx.part(BOX.at(part.index()), shape).sense(sense | slop_sense(part) | context).priority(priority).focus_shape(focus).focusable(); any = true; } if let Some(line) = self.line { for (end, at) in line.free_ends() { cx.part(LINE_END.at(end.index()), HitShape::circle(space.view.to_screen(at), style.handle_reach)) - .sense(Sense::DRAG | Sense::CLICK) + .sense(Sense::DRAG | Sense::CLICK | context) .priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB)) .pointer_only(LINE_END_BY_KEY); } @@ -1299,7 +1305,7 @@ impl Component for TransformBox<'_> { let band = if self.rules.edge_band > 0.0 { edge_band(&quad, side, self.rules.edge_band) } else { side_band(&quad, side, style.side_band) }; cx.part(EDGE.at(u64::from(k)), band) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Edge(k))) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Edge(k)) | context) .priority(HitPriority::new(HitLevel::Handle, EDGE_SUB)) .pointer_only(EDGE_BY_KEY); } @@ -1309,7 +1315,7 @@ impl Component for TransformBox<'_> { for (end, side) in [(0u64, corner), (1, (corner + 3) % 4)] { let Some(reach) = corner_reach(&quad, side, corner, style.side_band) else { continue }; cx.part(CORNER_REACH.at(2 * u64::from(k) + end), reach) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Corner(k))) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Corner(k)) | context) .priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB)) .pointer_only(CORNER_BY_KEY); } @@ -1317,7 +1323,7 @@ impl Component for TransformBox<'_> { if self.declares_centre() { let centre = quad.iter().fold(Vec2::ZERO, |sum, corner| sum + corner.to_vec2()) / 4.0; cx.part(CENTRE.at(0), HitShape::circle(centre.to_pos2(), style.hit)) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Inside)) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Inside) | context) .priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB)) .pointer_only(MOVE_BY_KEY); } @@ -1328,7 +1334,7 @@ impl Component for TransformBox<'_> { RotateZone::Outside | RotateZone::Border { .. } if self.rules.allows(BoxPart::Outside) => { for (corner, region) in outside_regions(&quad, rect).into_iter().enumerate() { cx.part(OUTSIDE.at(corner as u64), HitShape::Polygon(region)) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside)) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside) | context) .priority(HitPriority::new(HitLevel::Background, 0)) .pointer_only(ROTATE_BY_KEY); } @@ -1336,7 +1342,7 @@ impl Component for TransformBox<'_> { RotateZone::Band if self.rules.allows(BoxPart::Outside) => { for (corner, ring) in band_rings(&screen, style).into_iter().enumerate() { cx.part(OUTSIDE.at(corner as u64), HitShape::Polygon(ring)) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside)) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside) | context) .priority(HitPriority::new(HitLevel::Body, 0)) .pointer_only(ROTATE_BY_KEY); } @@ -1347,7 +1353,7 @@ impl Component for TransformBox<'_> { if self.has_knob() { let (knob, _) = knob_at(&quad, rect, style); cx.part(KNOB.at(0), HitShape::circle(knob, style.handle_reach)) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside)) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside) | context) .priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB)) .pointer_only(ROTATE_BY_KEY); } @@ -1355,7 +1361,7 @@ impl Component for TransformBox<'_> { RotateZone::Handle if self.rules.allows(BoxPart::Outside) => { let (_, knob) = rotate_handle(&quad, style.rotate_stem); cx.part(ROTATE_HANDLE.at(0), HitShape::circle(knob, style.handle_reach)) - .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside)) + .sense(Sense::DRAG | Sense::CLICK | slop_sense(BoxPart::Outside) | context) .priority(HitPriority::new(HitLevel::Handle, HANDLE_SUB)) .pointer_only(ROTATE_BY_KEY); } diff --git a/crates/draw/tests/it/transform_box.rs b/crates/draw/tests/it/transform_box.rs index 0fbf30cc6..e8b32bb82 100644 --- a/crates/draw/tests/it/transform_box.rs +++ b/crates/draw/tests/it/transform_box.rs @@ -1070,20 +1070,28 @@ fn a_jittery_double_click_inside_applies_with_no_move_committed() { assert_eq!(h.host.borrow().applied, 1, "the double click applies"); } -/// A secondary click on the session's box opens the mode menu (its rows are on the page); with the menu closed again, a -/// secondary click away from the box opens none. +/// A secondary click on the session's box opens the mode menu (its rows are on the page) and is the box's alone: the +/// tool host under it asks for no menu of its own. With the menu closed again, a secondary click away from the box +/// opens none. #[trial] fn a_secondary_click_on_the_box_opens_the_mode_menu() { + use craft_draw::ui::transform::TransformTool; + use craft_ui::canvas::{ToolHost, tool_pass}; let session = TransformSession::<()>::new(RECT); let settings = TransformSettings::default(); let view = Rc::new(RefCell::new(CanvasView::new(egui::Rect::NOTHING, Point::ZERO, 1.0))); - let shown_view = Rc::clone(&view); + let host_asked = Rc::new(Cell::new(false)); + let (shown_view, asked) = (Rc::clone(&view), Rc::clone(&host_asked)); let mut fixture = Fixture::new(move |ui| { let room = ui.available_rect_before_wrap(); let at = CanvasView::new(room, Point::new(f64::from(room.width()) / 2.0, f64::from(room.height()) / 2.0), 1.0); *shown_view.borrow_mut() = at; Canvas::new("Document").view(at).show(ui, |ui, body| { - TransformOverlay::new("Free Transform", &session, &settings).show_at(ui, body.rect); + let shown = TransformOverlay::new("Free Transform", &session, &settings).show_at(ui, body.rect); + if let Some(pass) = tool_pass(&body.env) { + let mut tool = TransformTool::new(&session, shown.snapped.clone()); + asked.set(asked.get() || ToolHost::new().run(ui, &pass, &mut tool).context.is_some()); + } }); }); fixture.settle(); @@ -1098,8 +1106,10 @@ fn a_secondary_click_on_the_box_opens_the_mode_menu() { right_click(&mut fixture, screen(Point::new(1000.0, 1000.0))); assert!(fixture.by_label("Distort").is_none(), "a secondary click away from the box opens no mode menu"); + host_asked.set(false); right_click(&mut fixture, screen(Point::new(200.0, 150.0))); assert!(fixture.by_label("Distort").is_some(), "a secondary click on the box opens the mode menu"); + assert!(!host_asked.get(), "the tool host under the box asks for no menu"); } /// A drag from inside snaps the moved box's edges, not the pointer: the right edge lands on the guide at 310 while the diff --git a/crates/font-manager/src/picker.rs b/crates/font-manager/src/picker.rs index 887faf69c..e25ff1766 100644 --- a/crates/font-manager/src/picker.rs +++ b/crates/font-manager/src/picker.rs @@ -19,7 +19,7 @@ use craft_host::Section; use craft_theme::variant::Tone; use craft_ui::buttons::{ControlPlace, IconButton}; use craft_ui::contract::{ - Access, Bind, Common, Component, Cx, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx, + Bind, Common, Component, Cx, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, Props as _, Remember as _, Role, Styled as _, WordSetCx as _, step_stop, }; use craft_ui::controls::disclosure::{DisclosureGlyph, DropdownArrow}; @@ -59,8 +59,6 @@ craft_ui::words! { /// The name of the preview banner, with `{family}` for the family it shows. preview_of: template "fontPicker.previewOf" = "Font preview: {family}"; no_match: "fontPicker.noMatch" = "No fonts match"; - /// The family field's label when the selection has several families. - mixed: "fontPicker.mixed" = "Mixed"; /// The name of a row's star, with `{row}` for the row's label. favorite: template "fontPicker.favorite" = "Favorite {row}"; list: "fontPicker.list" = "Fonts"; @@ -934,10 +932,8 @@ impl Component for FontPicker<'_> { } let mut options = TextOptions::new(); options.select_on_focus = true; + // A selection of several families shows an empty field, as the reference applications do. options.mixed = cx.value().is_none(); - if options.mixed { - options.placeholder = Some(cx.words::().mixed.clone()); - } if !self.catalog.is_ready() { // The first scan runs on a background thread; the field asks again until it ends. self.catalog.scan_in_background(); @@ -954,12 +950,6 @@ impl Component for FontPicker<'_> { Some(self.family.reborrow()) } - fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) { - if cx.value().is_none() && cx.text(&text_key()).is_none_or(|text| text.draft.as_deref().is_none_or(str::is_empty)) { - access.value(cx.words::().mixed.as_str()); - } - } - /// A changed draft filters the list: it opens on the matches, and closes when the draft ended (committed, /// cancelled or replaced by a pick). A preview that the list closed on without a pick is cancelled. While the /// list is closed, the arrows and the wheel step through the host rows and the families. diff --git a/crates/font-manager/tests/it/picker.rs b/crates/font-manager/tests/it/picker.rs index 5b1f60c26..bf185a32c 100644 --- a/crates/font-manager/tests/it/picker.rs +++ b/crates/font-manager/tests/it/picker.rs @@ -122,8 +122,10 @@ fn present(fx: &Fixture, text: &str) -> bool { fx.by_label(text).is_some() || fx.texts().iter().any(|painted| painted.text == text) } +/// A selection of several families leaves the family field empty, on screen and to assistive technology, as the +/// reference applications do: no family name and no word stands in for it. #[trial] -fn mixed_family_is_named_until_a_font_is_chosen() { +fn a_mixed_family_shows_an_empty_field() { let catalog = catalog_of(&[INTER_REGULAR]); let mut family = craft_behavior::Mixed::::Mixed; let mut fx = Fixture::new(move |ui| { @@ -132,8 +134,14 @@ fn mixed_family_is_named_until_a_font_is_chosen() { fx.in_room(Room::Window); fx.settle(); let field = fx.by_role(craft_ui::runtime::access::Role::COMBO_BOX).into_iter().next().expect("the family field"); - let label = fx.tree().value_of(field.node).filter(|value| !value.is_empty()).expect("the mixed family has an accessible label"); - assert!(present(&fx, label), "the accessible mixed label is also visible"); + assert!(fx.tree().value_of(field.node).is_none_or(str::is_empty), "the mixed family has no accessible value"); + let words: Vec = fx + .texts() + .iter() + .filter(|painted| field.rect.contains_rect(painted.rect) && painted.text.chars().any(char::is_alphabetic)) + .map(|painted| painted.text.clone()) + .collect(); + assert!(words.is_empty(), "the field paints no text: {words:?}"); } #[trial] diff --git a/crates/ui-canvas/src/canvas/rulers/mod.rs b/crates/ui-canvas/src/canvas/rulers/mod.rs index bed29b8ea..96acf884f 100644 --- a/crates/ui-canvas/src/canvas/rulers/mod.rs +++ b/crates/ui-canvas/src/canvas/rulers/mod.rs @@ -402,7 +402,7 @@ impl Component for Rulers<'_> { for (part, strip) in [(RulerPart::Horizontal, top), (RulerPart::Vertical, left)] { let declared = cx.part(part.part(), strip).priority(handle).pointer_only("the New Guide... command places a guide by number"); if self.interactive { - let declared = declared.sense(Sense::DRAG | Sense::CLICK); + let declared = declared.sense(Sense::DRAG | Sense::CLICK | Sense::CONTEXT_CLICK); if let Some(space) = space { declared.cursor(resize_cursor(&space.view, motion_across(part.guide_along()))); } @@ -410,7 +410,11 @@ impl Component for Rulers<'_> { } let declared = cx.part(CORNER, corner).priority(handle); if self.interactive { - let sense = if self.origin_locked { Sense::CLICK | Sense::CONTEXT_CLICK } else { Sense::DRAG | Sense::CLICK | Sense::TAKE_FOCUS }; + let sense = if self.origin_locked { + Sense::CLICK | Sense::CONTEXT_CLICK + } else { + Sense::DRAG | Sense::CLICK | Sense::CONTEXT_CLICK | Sense::TAKE_FOCUS + }; let declared = declared.sense(sense); if self.origin_locked { declared.pointer_only("the zero point is locked"); diff --git a/crates/ui-canvas/src/canvas_controls/guides/mod.rs b/crates/ui-canvas/src/canvas_controls/guides/mod.rs index c84c921be..f66ebb358 100644 --- a/crates/ui-canvas/src/canvas_controls/guides/mod.rs +++ b/crates/ui-canvas/src/canvas_controls/guides/mod.rs @@ -499,7 +499,7 @@ impl Component for Guides<'_> { let Some([a, b]) = place::segment(&space.view, guide.along, guide.position, guide.span, rect) else { continue }; let part = cx .part(guide.key.part(GUIDE), HitShape::segment(a, b)) - .sense(Sense::DRAG | Sense::CLICK | Sense::TAKE_FOCUS) + .sense(Sense::DRAG | Sense::CLICK | Sense::CONTEXT_CLICK | Sense::TAKE_FOCUS) .priority(HitPriority::new(HitLevel::Edge, 0)) .cursor(resize_cursor(&space.view, motion_across(guide.along))) .focusable(); diff --git a/crates/ui-canvas/tests/it/canvas/rulers.rs b/crates/ui-canvas/tests/it/canvas/rulers.rs index 7176fc6ff..16aa58288 100644 --- a/crates/ui-canvas/tests/it/canvas/rulers.rs +++ b/crates/ui-canvas/tests/it/canvas/rulers.rs @@ -265,3 +265,43 @@ fn a_corner_drag_the_host_cancelled_lands_nothing_at_its_release() { fixture.settle(); assert_eq!(*zero.borrow(), host, "the release after the host's change leaves the zero point where the host put it"); } + +/// A right-click on a ruler strip or on the corner is the rulers': they report the part, for their units menu, and +/// the tool host under them asks for no menu of its own. +#[trial] +fn a_right_click_on_a_ruler_is_the_rulers_not_the_tools() { + use craft_ui::canvas::{RulerPart, ToolHost, tool_pass}; + let zero = Rc::new(RefCell::new(Point::ZERO)); + let asked: Rc, bool)>> = Rc::new(RefCell::new((None, false))); + let (shown_zero, seen) = (Rc::clone(&zero), Rc::clone(&asked)); + let room = Rc::new(Cell::new(Rect::NOTHING)); + let shown_room = Rc::clone(&room); + let tool = RefCell::new(Overpaint); + let mut fixture = Fixture::new(move |ui| { + let at = ui.available_rect_before_wrap(); + shown_room.set(at); + let view = CanvasView::new(at, Point::new(f64::from(at.center().x), f64::from(at.center().y)), 1.0); + let mut zero = shown_zero.borrow_mut(); + let mut host_asked = false; + let canvas = Canvas::new("Document").view(view).with_rulers(Some(Rulers::new("Rulers", Bind::bound(&mut *zero)))).show(ui, |ui, body| { + if let Some(pass) = tool_pass(&body.env) { + host_asked = ToolHost::new().run(ui, &pass, &mut *tool.borrow_mut()).context.is_some(); + } + }); + let mut seen = seen.borrow_mut(); + seen.0 = seen.0.or(canvas.output.rulers.as_ref().and_then(|rulers| rulers.context)); + seen.1 |= host_asked; + }); + fixture.room(Vec2::new(500.0, 400.0)).settle(); + let mut right_click = |at: Pos2| { + *asked.borrow_mut() = (None, false); + fixture.frame(vec![craft_ui::testing::pointer::moved(at)]); + fixture.frame(vec![craft_ui::testing::pointer::secondary(at, true)]); + fixture.frame(vec![craft_ui::testing::pointer::secondary(at, false)]); + fixture.settle(); + *asked.borrow() + }; + let canvas = room.get(); + assert_eq!(right_click(egui::pos2(canvas.center().x, canvas.min.y + 4.0)), (Some(RulerPart::Horizontal), false), "the top strip"); + assert_eq!(right_click(canvas.min + Vec2::splat(4.0)), (Some(RulerPart::Corner), false), "the corner, its zero point unlocked"); +} diff --git a/crates/ui-canvas/tests/it/canvas_controls/guides.rs b/crates/ui-canvas/tests/it/canvas_controls/guides.rs index 3f32ad108..9336a261b 100644 --- a/crates/ui-canvas/tests/it/canvas_controls/guides.rs +++ b/crates/ui-canvas/tests/it/canvas_controls/guides.rs @@ -6,7 +6,7 @@ use craft_behavior::{Axis, CancelReason, CanvasView}; use craft_ui::canvas::{CanvasTool, Guide, GuideKey, Snap, ToolAction, ToolContext, ToolPath, ToolPointer}; use craft_ui::canvas_controls::Guides; use craft_ui::canvas_controls::reading::{GuideReading, running}; -use craft_ui::contract::{Bind, BodyCx, Show as _}; +use craft_ui::contract::{Bind, BodyCx, Props as _, Show as _, ShowContainer as _}; use craft_ui::primitives::Draw; use craft_ui::testing::{ToolFixture, pointer, tool_fixture, trial}; use egui::{Id, Key, Modifiers, Pos2, Rect, Vec2, pos2, vec2}; @@ -284,3 +284,39 @@ fn a_deleted_guide_hands_focus_on_without_selecting_the_next_guide() { assert!(at(&guides, Axis::Y, 200.0).is_none(), "Delete removes it: {:?}", guides.borrow()); assert_eq!(*selected.borrow(), None, "and selects no other guide"); } + +// A right-click on an unlocked guide is the guide's: the guides report its menu request and the tool host under them +// reports none. Off the guide the right-click reaches the host, which asks for its own menu. +#[trial] +fn a_right_click_on_a_guide_asks_for_the_guide_menu_not_the_tools() { + use craft_ui::canvas::{Canvas, ToolHost, tool_pass}; + use craft_ui::testing::Fixture; + use craft_ui::testing::tool_fixture::DOCUMENT; + let guides: Shared> = Rc::new(RefCell::new(vec![guide(1, Axis::Y, 200.0)])); + let asked: Shared<(Option, bool)> = Rc::new(RefCell::new((None, false))); + let (shown, seen) = (Rc::clone(&guides), Rc::clone(&asked)); + let tool = RefCell::new(Recorder::default()); + let mut fixture = Fixture::new(move |ui| { + let room = ui.available_rect_before_wrap(); + let canvas = Canvas::new("Document").id(tool_fixture::canvas_id("Document")).document(DOCUMENT).view(view_at(1.0)(room)); + let _ = canvas.show(ui, |ui, body| { + let out = Guides::new("Guides", canvas_of(body), Bind::bound(&mut *shown.borrow_mut())).interactive(true).show_at(ui, body.rect); + let mut seen = seen.borrow_mut(); + seen.0 = seen.0.or(out.context.map(|(key, _)| key)); + if let Some(pass) = tool_pass(&body.env) { + seen.1 |= ToolHost::new().run(ui, &pass, &mut *tool.borrow_mut()).context.is_some(); + } + }); + }); + fixture.settle(); + let mut right_click = |at: Pos2| { + *asked.borrow_mut() = (None, false); + fixture.frame(vec![pointer::moved(at)]); + fixture.frame(vec![pointer::secondary(at, true)]); + fixture.frame(vec![pointer::secondary(at, false)]); + fixture.settle(); + *asked.borrow() + }; + assert_eq!(right_click(pos2(200.0, 300.0)), (Some(GuideKey::new(1)), false), "on the guide: its menu, not the tool's"); + assert_eq!(right_click(pos2(400.0, 300.0)), (None, true), "off the guide: the tool's menu"); +} diff --git a/crates/ui-widgets/src/text/number.rs b/crates/ui-widgets/src/text/number.rs index 464009b74..51bdb02b3 100644 --- a/crates/ui-widgets/src/text/number.rs +++ b/crates/ui-widgets/src/text/number.rs @@ -194,7 +194,8 @@ pub struct NumberField<'a, V: NumberValue + 'static = Option> { /// A typed value goes to the nearest multiple of the step when it commits. #[prop] snap_typed: bool, - /// The decimals a committed value is rounded to; the display keeps the codec's. + /// The decimals a committed value is rounded to; the display keeps the codec's, except that a percent field with no + /// decimals of its own shows none when this is 0 ("10%"). #[prop] commit_decimals: Option, /// An empty field means automatic: it shows the "Auto" word as its placeholder. @@ -442,11 +443,21 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> { value.and_then(NumberValue::number).map(|stored| self.to_shown(stored)) } - /// Whether the field counts percent: it writes its precision's decimals in full, its sign right after the number. + /// Whether the field counts percent: it shows its sign right after the number. fn is_percent(&self) -> bool { self.codec.is_none() && self.unit_kind == Some(UnitKind::Percent) } + /// The decimals a percent field writes in full when the caller sets none of its own: one at the standard precision + /// ("100.0%"), none at the measured precision ("100%") or for a field whose committed values carry none + /// (`commit_decimals(0)`). + fn percent_decimals(&self) -> Option { + (self.is_percent() && self.fixed_decimals.is_none() && self.max_decimals.is_none()).then(|| match self.precision { + NumberPrecision::Standard => self.commit_decimals.unwrap_or(1).min(1), + NumberPrecision::Measured => 0, + }) + } + /// Whether the field uses the dash for a missing or invalid value. fn shows_blank(&self, shown: Option<&V>) -> bool { shown.is_none() || non_finite(shown) || (self.status_zoom && shown.and_then(NumberValue::number).is_none()) @@ -461,19 +472,18 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> { None => units.reader(self.unit_kind), }; let codec = NumberCodec::new(reader, self.decimals()); - if self.fixed_decimals.is_some() || self.is_percent() { codec.fixed() } else { codec } + if self.fixed_decimals.is_some() || self.percent_decimals().is_some() { codec.fixed() } else { codec } }) } - /// The decimals the field shows: its codec's, fixed or maximum precision, else its unit kind's. + /// The decimals the field shows: its codec's, fixed or maximum precision, a percent field's own, else its unit + /// kind's. fn shown_decimals(&self) -> RangeInclusive { + if let Some(percent) = self.percent_decimals() { + return percent..=percent; + } match (&self.codec, self.fixed_decimals, self.max_decimals, self.unit_kind) { (Some(codec), _, _, _) => 0..=codec.decimals(), - // A percentage reads "100.0%": one decimal, written in full; whole at the measured precision. - (None, _, _, Some(UnitKind::Percent)) => match self.precision { - NumberPrecision::Standard => 1..=1, - NumberPrecision::Measured => 0..=0, - }, (None, Some(fixed), _, _) => fixed..=fixed, (None, None, Some(max), _) => 0..=max.min(12), (None, None, None, Some(kind)) => match (self.precision, self.lengths) { diff --git a/crates/ui-widgets/tests/it/text/number.rs b/crates/ui-widgets/tests/it/text/number.rs index d3bce1323..3420c531a 100644 --- a/crates/ui-widgets/tests/it/text/number.rs +++ b/crates/ui-widgets/tests/it/text/number.rs @@ -775,3 +775,25 @@ fn a_percent_field_reads_one_decimal_then_the_sign() { let sign = painted("%").unwrap_or_else(|| panic!("the field shows the sign")); assert!(sign.min.x - number.max.x <= 5.0, "the sign follows the number closely: {number:?} {sign:?}"); } + +/// A percent field whose committed values carry no decimals (`commit_decimals(0)`, a paint bar's Opacity) shows none, +/// "10%"; one that sets no decimals of its own keeps the one-decimal look, "10.0%". +#[trial] +fn a_percent_field_shows_the_decimals_its_caller_commits() { + let shown = |commit: Option| { + let mut value = Some(10.0f64); + let mut fixture = craft_ui::testing::Fixture::new(move |ui| { + let field = NumberField::new("Opacity", Bind::bound(&mut value)).unit_kind(UnitKind::Percent).range(0.0..=100.0); + let _ = match commit { + Some(decimals) => field.commit_decimals(decimals).show(ui), + None => field.show(ui), + }; + }); + fixture.settle(); + fixture.texts().iter().map(|run| run.text.clone()).collect::>() + }; + let whole = shown(Some(0)); + assert!(whole.iter().any(|text| text == "10") && !whole.iter().any(|text| text == "10.0"), "commit_decimals(0) shows 10%: {whole:?}"); + let default = shown(None); + assert!(default.iter().any(|text| text == "10.0"), "with no decimals set the field shows 10.0%: {default:?}"); +}