From 573c38c23fc7bb90bb3c6d9a59acd90211b65494 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 21 Nov 2026 23:21:26 +0700 Subject: [PATCH] canvas-w6: net change of 1 commits - canvas-w6: written by an agent --- crates/draw/src/ui/corner/stories.rs | 12 + crates/draw/src/ui/corner/widgets.rs | 41 +++- .../draw/src/ui/transform/session_overlay.rs | 5 +- crates/draw/src/ui/transform/transform_box.rs | 66 ++++-- .../src/ui/transform/transform_box/stories.rs | 36 ++- crates/draw/tests/it/corner.rs | 28 ++- crates/draw/tests/it/main.rs | 1 + crates/draw/tests/it/presses.rs | 31 +++ crates/draw/tests/it/transform_box.rs | 210 +++++++++++++++--- .../src/canvas_controls/outline/mod.rs | 142 +++++++++--- .../src/canvas_controls/outline/stories.rs | 7 + .../tests/it/canvas_controls/outline.rs | 89 +++++++- 12 files changed, 565 insertions(+), 103 deletions(-) create mode 100644 crates/draw/tests/it/presses.rs diff --git a/crates/draw/src/ui/corner/stories.rs b/crates/draw/src/ui/corner/stories.rs index ef25594fbb..d3bbb26d65 100644 --- a/crates/draw/src/ui/corner/stories.rs +++ b/crates/draw/src/ui/corner/stories.rs @@ -7,10 +7,12 @@ use std::f64::consts::{PI, TAU}; use std::hash::{DefaultHasher, Hash as _, Hasher as _}; use crate::geometry::fillet::fillet; +use crate::ui::transform::TransformReach; use craft_behavior::kurbo::{BezPath, Point, Vec2}; use craft_ui::canvas::RasterSource as _; use craft_ui::contract::{Bind, Show as _}; use craft_ui::runtime::env::Env; +use craft_ui::style::DataColor; use craft_ui::testing::canvas_story::{OUTLINE, StoryDocument, StoryPicture, StoryShape, accent, on_picture, paint_shapes}; use craft_ui::testing::{Drive, EditKind, Grip, StoryData, StoryOutput, story}; use egui::{Color32, Ui, vec2}; @@ -184,3 +186,13 @@ fn cycling_kinds_and_a_wide_angle_limit(ui: &mut Ui, data: &mut StoryData) -> St let targets = data.value("kinds", targets()); on_canvas(ui, targets, |ui, at, targets| CornerWidgets::new("Corner radius", Bind::bound(targets)).kinds(true).hide_above(120.0).show_at(ui, at)) } + +/// The widgets of a layer the tool does not edit: drawn in the layer's colour, taking no press and no key. +#[story(CornerWidgets<'static>, covers = [], drive = Drive::Never)] +fn display_only_in_a_layer_colour(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let color = DataColor::new(accent(ui, 1.0)); + let targets = data.value("targets", targets()); + on_canvas(ui, targets, |ui, at, targets| { + CornerWidgets::new("Corner radius", Bind::bound(targets)).reach(TransformReach::Shown).color(color).show_at(ui, at) + }) +} diff --git a/crates/draw/src/ui/corner/widgets.rs b/crates/draw/src/ui/corner/widgets.rs index 032a9b6162..b2ebaff95f 100644 --- a/crates/draw/src/ui/corner/widgets.rs +++ b/crates/draw/src/ui/corner/widgets.rs @@ -58,6 +58,9 @@ struct Grab { /// the picked widget's corner on every target by 1 (⇧ 10; up and right grow it), ⌥ that corner only; Enter reports /// `activate`. /// - AccessKit: one object per widget named "Corner i of n", valued "radius 12 px". +/// - Reach: with [`reach`](Self::reach) other than the whole box (`Shown`, or `MoveOnly`, which the widgets have no +/// move reach for) the widgets only paint, in the host's [`color`](Self::color) if it gives one: no part, no key, no +/// AccessKit object. /// - Geometry is in document space and does not mirror right to left. #[derive(craft_ui::contract::Component, craft_ui::contract::Props)] #[component(canvas_control)] @@ -125,6 +128,12 @@ impl Outcome for CornerWidgetsOutput { } impl CornerWidgets<'_> { + /// Whether the widgets take presses and keys: only with the whole reach. The widgets have no move reach, so + /// `MoveOnly` is a display as `Shown` is. + fn takes_input(&self) -> bool { + self.reach == TransformReach::Box + } + /// The widgets of the targets now, on screen. fn shown(&self, style: &CornerStyle, targets: Option<&Vec>, view: &craft_behavior::CanvasView) -> Vec { targets.map_or_else(Vec::new, |targets| geometry::widgets(targets, view, style.inset, style.min_side, self.hide_above)) @@ -242,6 +251,9 @@ impl Component for CornerWidgets<'_> { /// arrival and the arrows are the widget's nudge. fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) { let Some(space) = canvas_space(&cx.env) else { return }; + if !self.takes_input() { + return; + } let widgets = self.shown(cx.style, cx.value(), &space.view); let reach = cx.style.reach; for (at, widget) in widgets.iter().enumerate() { @@ -257,6 +269,9 @@ impl Component for CornerWidgets<'_> { fn update(&mut self, cx: &mut Cx<'_, Self>) { let Some(space) = canvas_space(&cx.env) else { return }; + if !self.takes_input() { + return; + } let widgets = self.shown(cx.style, cx.value(), &space.view); self.run_pointer(cx, &widgets, &space.view); self.run_keys(cx, &widgets); @@ -267,13 +282,16 @@ impl Component for CornerWidgets<'_> { let widgets = self.shown(cx.style, cx.value(), &space.view); let draw = ui.draw(); for widget in &widgets { - paint_widget(&draw, widget.at, cx.style); + paint_widget(&draw, widget.at, cx.style, self.color); } } /// One object per widget, named "Corner i of n" and valued with its radius. fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) { let Some(space) = canvas_space(&cx.env) else { return }; + if !self.takes_input() { + return; + } let widgets = self.shown(cx.style, cx.value(), &space.view); let (words, units) = (cx.words::(), cx.env.units()); let n = widgets.len().to_string(); @@ -291,11 +309,22 @@ impl Component for CornerWidgets<'_> { } } -/// Paints one round widget centred at `at`: the filled ring and its dot. The one painter of the look, which the -/// transform box's live-line midpoint shares. -pub(crate) fn paint_widget(draw: &Draw<'_>, at: Pos2, style: &CornerStyle) { +/// Paints one round widget centred at `at`: the filled ring and its dot, the outline and dot in the host's `color` +/// else the style's. The one painter of the look, which the transform box's live-line midpoint shares. +// PLAN: the sheet's `CornerStyle::with_color(StyleColor)` cannot hold a host's `DataColor` (`StyleColor` has no public +// constructor from a colour), so the override is a parameter and `corner/style.rs` stays as it was. +pub(crate) fn paint_widget(draw: &Draw<'_>, at: Pos2, style: &CornerStyle, color: Option) { let ring = PaintShape::Circle(at, style.widget / 2.0); + let dot = PaintShape::Circle(at, style.dot / 2.0); draw.fill(&ring, style.fill); - draw.stroke(&ring, StrokeWidth::Medium, style.color); - draw.fill(&PaintShape::Circle(at, style.dot / 2.0), style.color); + match color { + None => { + draw.stroke(&ring, StrokeWidth::Medium, style.color); + draw.fill(&dot, style.color); + } + Some(color) => { + draw.stroke(&ring, StrokeWidth::Medium, color); + draw.data_fill(&dot, color); + } + } } diff --git a/crates/draw/src/ui/transform/session_overlay.rs b/crates/draw/src/ui/transform/session_overlay.rs index c86781be77..20b95bad69 100644 --- a/crates/draw/src/ui/transform/session_overlay.rs +++ b/crates/draw/src/ui/transform/session_overlay.rs @@ -54,7 +54,8 @@ pub struct TransformOverlayOutput { /// [`discard`](TransformSession::discard) after the edits. /// - A secondary click on the canvas opens the session's mode menu; a pick reports as the edit it stands for. /// - [`TransformReach::MoveOnly`] offers only the move reach outside the frame: no handle, side, inside, outside, key -/// or menu, and the box is drawn only while its drag runs. +/// or menu, and the box is drawn only while its drag runs. [`TransformReach::Shown`] draws the box and takes +/// nothing: every press and key is the host's. /// - Warp phase: draws nothing, senses nothing and claims nothing; the app's warp widgets own the canvas. /// - Keyboard, AccessKit and right-to-left are the box's. Undo and Redo are the app's Edit commands. #[derive(craft_ui::contract::Pattern)] @@ -112,7 +113,7 @@ impl<'a, W: TransformWarp> TransformOverlay<'a, W> { /// What of the box takes the pointer and the keys: the whole box (the default), or only the move reach outside /// the frame ([`TransformReach::MoveOnly`]), where a plain press moves the box and reaches /// [`TransformOverlayOutput::edits`] as a [`TransformEdit::Box`]; every other press is the host's, and the box has - /// no menu. + /// no menu. [`TransformReach::Shown`] only draws the box: every press and key is the host's. #[must_use] pub fn reach(mut self, reach: TransformReach) -> Self { self.reach = reach; diff --git a/crates/draw/src/ui/transform/transform_box.rs b/crates/draw/src/ui/transform/transform_box.rs index cae997ce62..1542a04941 100644 --- a/crates/draw/src/ui/transform/transform_box.rs +++ b/crates/draw/src/ui/transform/transform_box.rs @@ -18,7 +18,7 @@ use craft_ui::contract::{ Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Focus as _, MeasureCx, Name, Outcome, PaintUi, PartsCx, Pointer as _, Props as _, Remember as _, Role, Styled as _, WordSetCx as _, }; -use craft_ui::primitives::{Draw, Handle, PaintShape, StrokeWidth}; +use craft_ui::primitives::{Draw, Handle, PaintShape, StrokeColor, StrokeWidth}; use craft_ui::runtime::env::{Label, UnitKind}; use craft_ui::runtime::focus::{FocusShape, KeyUse}; use craft_ui::style::{ComponentStyle, DataColor, HandleLook, StyleColor, StyleCx}; @@ -336,7 +336,9 @@ fn slop_sense(part: BoxPart) -> Sense { /// arrows then move the whole box. /// - The box holds the canvas's session (`KeyUse::session`): with the canvas focused or nothing focused, Enter, Escape /// and the arrows reach it before the canvas's tool, and the arrows move the whole box. With -/// [`session_arrows`](Self::session_arrows) off the arrows stay the tool's (the Move tool nudges the layer). +/// [`session_arrows`](Self::session_arrows) off the arrows stay the tool's (the Move tool nudges the layer); with +/// [`session_commit`](Self::session_commit) off Enter and Escape stay the scope's around the canvas (a dialog's OK +/// and Cancel). A [`reach`](Self::reach) of [`TransformReach::Shown`] takes no press and no key at all. /// - A [centre mark](Self::centre_mark) draws the reference point's glyph at the middle of the box and takes no press. /// A [live line's look](Self::line) declares only the line's two ends, each standing for the box handle it points /// to, and draws the line's controls in place of the frame. @@ -445,14 +447,23 @@ impl<'a> TransformBox<'a> { fn move_only(&self) -> Option { match self.reach { TransformReach::MoveOnly { points } => Some(points), - TransformReach::Box => None, - TransformReach::Shown => todo!("cv.F30"), + TransformReach::Box | TransformReach::Shown => None, } } + /// Whether the box takes any press or key: a shown box only paints, so what lies under it keeps every press. + fn takes_input(&self) -> bool { + self.reach != TransformReach::Shown + } + + /// The colour of a stroke that is `theme` unless the host gave the box its own. + fn ink(&self, theme: StyleColor) -> StrokeColor { + self.color.map_or(StrokeColor::from(theme), StrokeColor::from) + } + /// Whether the middle of the box is a move part: the reference point is hidden, so it does not take that place. fn declares_centre(&self) -> bool { - self.move_only().is_none() && !self.reference_point && self.inside_moves && self.rules.allows(BoxPart::Inside) + self.takes_input() && self.move_only().is_none() && !self.reference_point && self.inside_moves && self.rules.allows(BoxPart::Inside) } /// The width of the strips outside the frame, when they are move parts. @@ -462,9 +473,9 @@ impl<'a> TransformBox<'a> { /// The parts the keyboard walks, in order. A box whose inside does not move has no inside part, so a press or drag /// over its body reaches what lies beneath (a type editor under a paragraph frame). A box that offers only its - /// move reach has none. + /// move reach or only a display has none. fn keyboard_parts(&self) -> Vec { - if self.move_only().is_some() { + if self.move_only().is_some() || !self.takes_input() { return Vec::new(); } if let Some(line) = &self.line { @@ -625,8 +636,11 @@ impl<'a> TransformBox<'a> { /// The parts that take a press, with the box part each stands for. Mirrors what [`parts`](Component::parts) /// declares: the keyboard parts, a segment per allowed edge, the centre where declared, and the outside; or only the - /// move strips. + /// move strips; or none for a shown box. fn pointer_parts(&self) -> Vec<(PartRef, BoxPart)> { + if !self.takes_input() { + return Vec::new(); + } if self.move_only().is_some() { let parts = if self.ring_reach().is_some() { 0..8 } else { 0..0 }; return parts.map(|part| (MOVE_RING.at(part), BoxPart::Inside)).collect(); @@ -774,10 +788,10 @@ impl<'a> TransformBox<'a> { } } } - if cx.intents().take(Intent::Submit) { + if self.session_commit && cx.intents().take(Intent::Submit) { self.report.apply = Some(ApplyBy::Key); } - if !pressing && cx.intents().take(Intent::Cancel) { + if self.session_commit && !pressing && cx.intents().take(Intent::Cancel) { self.report.discard = true; } } @@ -792,7 +806,7 @@ impl TransformBox<'_> { let square = PaintShape::Rect(Rect::from_center_size(at, Vec2::splat(side)), CornerRadius::ZERO); let fill = if self.rules.allows(part) { cx.resolve_part(BOX.at(part.index()), &look.fill) } else { cx.resolve(&look.fill) }; draw.fill(&square, fill); - draw.stroke(&square, StrokeWidth::Thin, look.stroke); + draw.stroke(&square, StrokeWidth::Thin, self.ink(look.stroke)); if enlarged { Handle::plus(draw, look, at, side); } @@ -804,27 +818,27 @@ impl TransformBox<'_> { let style = cx.style; if let Some(outline) = line.outline { let corners = outline.map(|corner| view.to_screen(corner)); - paint_frame(draw, style, corners); + paint_frame(draw, style, self.ink(style.line), corners); let look = &style.handle; for k in 0..4 { let middle = corners[k].lerp(corners[(k + 1) % 4], 0.5); let square = PaintShape::Rect(Rect::from_center_size(middle, Vec2::splat(look.side)), CornerRadius::ZERO); draw.fill(&square, cx.resolve(&look.fill)); - draw.stroke(&square, StrokeWidth::Thin, look.stroke); + draw.stroke(&square, StrokeWidth::Thin, self.ink(look.stroke)); } } for (part, end) in line.ends() { self.paint_handle(draw, cx, part, view.to_screen(end), false); } - paint_widget(draw, view.to_screen(line.from.midpoint(line.to)), &style.widget); + paint_widget(draw, view.to_screen(line.from.midpoint(line.to)), &style.widget, None); } } -/// The outline of a box whose corners are `corners` on the screen: the line over its halo. -fn paint_frame(draw: &Draw<'_>, style: &TransformBoxStyle, corners: [Pos2; 4]) { +/// The outline of a box whose corners are `corners` on the screen: `line` over the halo. +fn paint_frame(draw: &Draw<'_>, style: &TransformBoxStyle, line: StrokeColor, corners: [Pos2; 4]) { let outline = PaintShape::Polygon(corners.to_vec()); draw.stroke(&outline, StrokeWidth::Thick, style.halo); - draw.stroke(&outline, StrokeWidth::Medium, style.line); + draw.stroke(&outline, StrokeWidth::Medium, line); } /// The move reach outside the box whose corners are `quad` on the screen: every point within `points` of its border, @@ -870,10 +884,10 @@ fn outward_normals(quad: &[Pos2; 4]) -> [Vec2; 4] { } /// The reference point's glyph centred at `centre`: a circle crossed by two arms, over its halo. The one glyph of the -/// reference point and of the centre mark. -fn paint_centre_glyph(draw: &Draw<'_>, centre: Pos2, style: &TransformBoxStyle) { +/// reference point and of the centre mark; `line` is the colour over the halo. +fn paint_centre_glyph(draw: &Draw<'_>, centre: Pos2, style: &TransformBoxStyle, line: StrokeColor) { let (radius, arm) = (style.pivot_radius, style.pivot_arm); - for (width, color) in [(StrokeWidth::Thick, style.halo), (StrokeWidth::Medium, style.line)] { + for (width, color) in [(StrokeWidth::Thick, StrokeColor::from(style.halo)), (StrokeWidth::Medium, line)] { draw.stroke(&PaintShape::Circle(centre, radius), width, color); draw.stroke(&PaintShape::Path(vec![centre - Vec2::new(arm, 0.0), centre + Vec2::new(arm, 0.0)]), width, color); draw.stroke(&PaintShape::Path(vec![centre - Vec2::new(0.0, arm), centre + Vec2::new(0.0, arm)]), width, color); @@ -960,6 +974,9 @@ impl Component for TransformBox<'_> { /// line's controls declare its two ends only. fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) { let (Some(space), Some(state)) = (canvas_space(&cx.env), cx.value().copied()) else { return }; + if !self.takes_input() { + return; + } let style = cx.style; let screen = on_screen(&space.view, &state); let quad: [Pos2; 4] = screen.quad.map(pos); @@ -1052,6 +1069,9 @@ impl Component for TransformBox<'_> { fn update(&mut self, cx: &mut Cx<'_, Self>) { let (Some(space), Some(shown)) = (canvas_space(&cx.env), cx.value().copied()) else { return }; + if !self.takes_input() { + return; + } let held = cx.press_slot::().is_some(); self.run_pointer(cx, &space, &shown); self.pivot_held = cx.press_slot::().is_some_and(|grip| grip.part == BoxPart::Pivot); @@ -1077,10 +1097,10 @@ impl Component for TransformBox<'_> { match self.line.filter(|_| !self.dragging) { Some(line) => self.paint_line(&draw, cx, &space.view, &line), None => { - paint_frame(&draw, style, screen.quad.map(pos)); + paint_frame(&draw, style, self.ink(style.line), screen.quad.map(pos)); if self.centre_mark { let centre = screen.quad.iter().fold(Vec2::ZERO, |sum, corner| sum + pos(*corner).to_vec2()) / 4.0; - paint_centre_glyph(&draw, centre.to_pos2(), style); + paint_centre_glyph(&draw, centre.to_pos2(), style, self.ink(style.line)); } for i in 0..4u8 { for part in [BoxPart::Corner(i), BoxPart::Edge(i)] { @@ -1092,7 +1112,7 @@ impl Component for TransformBox<'_> { } } if self.reference_point || self.pivot_held { - paint_centre_glyph(&draw, pos(screen.pivot), style); + paint_centre_glyph(&draw, pos(screen.pivot), style, self.ink(style.line)); } } diff --git a/crates/draw/src/ui/transform/transform_box/stories.rs b/crates/draw/src/ui/transform/transform_box/stories.rs index 9dc87eb10c..dba8beef6a 100644 --- a/crates/draw/src/ui/transform/transform_box/stories.rs +++ b/crates/draw/src/ui/transform/transform_box/stories.rs @@ -1,12 +1,16 @@ //! Stories of the transform box: Free Transform with its reference point, the Move tool's controls, Distort, the //! Ellipse tool's centre mark and the Line tool's live-line controls. -use super::{BOX, LineLook, RotateZone, TransformBox}; +use super::{BOX, LineLook, RotateZone, TransformBox, TransformReach}; use craft_behavior::geometry::quad::{BoxPart, BoxRules, BoxState, TransformMode}; use craft_behavior::kurbo::{Point, Rect as DocRect}; +use craft_ui::buttons::Button; use craft_ui::canvas::Canvas; -use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; -use craft_ui::testing::canvas_story::{OUTLINE, StoryDocument, StoryPicture, StoryShape, paint_shapes, show_document, show_quad}; +use craft_ui::contract::{Bind, Show as _, ShowContainer as _, clicked}; +use craft_ui::dialog::Dialog; +use craft_ui::sections::{DialogRole, FooterButton}; +use craft_ui::style::DataColor; +use craft_ui::testing::canvas_story::{OUTLINE, StoryDocument, StoryPicture, StoryShape, accent, paint_shapes, show_document, show_quad}; use craft_ui::testing::{Drive, Grip, StoryData, StoryOutput, story}; use egui::{Color32, Ui, vec2}; @@ -72,6 +76,32 @@ fn ellipse_centre_mark(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).centre_mark(true)) } +/// A display-only box in a layer's colour, as the Selection tool shows the layers it does not transform: it takes no +/// press and no key. +#[story(TransformBox<'static>, covers = [Default], drive = Drive::Never)] +fn display_only_in_a_layer_colour(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let color = DataColor::new(accent(ui, 1.0)); + on_canvas(ui, data, move |state| free_box(state).reach(TransformReach::Shown).color(color)) +} + +/// Free Distort's pad: a box that only distorts, with no reference point and no inside move, in a dialog it does not +/// close: Enter and Escape stay the dialog's. The dialog starts closed. +#[story(TransformBox<'static>, covers = [Default], drive = Drive::Never)] +fn distort_pad(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let mut open = *data.value("open", false); + if clicked(&Button::new("Open Free Distort").show(ui)) { + open = true; + } + let mut output = StoryOutput::default(); + Dialog::new("Free Distort").opened(Bind::bound(&mut open)).buttons([FooterButton::new("OK", DialogRole::Accept)]).show(ui, |ui, _| { + output = on_canvas(ui, data, |state| { + free_box(state).rules(BoxRules::in_mode(TransformMode::Distort)).reference_point(false).inside_moves(false).session_commit(false) + }); + }); + *data.value("open", false) = open; + output +} + /// The Line tool's controls on a live line across the box: a square at each end and the round widget at its middle, /// no frame. Each end drags as the corner it points to. #[story(TransformBox<'static>, covers = [Default], drive = Drive::Drag(Grip::part(BOX.at(BoxPart::Corner(1).index())).toward(vec2(1.0, -1.0))))] diff --git a/crates/draw/tests/it/corner.rs b/crates/draw/tests/it/corner.rs index b014cb1a4a..966d6b0650 100644 --- a/crates/draw/tests/it/corner.rs +++ b/crates/draw/tests/it/corner.rs @@ -1,14 +1,16 @@ //! The corner widgets' drag reports its edit on the pass that commits it. +use super::presses::Presses; use craft_behavior::CanvasView; use craft_behavior::kurbo::Point; use craft_draw::ui::corner::{CornerPoint, CornerTarget}; +use craft_draw::ui::transform::TransformReach; use craft_draw::ui::{CornerEdit, CornerKind, CornerWidgets}; use craft_ui::canvas::Canvas; use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; -use craft_ui::testing::{EditKind, Fixture, trial}; +use craft_ui::testing::{EditKind, Fixture, ToolFixture, trial}; use egui::vec2; -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::rc::Rc; const START_RADIUS: f64 = 4.0; @@ -85,6 +87,28 @@ fn apex_radius_after_drag(down: f32) -> f64 { host.borrow()[0].corners[0].radius } +/// A press on a widget of a shown set reaches what lies under the widgets, the Selection tool: the widgets declare no +/// part and show no node, and no radius changes. +#[trial] +fn shown_corner_widgets_leave_a_press_on_a_widget_to_the_canvas_background() { + let targets = Rc::new(RefCell::new(vec![square()])); + let reach = Rc::new(Cell::new(TransformReach::Box)); + let (shown, mode) = (Rc::clone(&targets), Rc::clone(&reach)); + let view = |room: egui::Rect| CanvasView::new(room, Point::new(210.0, 200.0), 1.0); + let mut fixture = ToolFixture::with_view("Document", Presses::default(), view, move |ui, body| { + let mut targets = shown.borrow_mut(); + let _ = CornerWidgets::new("Corner radius", Bind::bound(&mut *targets)).reach(mode.get()).show_at(ui, body.rect); + }); + // Where the widget is while it takes presses. + let at = fixture.fixture().by_label("Corner 1 of 4").expect("the first corner has a widget").center(); + reach.set(TransformReach::Shown); + fixture.fixture().settle(); + assert!(fixture.fixture().by_label("Corner 1 of 4").is_none(), "a shown widget has no node"); + fixture.drag_from(at, vec2(30.0, 30.0)); + assert_eq!(fixture.tool().count, 1, "the press reached the tool"); + assert_eq!(targets.borrow()[0].corners[0].radius, START_RADIUS, "no radius changed"); +} + /// The apex of a triangle is a corner like any other: pulling its widget inward rounds it, and the further the /// pointer travels the larger the radius. #[trial] diff --git a/crates/draw/tests/it/main.rs b/crates/draw/tests/it/main.rs index 03e713b2e9..031268df27 100644 --- a/crates/draw/tests/it/main.rs +++ b/crates/draw/tests/it/main.rs @@ -3,6 +3,7 @@ // draw-shape mod add_beside; mod corner; +mod presses; mod shape_cells; // draw-gradient-b diff --git a/crates/draw/tests/it/presses.rs b/crates/draw/tests/it/presses.rs new file mode 100644 index 0000000000..1498f455b6 --- /dev/null +++ b/crates/draw/tests/it/presses.rs @@ -0,0 +1,31 @@ +//! A canvas tool that counts the presses that reach it, for trials of controls that must leave a press to the tool. + +use craft_behavior::CancelReason; +use craft_ui::canvas::{CanvasTool, ToolAction, ToolContext, ToolPath, ToolPointer}; +use craft_ui::primitives::Draw; + +/// A tool that counts the presses that reach it. +#[derive(Default)] +pub struct Presses { + /// The presses so far. + pub count: usize, +} + +impl CanvasTool for Presses { + fn press(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) -> ToolAction { + self.count += 1; + ToolAction::Claimed + } + + fn drag(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {} + + fn release(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {} + + fn cancel(&mut self, _: CancelReason, _: &mut ToolContext<'_>) {} + + fn paint(&self, _: &Draw<'_>, _: &ToolContext<'_>) {} + + fn command_form(&self) -> ToolPath { + ToolPath::Command("the Select Area... command") + } +} diff --git a/crates/draw/tests/it/transform_box.rs b/crates/draw/tests/it/transform_box.rs index 4712c9ff8a..f0f82d9e6d 100644 --- a/crates/draw/tests/it/transform_box.rs +++ b/crates/draw/tests/it/transform_box.rs @@ -4,19 +4,23 @@ use craft_behavior::geometry::quad::{BoxPart, BoxRules, BoxState, ScaleRule, TransformMode}; use craft_behavior::geometry::{SnapKind, SnapOptions, SnapTarget, SnapTargets}; use craft_behavior::kurbo::{Point, Rect}; +use super::presses::Presses; use craft_behavior::{CanvasView, EditEvent, RulerUnits, Ticks}; use craft_draw::ui::transform::{ - LineLook, RotateZone, TransformBox, TransformEdit, TransformOverlay, TransformReach, TransformSession, TransformSettings, + LineLook, RotateZone, TransformBox, TransformBoxOutput, TransformEdit, TransformOverlay, TransformReach, TransformSession, TransformSettings, }; use craft_keymap::{Mods, Platform}; use craft_ui::canvas::{Canvas, RulerText, Snap}; use craft_ui::canvas::{Guide, GuideKey}; use craft_ui::canvas_controls::Guides; use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft_ui::dialog::Dialog; use craft_ui::runtime::env::UnitKind; -use craft_ui::testing::{Fixture, pointer, trial}; -use egui::{Pos2, Vec2}; -use std::cell::RefCell; +use craft_ui::runtime::overlay::CloseReason; +use craft_ui::sections::{DialogRole, FooterButton}; +use craft_ui::testing::{Fixture, ToolFixture, pointer, trial}; +use egui::{Key, Modifiers, Pos2, Shape, Vec2}; +use std::cell::{Cell, RefCell}; use std::rc::Rc; use std::sync::Arc; @@ -57,6 +61,10 @@ struct Config { targets: Vec, /// egui runs each frame twice and gives the frame's input to its first pass only. twice: bool, + /// What of the box takes the pointer and the keys. + reach: TransformReach, + /// Whether Enter and Escape from the canvas session are the box's. + session_commit: bool, } /// What the host keeps of the box and what the passes reported. @@ -102,6 +110,8 @@ fn defaults() -> Config { line: None, targets: Vec::new(), twice: false, + reach: TransformReach::Box, + session_commit: true, } } @@ -184,6 +194,7 @@ fn harness(state: BoxState, setup: impl FnOnce(&mut Config)) -> Harness { if let Some(line) = config.line { control = control.line(line); } + control = control.reach(config.reach).session_commit(config.session_commit); (control.show_at(ui, body.rect), guide_edits) }); if config.twice && ui.ctx().current_pass_index() == 0 { @@ -192,42 +203,48 @@ fn harness(state: BoxState, setup: impl FnOnce(&mut Config)) -> Harness { if let Some((output, guide_edits)) = canvas.inner { let mut host = shown_host.borrow_mut(); host.guide_events += guide_edits; - host.snapped = output.snapped.len(); - host.id = output.edit.response.id; - host.applied += usize::from(output.apply.is_some()); - host.discarded += usize::from(output.discard); - (host.picked, host.hovered) = (output.picked, output.hovered); - for event in &output.edit.events { - match event { - EditEvent::Begin { .. } => { - host.events.push(Seen::Begin); - host.before = Some(host.state); - } - EditEvent::Update { value, .. } => { - host.events.push(Seen::Update); - host.state = if config.f32_host { kept_in_f32(value) } else { *value }; - } - EditEvent::Commit { after, .. } => { - host.events.push(Seen::Commit); - host.state = if config.f32_host { kept_in_f32(after) } else { *after }; - } - EditEvent::Set { after, .. } => { - host.events.push(Seen::Set); - host.state = *after; - } - EditEvent::Cancel { .. } => { - host.events.push(Seen::Cancel); - host.state = host.before.take().unwrap_or(host.state); - } - _ => {} - } - } + absorb(&mut host, &output, config.f32_host); } }); fixture.settle(); Harness { fixture, host, config: kept_config } } +/// Takes what a pass reported into the host: the apply and discard counts, the part the keys act on and the part under +/// the pointer, and each edit event into the box the host keeps. +fn absorb(host: &mut Host, output: &TransformBoxOutput, f32_host: bool) { + host.snapped = output.snapped.len(); + host.id = output.edit.response.id; + host.applied += usize::from(output.apply.is_some()); + host.discarded += usize::from(output.discard); + (host.picked, host.hovered) = (output.picked, output.hovered); + for event in &output.edit.events { + match event { + EditEvent::Begin { .. } => { + host.events.push(Seen::Begin); + host.before = Some(host.state); + } + EditEvent::Update { value, .. } => { + host.events.push(Seen::Update); + host.state = if f32_host { kept_in_f32(value) } else { *value }; + } + EditEvent::Commit { after, .. } => { + host.events.push(Seen::Commit); + host.state = if f32_host { kept_in_f32(after) } else { *after }; + } + EditEvent::Set { after, .. } => { + host.events.push(Seen::Set); + host.state = *after; + } + EditEvent::Cancel { .. } => { + host.events.push(Seen::Cancel); + host.state = host.before.take().unwrap_or(host.state); + } + _ => {} + } + } +} + fn upright() -> Harness { harness(BoxState::from_rect(RECT), |_| {}) } @@ -1030,3 +1047,128 @@ fn the_reference_point_snaps_to_the_turned_boxs_points_only() { assert_eq!(h.state().quad, turned.quad, "the box never moved"); } } + +#[trial] +fn a_shown_box_takes_no_press_and_no_key_and_leaves_both_to_the_tool() { + let reported = Rc::new(Cell::new(0usize)); + let sink = Rc::clone(&reported); + // The view shows the room's centre as the document point of the same numbers, so document and screen points + // coincide. + let view = |room: egui::Rect| CanvasView::new(room, Point::new(f64::from(room.center().x), f64::from(room.center().y)), 1.0); + let mut fixture = ToolFixture::with_view("Document", Presses::default(), view, move |ui, body| { + let shown = TransformBox::new("Free Transform", Bind::given(BoxState::from_rect(RECT)), RECT, 0.0) + .reach(TransformReach::Shown) + .show_at(ui, body.rect); + sink.set(sink.get() + usize::from(shown.apply.is_some()) + usize::from(shown.discard) + shown.edit.events.len()); + }); + // A handle, the inside and the outside of the box. + for at in [Pos2::new(300.0, 220.0), Pos2::new(200.0, 150.0), Pos2::new(350.0, 270.0)] { + fixture.press_at(at).release_at(at); + } + assert_eq!(fixture.tool().count, 3, "every press reaches the tool"); + for key in [Key::ArrowRight, Key::Enter, Key::Escape] { + fixture.fixture().key(key, Modifiers::NONE); + } + assert_eq!(reported.get(), 0, "the box reported no edit, apply or discard"); + assert!(fixture.fixture().by_label("Bottom right corner").is_none(), "a shown box has no part in the accessibility tree"); + let framed = |shape: &Shape| matches!(shape, Shape::Path(path) if path.closed && path.points.len() == 4); + assert!(fixture.fixture().frame_shapes().iter().any(framed), "the box still paints its frame"); +} + +/// The host of a distort pad in a dialog: the box it keeps, what the box reported and how the dialog closed. +struct Pad { + host: Host, + closed: Option, +} + +/// A Free Distort pad as the effects dialogs show it, with `session_commit` off, in an open dialog whose Enter is OK +/// and whose Escape cancels. The pad's view is kept in the host. +fn pad() -> (Fixture, Rc>) { + let state = BoxState::from_rect(RECT); + let host = Host { + state, + before: None, + events: Vec::new(), + applied: 0, + discarded: 0, + picked: None, + hovered: None, + id: egui::Id::NULL, + view: CanvasView::new(egui::Rect::NOTHING, Point::ZERO, 1.0), + guide_events: 0, + snapped: 0, + }; + let pad = Rc::new(RefCell::new(Pad { host, closed: None })); + let shown = Rc::clone(&pad); + let mut fixture = Fixture::new(move |ui| { + let mut open = true; + let dialog = Dialog::new("Free Distort") + .opened(Bind::bound(&mut open)) + .close_on_enter(true) + .buttons([FooterButton::new("OK", DialogRole::Accept), FooterButton::new("Cancel", DialogRole::Cancel)]) + .show(ui, |ui, _| { + ui.allocate_ui(egui::vec2(400.0, 300.0), |ui| { + let room = ui.available_rect_before_wrap(); + let view = CanvasView::new(room, Point::new(f64::from(room.width()) / 2.0, f64::from(room.height()) / 2.0), 1.0); + let state = { + let mut pad = shown.borrow_mut(); + pad.host.view = view; + pad.host.state + }; + let canvas = Canvas::new("Document").view(view).show(ui, |ui, body| { + TransformBox::new("Free Transform", Bind::given(state), RECT, 0.0) + .rules(BoxRules::in_mode(TransformMode::Distort)) + .reference_point(false) + .inside_moves(false) + .session_commit(false) + .show_at(ui, body.rect) + }); + if let Some(output) = canvas.inner { + absorb(&mut shown.borrow_mut().host, &output, false); + } + }); + }); + if dialog.output.closed.is_some() { + shown.borrow_mut().closed = dialog.output.closed; + } + }); + fixture.settle(); + (fixture, pad) +} + +#[trial] +fn a_box_without_session_commit_leaves_enter_and_escape_to_the_dialog() { + for (key, closed) in [(Key::Enter, CloseReason::Activated), (Key::Escape, CloseReason::Escape)] { + let (mut fixture, pad) = pad(); + // A click on a handle gives the box the keyboard, where the session's Enter and Escape would be its own. + let corner = pad.borrow().host.view.to_screen(Point::new(300.0, 220.0)); + fixture.frame(vec![pointer::moved(corner)]); + fixture.frame(vec![pointer::press(corner)]); + fixture.frame(vec![pointer::release(corner)]); + fixture.key(Key::ArrowRight, Modifiers::NONE); + let moved = pad.borrow().host.state.quad[0].x - RECT.x0; + assert!((moved - 1.0).abs() < 1e-6, "an arrow still moves the box by one unit: {moved}"); + fixture.key(key, Modifiers::NONE); + fixture.settle(); + let pad = pad.borrow(); + assert_eq!((pad.host.applied, pad.host.discarded), (0, 0), "{key:?}: the box takes neither Enter nor Escape"); + assert_eq!(pad.closed, Some(closed), "{key:?}: the dialog around the canvas gets it"); + } +} + +#[trial] +fn a_drags_escape_still_cancels_it_in_a_box_without_session_commit() { + let (mut fixture, pad) = pad(); + let start = pad.borrow().host.view.to_screen(Point::new(300.0, 220.0)); + fixture.frame(vec![pointer::moved(start)]); + fixture.frame(vec![pointer::press(start)]); + fixture.frame(vec![pointer::moved(start + by(8.0, 6.0))]); + fixture.frame(vec![pointer::moved(start + by(16.0, 12.0))]); + assert!(pad.borrow().host.state != BoxState::from_rect(RECT), "the drag moved the corner"); + fixture.key(Key::Escape, Modifiers::NONE); + fixture.frame(vec![pointer::release(start + by(16.0, 12.0))]); + fixture.settle(); + let pad = pad.borrow(); + assert_eq!(pad.host.state, BoxState::from_rect(RECT), "Escape put the box back"); + assert!(pad.host.events.contains(&Seen::Cancel), "the drag was cancelled: {:?}", pad.host.events); +} diff --git a/crates/ui-canvas/src/canvas_controls/outline/mod.rs b/crates/ui-canvas/src/canvas_controls/outline/mod.rs index 5475352c31..d65b48a3c5 100644 --- a/crates/ui-canvas/src/canvas_controls/outline/mod.rs +++ b/crates/ui-canvas/src/canvas_controls/outline/mod.rs @@ -9,13 +9,15 @@ pub(super) mod stories; use crate::canvas::canvas_space; use crate::contract::{Access, Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role}; use crate::primitives::textures::{Revision, TextureStore, TextureStoreOptions, UNTINTED}; -use crate::primitives::{ContentPainterCx, Dashes, PaintShape, StrokeWidth}; +use crate::primitives::{ContentPainterCx, Dashes, PaintShape, dashed, outline}; use crate::runtime::env::Label; -use crate::style::{ComponentStyle, DataColor, StyleColor, StyleCx}; -use craft_behavior::kurbo::{self, BezPath, PathEl, Rect}; +use crate::runtime::memory::Remember as _; +use crate::style::{ComponentStyle, DataColor, StyleColor, StyleCx, UiTokens}; +use craft_behavior::kurbo::{self, BezPath, PathEl, Point, Rect}; use craft_behavior::{CanvasView, Input, Metrics}; use egui::epaint::Vertex; -use egui::{Color32, ColorImage, Mesh, Pos2, Response, Shape, Stroke, pos2}; +use egui::{Color32, ColorImage, Mesh, Pos2, Response, Shape, Stroke, Vec2, pos2}; +use std::sync::Arc; pub use hover::HoverMask; @@ -149,17 +151,23 @@ fn segment_hull(from: kurbo::Point, segment: PathEl) -> Vec { } } -/// Strokes one run: the kit's halo-and-line outline in the overlay colours, or a line of the host's `color` alone. -fn stroke_run(painter: &ContentPainterCx<'_>, run: Vec, closed: bool, color: Option, width: f32) { +/// The shapes of one run: the kit's halo-and-line outline in the overlay colours, or a line of the host's `color` +/// alone. +fn run_shapes(tokens: &UiTokens, run: Vec, closed: bool, color: Option, width: f32) -> Vec { match color { - None => painter.outline(&if closed { PaintShape::Polygon(run) } else { PaintShape::Path(run) }), + None => outline(tokens, &if closed { PaintShape::Polygon(run) } else { PaintShape::Path(run) }), Some(color) => { let stroke = Stroke::new(width, color.0); - painter.painter.add(if closed { Shape::closed_line(run, stroke) } else { Shape::line(run, stroke) }); + vec![if closed { Shape::closed_line(run, stroke) } else { Shape::line(run, stroke) }] } } } +/// Strokes one run; see [`run_shapes`]. +fn stroke_run(painter: &ContentPainterCx<'_>, tokens: &UiTokens, run: Vec, closed: bool, color: Option, width: f32) { + painter.painter.extend(run_shapes(tokens, run, closed, color, width)); +} + fn tint(mask: &HoverMask, color: Color32) -> ColorImage { let [width, height] = mask.size(); let mut pixels = Vec::with_capacity(width * height); @@ -243,11 +251,11 @@ impl Component for HoverOutline { let (half_y, half_x) = (view.doc_len(style.medium / 2.0), f64::from(style.medium / 2.0) / view.zoom_x()); let rect = rect.abs(); let grown = Rect::new(rect.x0 - half_x, rect.y0 - half_y, rect.x1 + half_x, rect.y1 + half_y); - stroke_run(&painter, view.quad(grown).to_vec(), true, self.color, style.medium); + stroke_run(&painter, &cx.env.tokens, view.quad(grown).to_vec(), true, self.color, style.medium); } HoverShape::Path(path) => { for (points, closed) in path_runs(&view, path) { - stroke_run(&painter, points, closed, self.color, style.medium); + stroke_run(&painter, &cx.env.tokens, points, closed, self.color, style.medium); } } HoverShape::Mask(mask) => paint_mask(&painter, &view, mask, self.color.map_or(style.line.egui(), |color| color.0)), @@ -276,17 +284,38 @@ pub struct SelectionOutline<'a> { /// The line colour (a layer's colour); the overlay line colour by default. #[prop] color: Option, - /// The key outline, stroked after the paths at `stroke.medium`. + /// The key outline, stroked after the paths at `stroke.medium` in the outline colour. #[prop] - #[allow(dead_code)] // P3(canvas-w6): cv.F29 key: Option<&'a BezPath>, - /// The paths' revision: with it, the stroked shapes are kept in control memory and reused; without it, rebuilt - /// every pass. + /// The revision of the paths and the key: while it holds, the view, the colour and the look, the stroked shapes + /// are kept in control memory and reused, and a pan by whole device pixels moves them instead of flattening the + /// paths again. The host changes it whenever a path changes. Without it the shapes are built every pass. #[prop] - #[allow(dead_code)] // P3(canvas-w6): cv.F29 revision: Option, } +/// What the shapes of a [`SelectionOutline`] are built from besides the view's centre: when none of it changed, the +/// kept shapes are the shapes to paint. The paths themselves are covered by `revision`. +#[derive(Clone, PartialEq)] +struct OutlineKey { + revision: u64, + /// The view with its centre zeroed: a pan keeps the key. + view: CanvasView, + color: Color32, + look: SelectionOutlineLook, + has_key: bool, + style: OutlineStyle, + pixels_per_point: f32, +} + +/// The shapes of a selection outline under the key they were built for, and the view centre they were built at. +#[derive(Clone, Default)] +struct OutlineShapes { + key: Option, + centre: Point, + shapes: Arc>, +} + impl<'a> SelectionOutline<'a> { /// A solid outline of `paths` (document units), named `label`. pub fn solid(label: impl Into