diff --git a/crates/behavior/src/codec.rs b/crates/behavior/src/codec.rs index 529f8bbf5..045d172c4 100644 --- a/crates/behavior/src/codec.rs +++ b/crates/behavior/src/codec.rs @@ -158,6 +158,7 @@ pub struct NumberCodec { custom: Option, /// Typing rules of a zoom field ([`NumberCodec::zoom_typing`]). zoom: bool, + signed_zoom: bool, } impl fmt::Debug for NumberCodec { @@ -167,6 +168,7 @@ impl fmt::Debug for NumberCodec { .field("decimals", &self.decimals) .field("fixed", &self.fixed) .field("zoom", &self.zoom) + .field("signed_zoom", &self.signed_zoom) .field("custom", &self.custom.is_some()) .finish() } @@ -179,7 +181,8 @@ impl PartialEq for NumberCodec { (Some(a), Some(b)) => Arc::ptr_eq(a, b), _ => false, }; - self.reader == other.reader && self.decimals == other.decimals && self.fixed == other.fixed && self.zoom == other.zoom && same_custom + self.reader == other.reader && self.decimals == other.decimals && self.fixed == other.fixed && self.zoom == other.zoom + && self.signed_zoom == other.signed_zoom && same_custom } } @@ -213,7 +216,7 @@ const NUMBER_SAMPLE: &str = "0000.00"; impl NumberCodec { /// A codec reading with `reader` and writing at most `decimals` decimal places. pub fn new(reader: Reader, decimals: usize) -> Self { - NumberCodec { reader, decimals, fixed: false, custom: None, zoom: false } + NumberCodec { reader, decimals, fixed: false, custom: None, zoom: false, signed_zoom: false } } /// The same codec writing every decimal place, trailing zeros included ("1.00"), as a field of a quantity shown @@ -230,8 +233,14 @@ impl NumberCodec { self } + /// Allow a leading minus in zoom input so the field can reject negative values instead of discarding the sign. + pub fn signed_zoom(mut self) -> Self { + self.signed_zoom = true; + self + } + /// The zoom reading of trimmed, non-empty `text`: the text before a second decimal separator, then `a/b` as a - /// percentage or a plain number. The filter keeps `+`, `-` and `*` out, so the reader's expressions never run. + /// percentage or a plain number. The filter keeps `+` and `*` out, so the reader's expressions never run. fn read_zoom(&self, text: &str) -> Result<(f64, ParseNote), NotAValue> { let separator = self.reader.decimal_separator(); let second = text.char_indices().filter(|&(_, c)| c == separator).nth(1).map(|(at, _)| at); @@ -239,6 +248,9 @@ impl NumberCodec { Some(at) => (&text[..at], true), None => (text, false), }; + if kept.strip_prefix('-').unwrap_or(kept).contains('-') { + return Err(NotAValue); + } let number = match kept.split_once('/') { Some((part, whole)) => { let part = self.reader.read(part, None)?; @@ -336,9 +348,9 @@ impl Codec for NumberCodec { } } - /// Zoom typing takes ASCII digits, `/` and the decimal separator; every other number field takes every character. + /// Zoom typing takes ASCII digits, `/` and the decimal separator, with an optional minus; other fields take every character. fn filter(&self, c: char) -> bool { - !self.zoom || c.is_ascii_digit() || c == '/' || c == self.reader.decimal_separator() + !self.zoom || c.is_ascii_digit() || (self.signed_zoom && c == '-') || c == '/' || c == self.reader.decimal_separator() } fn sample(&self, _current: &Option) -> Cow<'_, str> { diff --git a/crates/behavior/src/geometry/quad.rs b/crates/behavior/src/geometry/quad.rs index 4c70ff25d..8603bcd0b 100644 --- a/crates/behavior/src/geometry/quad.rs +++ b/crates/behavior/src/geometry/quad.rs @@ -97,6 +97,8 @@ pub enum ScaleRule { /// PhotoCraft's Use Legacy Free Transform, DesignCraft and VectorCraft: corners stretch freely /// and ⇧ keeps the proportions; edges stretch their one axis. Free, + /// Corners keep their proportions using the larger relative axis change; ⇧ frees them. + LargerAxis, /// A shape or path bounds box: a corner scales by the projection of the drag on the anchor-corner diagonal, /// keeping the proportions; an edge stretches its one axis. Shape, @@ -534,16 +536,18 @@ fn apply_drag(g: &Gesture, p: Point, mods: Mods, rules: &BoxRules) -> BoxState { } BoxState { quad, pivot: carry_pivot(q0, quad, c) } } - BoxPart::Corner(_) | BoxPart::Edge(_) => scale_drag(g, p, mods, rules.min_side).unwrap_or(BoxState { quad: q0, pivot: c }), + BoxPart::Corner(_) | BoxPart::Edge(_) => { + scale_drag(g, p, mods, rules.min_side, rules.scale == ScaleRule::LargerAxis).unwrap_or(BoxState { quad: q0, pivot: c }) + } } } /// A plain corner or edge drag: scaling in the box's own frame (the unit square through the /// homography), so rotated and skewed boxes scale along their axes. A proportional corner follows -/// the pointer's projection on the line from the anchor to the corner, so a distorted box scales -/// along its own diagonal; past the anchor the factor turns negative and the box flips. Each -/// scaled side keeps at least `min_side` ([`scale_floor`]). `None` for a collapsed box. -fn scale_drag(g: &Gesture, p: Point, mods: Mods, min_side: f64) -> Option { +/// the pointer's projection on the diagonal, or the larger relative axis change when selected. Past the anchor +/// the factor turns negative and the box flips. Each scaled side keeps at least `min_side` +/// ([`scale_floor`]). `None` for a collapsed box. +fn scale_drag(g: &Gesture, p: Point, mods: Mods, min_side: f64, larger_axis: bool) -> Option { let h = Homography::unit_to_quad(g.quad0)?; let inv = h.inverse()?; let Point { x: u, y: v } = inv.apply(p); @@ -586,16 +590,14 @@ fn scale_drag(g: &Gesture, p: Point, mods: Mods, min_side: f64) -> Option 1e-12 { + let k = if larger_axis { + if (ku - 1.0).abs() > (kv - 1.0).abs() { ku } else { kv } + } else if len2 > 1e-12 { let q = inv.apply(a + d * ((p - a).dot(d) / len2)); if (hu - au).abs() >= (hv - av).abs() { (q.x - au) / (hu - au) } else { (q.y - av) / (hv - av) } } else { diff --git a/crates/behavior/tests/geometry/quad.rs b/crates/behavior/tests/geometry/quad.rs index 2d8f74416..fc93e186c 100644 --- a/crates/behavior/tests/geometry/quad.rs +++ b/crates/behavior/tests/geometry/quad.rs @@ -31,6 +31,15 @@ fn turns(q: &[Point; 4]) -> [f64; 4] { std::array::from_fn(|k| (q[(k + 1) % 4] - q[k]).cross(q[(k + 2) % 4] - q[(k + 1) % 4])) } +#[test] +fn proportional_corner_uses_the_larger_relative_drag_even_when_shrinking() { + let rules = BoxRules::default().with_scale(ScaleRule::LargerAxis); + let wider = dragged(p(100.0, 50.0), p(200.0, 60.0), Mods::NONE, &rules); + assert!(corners_are(&wider, 0.0, 0.0, 200.0, 100.0)); + let smaller = dragged(p(100.0, 50.0), p(75.0, 50.0), Mods::NONE, &rules); + assert!(corners_are(&smaller, 0.0, 0.0, 75.0, 37.5)); +} + #[test] fn a_proportional_corner_follows_the_diagonal_and_flips_past_the_anchor() { let rules = BoxRules::default(); diff --git a/crates/draw/src/ui/transform/transform_box/stories.rs b/crates/draw/src/ui/transform/transform_box/stories.rs index e31819bb7..c39ea36fe 100644 --- a/crates/draw/src/ui/transform/transform_box/stories.rs +++ b/crates/draw/src/ui/transform/transform_box/stories.rs @@ -56,6 +56,12 @@ fn free_transform(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { on_canvas(ui, data, |state| free_box(state).reference_point(true)) } +/// Proportional corners follow the axis with the larger relative change. +#[story(TransformBox<'static>, covers = [Default], drive = Drive::Drag(Grip::part(BOX.at(BoxPart::Corner(2).index())).toward(vec2(1.0, 0.5))))] +fn larger_axis_scale(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + on_canvas(ui, data, |state| free_box(state).rules(BoxRules::default().with_scale(ScaleRule::LargerAxis))) +} + #[story(TransformBox<'static>, covers = [Default])] fn move_tool_controls(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { on_canvas(ui, data, |state| free_box(state).rotate_zone(RotateZone::Band).inside_moves(false).reference_point(false)) diff --git a/crates/pages/src/ui/fixtures.rs b/crates/pages/src/ui/fixtures.rs index a5dd1d8de..d8864b24d 100644 --- a/crates/pages/src/ui/fixtures.rs +++ b/crates/pages/src/ui/fixtures.rs @@ -76,6 +76,7 @@ pub fn demo_placed(count: usize, origin: Pos2) -> Vec { scale: 1.0, band: (0.0, height), picture: TextureState::Missing, + picture_revision: None, } }) .collect() diff --git a/crates/pages/src/ui/grid/stories.rs b/crates/pages/src/ui/grid/stories.rs index 82644d945..4b9d58e9e 100644 --- a/crates/pages/src/ui/grid/stories.rs +++ b/crates/pages/src/ui/grid/stories.rs @@ -23,6 +23,7 @@ fn margins_and_columns_with_a_baseline_grid(ui: &mut Ui, _: &mut StoryData) -> S scale: SCALE, band: (0.0, page.height() as f32 * SCALE as f32), picture: TextureState::Missing, + picture_revision: None, }]; let grids = [PageGrid { index: 0, diff --git a/crates/pages/src/ui/mod.rs b/crates/pages/src/ui/mod.rs index f04f4bbd7..a24bddfb2 100644 --- a/crates/pages/src/ui/mod.rs +++ b/crates/pages/src/ui/mod.rs @@ -58,4 +58,4 @@ pub use thumbnails::{ ORGANIZE_ZOOM, PageThumbnails, PageThumbnailsOutput, THUMBNAIL_ZOOM, ThumbnailArrangement, ThumbnailEvent, ThumbnailMarks, ThumbnailSection, ThumbnailWords, moved_page, }; -pub use view::{GoTo, PageBody, PageSource, PageView, PageViewOutput, PageViewState, PageViewWords, PlacedPage}; +pub use view::{GoTo, PageBody, PageRevision, PageSource, PageView, PageViewOutput, PageViewState, PageViewWords, PlacedPage}; diff --git a/crates/pages/src/ui/view.rs b/crates/pages/src/ui/view.rs index e9765ecf7..2c218c6fd 100644 --- a/crates/pages/src/ui/view.rs +++ b/crates/pages/src/ui/view.rs @@ -41,6 +41,15 @@ use std::cell::RefCell; use std::ops::Range; use std::sync::Arc; +/// The document and page revisions represented by a page picture. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct PageRevision { + /// The revision of the document containing the page. + pub document: u64, + /// The revision of the individual page. + pub page: u64, +} + /// The document's pages as a page view, thumbnails and previews read them. The app implements it over its document; /// the view never owns pages. /// @@ -55,6 +64,12 @@ pub trait PageSource: ThumbSource { /// Page `page`'s size in points as shown (its rotation applied). fn page_size(&self, page: usize) -> Size; + /// The document and page revision of `page`, when the source tracks them. The source's texture revision must + /// change whenever this revision changes, so a ready picture corresponds to this stamp. + fn page_revision(&self, _page: usize) -> Option { + None + } + /// The page's label ("iv", "A-3"; PDF page labels, section numbering): what the page box, thumbnails and the /// accessibility tree call it. 1-based number by default. fn page_label(&self, page: usize) -> String { @@ -233,13 +248,15 @@ pub struct PlacedPage { pub band: (f32, f32), /// What the page's picture shows this pass; `Missing` during the geometry-only pre-draw callback. pub picture: TextureState, + /// The source's document and page revision when `picture` is ready; `None` for a stand-in or an unknown stamp. + pub picture_revision: Option, } impl PlacedPage { /// Page `page` at `rect` on screen, `scale` screen points to a page point, with `band` the visible part of its height in /// screen points and `picture` what its picture shows. pub fn new(page: usize, rect: Rect, scale: f64, band: (f32, f32), picture: TextureState) -> Self { - PlacedPage { page, rect, scale, band, picture } + PlacedPage { page, rect, scale, band, picture, picture_revision: None } } /// Page point (origin top-left, y down) to screen. @@ -747,7 +764,11 @@ fn run_pass(ui: &mut Ui, cx: &mut BodyCx<'_>, held: &mut Held<'_, PageViewState> .map(|&page| { let rect = to_screen(&drawn.layout.rects[page]); let band = (drawn.layout.bands[page].0 as f32 * ratio as f32, drawn.layout.bands[page].1 as f32 * ratio as f32); - PlacedPage::new(page, rect, drawn.scale * ratio, band, ask(page, rect.width().max(rect.height()), Priority::VISIBLE)) + let picture = ask(page, rect.width().max(rect.height()), Priority::VISIBLE); + let picture_revision = matches!(picture, TextureState::Ready(_)).then(|| source.page_revision(page)).flatten(); + let mut placed = PlacedPage::new(page, rect, drawn.scale * ratio, band, picture); + placed.picture_revision = picture_revision; + placed }) .collect(); let near = near_pages(&drawn, state.continuous, &visible, count, &build.layout_options(&state), travel); diff --git a/crates/pages/tests/it/views.rs b/crates/pages/tests/it/views.rs index 0888c0609..3cb615498 100644 --- a/crates/pages/tests/it/views.rs +++ b/crates/pages/tests/it/views.rs @@ -4,7 +4,7 @@ use craft_behavior::{GESTURE_GAP, kurbo}; use craft_pages::layout::{Fit, LayoutOptions, PageDisplay}; use craft_pages::ui::fixtures::{DemoPages, PAPER}; -use craft_pages::ui::{GoTo, PageBody, PagePreview, PageSource, PageView, PageViewState, PlacedPage, ReadingState, ReadingView}; +use craft_pages::ui::{GoTo, PageBody, PagePreview, PageRevision, PageSource, PageView, PageViewState, PlacedPage, ReadingState, ReadingView}; use craft_ui::canvas::{CanvasTool, HandTool, NavigationOptions, ToolAction, ToolContext, ToolHost, ToolKey, ToolPath, ToolPointer}; use craft_ui::contract::{Bind, Role, Show as _}; use craft_ui::primitives::textures::{Revision, TextureState, ThumbRender, ThumbRequest, ThumbSource}; @@ -24,6 +24,53 @@ fn state_with(change: impl FnOnce(&mut PageViewState)) -> PageViewState { type LayoutRig = (Fixture, Rc>, Rc>); +struct RevisionPages { + pictures: DemoPages, + revision: Rc>, +} + +impl ThumbSource for RevisionPages { + fn revision(&self, key: &usize, request: &ThumbRequest) -> Revision { + Revision::of(&(self.pictures.revision(key, request), self.revision.get())) + } + + fn render(&self, key: &usize, request: &ThumbRequest) -> ThumbRender { + self.pictures.render(key, request) + } +} + +impl PageSource for RevisionPages { + fn page_count(&self) -> usize { + self.pictures.page_count() + } + + fn page_size(&self, page: usize) -> kurbo::Size { + self.pictures.page_size(page) + } + + fn page_revision(&self, _: usize) -> Option { + Some(PageRevision { document: 0, page: self.revision.get() }) + } +} + +#[trial] +fn placed_page_reports_only_the_revision_of_a_ready_picture() { + let revision = Rc::new(Cell::new(1)); + let source = RevisionPages { pictures: DemoPages::new(1), revision: revision.clone() }; + let Rig { mut fixture, out, .. } = rig_over(source, PageViewState::default(), NavigationOptions::default(), false); + fixture.settle(); + assert_eq!(out.borrow().pages[0].picture_revision, Some(PageRevision { document: 0, page: 1 })); + revision.set(2); + fixture.idle(1); + let pages = out.borrow(); + let page = &pages.pages[0]; + if !matches!(page.picture, TextureState::Ready(_)) { + assert_eq!(page.picture_revision, None, "a stale stand-in is not the new revision"); + } else { + assert_eq!(page.picture_revision, Some(PageRevision { document: 0, page: 2 })); + } +} + /// What a trial reads of the last pass. #[derive(Clone, Debug)] struct Out { diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index 130a66532..8ae7c041d 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -908,6 +908,8 @@ fn run_in_host(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option, h let keys = e.keys(); let (holder_widget, text_keys) = text_holder(&ctx, id, &parts, keys, &mut *e.core().memory); let own = own_sense(e, resolved, inert); + // The collection handles a row's click, but its access node must still offer the redirected action. + let report_sense = own; // An item never senses the whole row for a press: the collection's root takes the click and the focus (17.2). It // does sense the pointer over it, so `PartsCx::hovered` and the state step read the row's hover from the same // arena outcome whether the item stands alone or in a collection. @@ -1163,7 +1165,7 @@ fn run_in_host(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option, h &steps::ReportIn { node, decls: &parts.decls, - sense: own, + sense: own | (report_sense & Sense::CLICK), live: e.live(), scrolls: e.scrolls(), expanded: e.expanded(), diff --git a/crates/ui-contract/src/runtime/drag.rs b/crates/ui-contract/src/runtime/drag.rs index ed48ba32c..33e7a2acd 100644 --- a/crates/ui-contract/src/runtime/drag.rs +++ b/crates/ui-contract/src/runtime/drag.rs @@ -191,6 +191,8 @@ struct Session { os: bool, /// The root frame in which the OS dropped the files. dropped: Option, + /// A file drop has arrived but no pointer position is available yet. + waiting_for_pointer: bool, /// The root frame the session started in, the only one in which [`amend`] changes its payload. began: u64, } @@ -230,6 +232,7 @@ struct Registration { pub(crate) struct Targets { this: Vec, winner: Option<(Id, u32)>, + winner_window: bool, } fn board(ctx: &Context, f: impl FnOnce(&mut Board) -> R) -> R { @@ -263,6 +266,7 @@ pub fn start(ctx: &Context, source: Id, payload: Arc, als taken: false, os: false, dropped: None, + waiting_for_pointer: false, began, }); board.ended = None; @@ -366,21 +370,31 @@ fn os_files(ctx: &Context) { let frame = pass::root_frame_nr(ctx); let viewport = pass::current_viewport(ctx); let hovering = !seen.hovered.is_empty(); + let host = WindowHost::of(ctx); + let positioned = if host.desktop_pointer().is_some() { host.pointer_in(viewport).is_some() } else { pointer::frame(ctx).pos.is_some() }; + // A window target does not need a position and can already have won while files hovered. + let window_winner = PerViewport::::with(ctx, viewport, |targets| targets.winner_window); + let mut repaint = false; board(ctx, |board| match &mut board.session { - None if hovering => { + None if hovering || !seen.dropped.is_empty() => { + let has_drop = !seen.dropped.is_empty(); + if has_drop { + repaint = true; + } board.session = Some(Session { source: Id::NULL.with("craft_ui::os_files"), moving: Moving::default(), viewport, button: PointerButton::Primary, - payload: Arc::new(OsFiles { files: seen.hovered }), + payload: Arc::new(OsFiles { files: if has_drop { seen.dropped } else { seen.hovered } }), also: None, preview: DragPreview::None, mark: None, released: None, taken: false, os: true, - dropped: None, + dropped: (has_drop && positioned).then_some(frame.saturating_add(1)), + waiting_for_pointer: has_drop && !positioned, began: frame, }); board.ended = None; @@ -391,8 +405,17 @@ fn os_files(ctx: &Context) { let hovered = session.payload.downcast_ref::(); let files = seen.dropped.into_iter().map(|file| with_hovered_type(file, hovered)).collect(); session.payload = Arc::new(OsFiles { files }); - session.dropped = Some(frame); - } else if !hovering && !seen.reading && session.dropped != Some(frame) { + if positioned || window_winner { + session.dropped = Some(frame); + } else { + session.waiting_for_pointer = true; + } + } else if session.waiting_for_pointer && (positioned || window_winner) { + // Targets register this pass and take the drop in the next, after their winner is resolved. + session.waiting_for_pointer = false; + session.dropped = Some(frame.saturating_add(1)); + repaint = true; + } else if !hovering && !seen.reading && !session.waiting_for_pointer && session.dropped.is_none_or(|drop| drop < frame) { board.session = None; } } @@ -400,7 +423,7 @@ fn os_files(ctx: &Context) { }); // The OS sends the window no pointer events while it drags files over it (winit 0.30), so nothing else asks for // the passes that follow the pointer to the target under it. - if hovering { + if hovering || repaint { crate::runtime::egui::repaint::request(ctx); } } @@ -630,6 +653,7 @@ pub(crate) fn end_pass(ctx: &Context) { .filter(|(at, _)| open[*at]) .max_by_key(|(at, registration)| (!registration.window, areas::layer_position(ctx, registration.layer), *at)) .map(|(_, registration)| registration); + targets.winner_window = best.is_some_and(|registration| registration.window); let best = best.map(|registration| ((registration.owner, registration.ordinal), (registration.mark, registration.op))); targets.winner = best.map(|(key, _)| key); targets.this.clear(); diff --git a/crates/ui-contract/tests/it/drag/mod.rs b/crates/ui-contract/tests/it/drag/mod.rs index 8dc2b95f9..140f57cbc 100644 --- a/crates/ui-contract/tests/it/drag/mod.rs +++ b/crates/ui-contract/tests/it/drag/mod.rs @@ -227,6 +227,70 @@ struct FileList<'a> { landed: &'a RefCell, } +#[derive(Component)] +struct RowOnly<'a> { + #[common] + common: Common, + landed: &'a RefCell, +} + +impl Component for RowOnly<'_> { + const ROLE: Role = Role::GROUP; + type Style = PlainStyle; + type Output = Response; + + fn style(_: &StyleCx<'_>, _: RowOnlyStyleKey) -> PlainStyle { + PlainStyle::default() + } + + fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 { + LIST.size() + } + + fn update(&mut self, cx: &mut Cx<'_, Self>) { + if let Some(row) = cx.drop_target(&OnRow) { + self.landed.borrow_mut().rows.push(row); + } + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + +#[trial] +fn file_drop_without_pointer_waits_for_its_target() { + let landed = RefCell::new(Landed::default()); + let mut frames = Frames::new(); + let mut show = |ui: &mut Ui| { + RowOnly { common: Common::new(), landed: &landed }.id_salt("files").show_at(ui, LIST); + }; + frames.idle(2, &mut show); + frames.hover_files(&["a.png"]); + frames.frame(vec![], &mut show); + frames.drop_files(&["a.png"]); + frames.frame(vec![], &mut show); + assert!(landed.borrow().rows.is_empty(), "the position is not known yet"); + frames.frame(vec![moved(LIST.center())], &mut show); + frames.idle(2, &mut show); + assert_eq!(landed.borrow().rows.len(), 1, "the drop reaches the row once its position arrives"); + assert!(landed.borrow().window.is_empty(), "the row takes the drop"); +} + +#[trial] +fn window_file_drop_without_hover_or_pointer_does_not_wait_for_pointer() { + let landed = RefCell::new(Landed::default()); + let mut frames = Frames::new(); + let mut show = |ui: &mut Ui| { + FileList { common: Common::new(), landed: &landed }.id_salt("files").show_at(ui, LIST); + }; + frames.idle(2, &mut show); + frames.drop_files(&["a.png"]); + frames.frame(vec![], &mut show); + frames.idle(3, &mut show); + assert_eq!(landed.borrow().window.len(), 1, "the window receives the drop without a pointer"); +} + impl Component for FileList<'_> { const ROLE: Role = Role::GROUP; type Style = PlainStyle; diff --git a/crates/ui-patterns/tests/it/form_dialogs/preview.rs b/crates/ui-patterns/tests/it/form_dialogs/preview.rs index 06a33107b..093b9cc6d 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/preview.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/preview.rs @@ -40,6 +40,9 @@ fn a_typed_zoom_sets_the_preview_zoom_inside_its_range() { type_zoom(&mut fixture, "5000"); let end = *view.borrow().range.end(); assert!((view.borrow().transform.scale - end).abs() < SAME, "a zoom past the range stops at its end: {:?}", view.borrow().transform); + + type_zoom(&mut fixture, "-50"); + assert!((view.borrow().transform.scale - 0.5).abs() < SAME, "the preview filters the minus sign"); } /// The picture the click trials show. diff --git a/crates/ui-widgets/src/text/number.rs b/crates/ui-widgets/src/text/number.rs index 88eb5ea85..78d3103c7 100644 --- a/crates/ui-widgets/src/text/number.rs +++ b/crates/ui-widgets/src/text/number.rs @@ -137,6 +137,7 @@ pub struct NumberField<'a, V: NumberValue + 'static = Option> { /// How many shown units make one stored unit, read from the env in measure and parts; 1 for a plain field. scale: f64, options: TextOptions, + positive_only: bool, scrub: bool, /// The popup slider's track length, read from the tokens in parts: a drag on its chevron moves the value as far /// as a drag on the slider would. @@ -193,6 +194,7 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> { lengths: None, scale: 1.0, options: TextOptions::default(), + positive_only: false, scrub: false, track: 0.0, picked: None, @@ -215,6 +217,7 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> { pub(super) fn zoom_typing(mut self) -> Self { self.options.tab_rewrites = true; self.options.holds_drafts = true; + self.positive_only = true; self } @@ -309,6 +312,7 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> { snap: self.snap_typed, decimals: self.commit_decimals, mixed, + positive_only: self.positive_only, names, scale: self.scale, value: PhantomData, diff --git a/crates/ui-widgets/src/text/number/rule.rs b/crates/ui-widgets/src/text/number/rule.rs index f468fe7d6..7d8070d27 100644 --- a/crates/ui-widgets/src/text/number/rule.rs +++ b/crates/ui-widgets/src/text/number/rule.rs @@ -109,6 +109,7 @@ pub(super) struct Ruled { pub(super) snap: bool, pub(super) decimals: Option, pub(super) mixed: bool, + pub(super) positive_only: bool, pub(super) names: Vec<(u32, String)>, /// How many shown units make one stored unit (1 for a field that shows what it holds). pub(super) scale: f64, @@ -123,6 +124,7 @@ impl Clone for Ruled { snap: self.snap, decimals: self.decimals, mixed: self.mixed, + positive_only: self.positive_only, names: self.names.clone(), scale: self.scale, value: PhantomData, @@ -178,6 +180,9 @@ impl Codec for Ruled { let (read, mut note) = self.inner.parse_tagged(text, &self.shown(start))?; match read { Some(number) => { + if self.positive_only && number <= 0.0 { + return Err(NotAValue); + } note.held = (number < self.rule.low || number > self.rule.high).then_some(number); Ok((V::of_number(self.held(number) / self.scale), note)) } diff --git a/crates/ui-widgets/src/text/zoom_field.rs b/crates/ui-widgets/src/text/zoom_field.rs index 4efd2bb4c..66cdb7027 100644 --- a/crates/ui-widgets/src/text/zoom_field.rs +++ b/crates/ui-widgets/src/text/zoom_field.rs @@ -19,8 +19,8 @@ const MESSAGE_DECIMALS: usize = 2; /// with the zoom codec and the zoom ladder's range. With no view it shows a disabled empty field. An edit writes the zoom about the view's centre; an empty /// commit keeps the view. /// -/// - Typing takes digits, `/` and the decimal separator: `a/b` is the zoom `a ÷ b × 100` %, and a second separator -/// applies the number before it and reports [`InvalidZoom`]. +/// - Typing takes digits, `-`, `/` and the decimal separator: `a/b` is the zoom `a ÷ b × 100` %. Non-positive +/// entries are rejected; a second separator applies the number before it and reports [`InvalidZoom`]. /// - Tab writes the typed number in the field's own form and selects it; focus stays and nothing applies. /// - A press on a part declared `holds_drafts` (the pasteboard, the title bar) keeps the typed zoom unapplied; the /// next Enter applies it. @@ -100,7 +100,7 @@ impl ZoomField { // The document's zoom range widened to the current zoom, so the field never pulls the zoom back. let range = device.map(|device| ZoomLadder::percent_range(device, document)); let mut field = NumberField::new(self.label, Bind::given(device.map(|device| device * 100.0))) - .codec(env.units().zoom_codec()) + .codec(env.units().zoom_codec().signed_zoom()) .unit_kind(UnitKind::Percent) .zoom_typing() .enabled(self.enabled && self.view.is_some()); diff --git a/crates/ui-widgets/tests/it/list.rs b/crates/ui-widgets/tests/it/list.rs index 636f3d776..3d4f4da88 100644 --- a/crates/ui-widgets/tests/it/list.rs +++ b/crates/ui-widgets/tests/it/list.rs @@ -34,6 +34,26 @@ fn rig(draft: fn(&usize) -> Option) -> (Fixture, Events) { (fixture, seen) } +#[trial] +fn list_row_declares_and_accepts_access_click() { + use craft_ui::testing::access::Declared; + use craft_ui::testing::focus::AccessActionKind; + let seen = Rc::new(RefCell::new(Vec::new())); + let held = seen.clone(); + let mut fixture = Fixture::new(move |ui| { + let keys = [0_usize, 1, 2]; + let source = keyed(&keys, |key: &usize| *key); + let out = List::options("Artboards").show_items(ui, &source, &mut |key, _| ListRow::new(NAMES[*key]).option()); + held.borrow_mut().extend(out.events); + }); + fixture.settle(); + let row = fixture.by_label(NAMES[1]).expect("the row"); + assert!(fixture.tree().declares_key(row.node, Declared::Click), "the row offers Click to automation"); + seen.borrow_mut().clear(); + fixture.access(AccessActionKind::Click, &row).settle(); + assert!(seen.borrow().iter().any(|event| matches!(event, CollectionEvent::Selection(_))), "Click selects the row"); +} + /// The rects of the three rows of a list shown with `rows`. fn row_rects(rows: RowHeight) -> Vec { let mut fixture = Fixture::new(move |ui| { diff --git a/crates/ui-widgets/tests/it/text/zoom_field.rs b/crates/ui-widgets/tests/it/text/zoom_field.rs index e94c67216..6e278eb84 100644 --- a/crates/ui-widgets/tests/it/text/zoom_field.rs +++ b/crates/ui-widgets/tests/it/text/zoom_field.rs @@ -165,6 +165,26 @@ fn close(a: f64, b: f64) -> bool { (a - b).abs() < 1e-9 } +#[trial] +fn zero_zoom_keeps_the_previous_view() { + let (mut fixture, kept) = focused(false, false); + let before = kept.zoom(); + fixture.type_text("0"); + fixture.key(Key::Enter, Modifiers::NONE); + fixture.settle(); + assert!(close(kept.zoom(), before), "zero must not change the zoom: {}", kept.zoom()); +} + +#[trial] +fn negative_zoom_keeps_the_previous_view() { + let (mut fixture, kept) = focused(false, false); + let before = kept.zoom(); + fixture.type_text("-5"); + fixture.key(Key::Enter, Modifiers::NONE); + fixture.settle(); + assert!(close(kept.zoom(), before), "a negative zoom must not change the view: {}", kept.zoom()); +} + /// The field reads digits, `/` as a ratio and one decimal separator of the locale; it drops every other character /// and alerts. Tab writes the number in the field's own form, selects it and alerts; a second separator applies the /// number before it and reports the range. Each row: (decimal comma, the entry, the text after Tab (no Tab: Enter