From 92ccdde34dd51b5996bad96e6cca6d182e2df585 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sun, 15 Nov 2026 04:46:09 +0000 Subject: [PATCH] tools-w8: net change of 3 commits - tools-w8: written from its sheet - tools-w8: review fixes (review-1) - tools-w8: the arrowheads popover takes a reborrowed binding (combine) --- crates/draw/src/ui/corner/widgets.rs | 10 +- crates/draw/src/ui/shape/arrowheads.rs | 87 +++++++++++++-- crates/draw/src/ui/shape/bar.rs | 76 ++++++------- crates/draw/src/ui/shape/mod.rs | 14 +-- crates/draw/src/ui/shape/mode_select.rs | 21 +++- crates/draw/src/ui/shape/panel.rs | 136 +++++++++++------------ crates/draw/src/ui/shape/stories.rs | 82 +++++++++++++- crates/draw/src/ui/shape/stroke_cells.rs | 70 ++++++++++-- crates/draw/src/ui/shape/words.rs | 24 ++++ crates/draw/src/ui/shape_drag/tool.rs | 4 +- crates/draw/tests/it/corner.rs | 62 +++++++++++ crates/draw/tests/it/main.rs | 2 + crates/draw/tests/it/shape_cells.rs | 100 +++++++++++++++++ 13 files changed, 540 insertions(+), 148 deletions(-) create mode 100644 crates/draw/tests/it/corner.rs create mode 100644 crates/draw/tests/it/shape_cells.rs diff --git a/crates/draw/src/ui/corner/widgets.rs b/crates/draw/src/ui/corner/widgets.rs index 3e60263fc..2144e1e62 100644 --- a/crates/draw/src/ui/corner/widgets.rs +++ b/crates/draw/src/ui/corner/widgets.rs @@ -144,7 +144,7 @@ impl CornerWidgets<'_> { self.show_readout(cx, pos, radius); self.report.change = Some(edit); } - PressPhase::Release { start, click, .. } if start.button == PointerButton::Primary => { + PressPhase::Release { start, pos, click, .. } if start.button == PointerButton::Primary => { let grab = cx.memory::().clone(); if grab.corner != Some(widget.corner) { continue; @@ -156,6 +156,14 @@ impl CornerWidgets<'_> { self.report.activate = Some(widget.corner); } } else { + // The release point is the gesture's last move: propose it and report it before the commit, so a + // host that applies `change` to its own types gets the last move too. + if let Some(step) = grab.step { + let radius = geometry::dragged_radius(grab.from, step, grab.press, view.to_doc(pos)); + let edit = geometry::drag_edit(&grab.targets, widget.corner, radius, press.mods.alt); + cx.propose(geometry::apply(&grab.targets, &edit)); + self.report.change = Some(edit); + } cx.commit(); } *cx.memory::() = Grab::default(); diff --git a/crates/draw/src/ui/shape/arrowheads.rs b/crates/draw/src/ui/shape/arrowheads.rs index 070dfd407..2c44c1d20 100644 --- a/crates/draw/src/ui/shape/arrowheads.rs +++ b/crates/draw/src/ui/shape/arrowheads.rs @@ -1,16 +1,28 @@ //! [`ArrowheadsPopover`]: the Line tool's arrowhead settings. -use super::Arrowheads; -use craft_behavior::EditEvent; -use craft_ui::contract::Bind; +use std::sync::Arc; + +use super::panel::NumberCell; +use super::{Arrowheads, ShapeWords}; +use craft_behavior::{EditEvent, EditEvents, IconId, Mixed}; +use craft_ui::buttons::IconButton; +use craft_ui::choice::Checkbox; +use craft_ui::contract::{Bind, LabelScheme, PopupKind, Props as _, Show as _, ShowContainer as _, clicked}; +use craft_ui::form::FieldGroup; +use craft_ui::layout_components::Row; +use craft_ui::popover::Popover; +use craft_ui::runtime::env::{Env, Units}; use egui::{Response, Ui}; -/// The arrowhead popover: which ends carry a head and the head's width, length and concavity. + +/// The arrowhead popover: which ends carry a head and the head's width, length and concavity. Its `open` flag is read +/// and written through the binding, so give it `Bind::bound`. #[must_use = "show the popover with `show`"] #[derive(craft_ui::contract::Pattern)] pub struct ArrowheadsPopover<'a> { value: Bind<'a, Arrowheads>, open: Bind<'a, bool>, + pixels_per_inch: f64, } /// What [`ArrowheadsPopover::show`] reports. @@ -19,20 +31,71 @@ pub struct ArrowheadsPopover<'a> { pub struct ArrowheadsOutput { /// The button's response. pub response: Response, - /// The edit made this pass, if any. - pub edit: Option>, + /// The edits of this pass in order, each the whole value with one field replaced. A gesture's first pass carries + /// its `Begin` and first `Update` together. + pub edits: Vec>, } impl<'a> ArrowheadsPopover<'a> { - /// The popover of `value`, open while `open` is set. - pub fn new(value: Bind<'a, Arrowheads>, open: Bind<'a, bool>) -> Self { - ArrowheadsPopover { value, open } + /// The popover of `value`, open while `open` is set, in a document of `pixels_per_inch`, which sizes a length typed + /// in inches or points. + pub fn new(value: Bind<'a, Arrowheads>, open: Bind<'a, bool>, pixels_per_inch: f64) -> Self { + ArrowheadsPopover { value, open, pixels_per_inch } } /// Shows the button and, while open, the popover. pub fn show(self, ui: &mut Ui) -> ArrowheadsOutput { - let ArrowheadsPopover { value, open } = self; - let _ = (ui, value, open); - todo!("tl.T29") + let ArrowheadsPopover { mut value, mut open, pixels_per_inch } = self; + let env = Env::of(ui); + let (words, units) = (env.words::(), env.units()); + let current = match value.reborrow().get() { + Some(Mixed::Same(shown)) => shown, + _ => Arrowheads::default(), + }; + let was = matches!(open.reborrow().get(), Some(Mixed::Same(true))); + let gear = IconButton::new(IconId::new("settings")).label(words.arrowheads.clone()).popup(PopupKind::Dialog).expanded(was).show(ui).response; + if clicked(&gear) { + // The popover's opener is manual: the gear's press is the pattern's to apply. + let event = EditEvent::set(Mixed::Same(was), !was, Arc::from(words.arrowheads.as_str()), None); + let _ = open.reborrow().apply(&event); + } + let mut edits = Vec::new(); + let _ = Popover::new(words.arrowheads.clone(), open.reborrowed()).opened_by(&gear).show(ui, |ui, _| { + FieldGroup::new(words.arrowheads.clone()).labels(LabelScheme::Inspector).show(ui, |ui, _| { + edits = arrow_rows(ui, &words, &units, pixels_per_inch, current, |_| {}); + }); + }); + ArrowheadsOutput { response: gear, edits } } } + +/// The arrowhead rows of `value`, shared by the popover and the Shape panel: the Start and End check boxes, then Width +/// and Length, then whatever `after_length` adds (the panel's Weight), then Concavity. Each edit is the whole value with +/// its one field replaced. +pub(super) fn arrow_rows( + ui: &mut Ui, + words: &ShapeWords, + units: &Units, + pixels_per_inch: f64, + value: Arrowheads, + after_length: impl FnOnce(&mut Ui), +) -> Vec> { + let mut edits = Vec::new(); + let (mut start, mut end) = (EditEvents::new(), EditEvents::new()); + Row::new().show(ui, |ui, _| { + start = Checkbox::new(Bind::given(value.start)).label(words.arrow_start.clone()).show(ui).events; + end = Checkbox::new(Bind::given(value.end)).label(words.arrow_end.clone()).show(ui).events; + }); + edits.extend(start.map(|on| Arrowheads { start: on, ..value })); + edits.extend(end.map(|on| Arrowheads { end: on, ..value })); + let width = NumberCell::pixels(units, pixels_per_inch, "arrow-width", &words.arrow_width, value.width, Arrowheads::ARROW_SIZE).labelled(ui); + edits.extend(width.map(|width| Arrowheads { width, ..value })); + let length = + NumberCell::pixels(units, pixels_per_inch, "arrow-length", &words.arrow_length, value.length, Arrowheads::ARROW_SIZE).labelled(ui); + edits.extend(length.map(|length| Arrowheads { length, ..value })); + after_length(ui); + let concavity = + NumberCell::percent(units, "arrow-concavity", &words.arrow_concavity, value.concavity, Arrowheads::ARROW_CONCAVITY).labelled(ui); + edits.extend(concavity.map(|concavity| Arrowheads { concavity, ..value })); + edits +} diff --git a/crates/draw/src/ui/shape/bar.rs b/crates/draw/src/ui/shape/bar.rs index 7af58aedf..3c3df6c25 100644 --- a/crates/draw/src/ui/shape/bar.rs +++ b/crates/draw/src/ui/shape/bar.rs @@ -1,7 +1,7 @@ //! [`ShapeBar`]: the Shape tools' options bar cells. use super::panel::{Cells, ChipSetup, NumberCell, SIDES_RANGE, sides_change}; -use super::{ShapeAppearance, ShapeChange, ShapePaint, ShapeToolSettings, ShapeWords}; +use super::{LINE_WEIGHT_RANGE, RADIUS_RANGE, ShapeAppearance, ShapeChange, ShapePaint, ShapeToolSettings, ShapeWords, StrokeCells}; use crate::ui::shape_drag::ShapeKind; use craft_behavior::EditEvent; use craft_color::ui::{PaintChip, ScreenPickGesture}; @@ -34,13 +34,14 @@ pub struct ShapeBarOutput { /// The cells a Shape tool adds to the options bar, in PhotoCraft's order: the "Fill" check box and chip, the /// "Stroke" chip, the stroke width (0 to 288 px), the Stroke style button; then the kind's cell: Rectangle and -/// Rounded Rectangle "Radius" (0 to 10,000), Polygon and Star "Sides" (3 to 100), Line "Weight" (1 to 1,000). A +/// Rounded Rectangle "Radius" (0 to 150,000), Polygon and Star "Sides" (3 to 100), Line "Weight" (1 to 10,000). A /// pattern shown as children of a `Bar`. /// /// - The values are the selected shape layer's when one is selected, else the tool settings' (the app passes the /// right [`ShapeAppearance`]). /// - Stroke width 0 is no stroke; an edit that turns the stroke on at 0 carries /// [`ShapeChange::ENABLED_STROKE_WIDTH`] in the same change. +/// - [`paint(false)`](Self::paint) leaves out the Fill check box, both chips and the stroke cells; the kind's cell stays. /// - Keyboard: every cell is a Tab stop in the bar's order; captions scrub their fields. #[must_use = "show the cells with `show`"] #[derive(craft_ui::contract::Pattern)] @@ -106,38 +107,43 @@ impl<'a> ShapeBar<'a> { /// Adds the cells to the bar's row `ui`. pub fn show(self, ui: &mut Ui) -> ShapeBarOutput { let ShapeBar { kind, settings, appearance, stroke_open, chips, fallbacks, sampled, pixels_per_inch, paint } = self; - let _ = paint; // P3(tools-w8): tl.T28 let env = Env::of(ui); let (words, units) = (env.words::(), env.units()); let mut pass = Cells::new(&words, &units, pixels_per_inch, appearance, fallbacks, sampled, chips); - pass.open = stroke_open; + let mut stroke_open = stroke_open; + let mut out_of_range = None; Row::new().enabled(!appearance.locked).show(ui, |ui, _| { + // The body may run more than once in a pass; each run starts clean. pass.begin(); - let fill_on = !matches!(appearance.fill, craft_color::ui::Paint::None); - let check = Checkbox::new(Bind::given(fill_on)).label(words.fill.clone()).show(ui).events; - pass.events.extend(check.map(ShapeChange::FillOn)); - let hidden = SideLabel::new().kind(LabelKind::Hidden); - let fill = Field::new(words.fill_color.clone()) - .id_salt("fill") - .side(hidden.clone()) - .sizing(Sizing::Content) - .show(ui, |ui, _| pass.chip(ui, ShapePaint::Fill)); - if let Some(out) = fill.inner { - pass.take_chip(ShapePaint::Fill, out); + out_of_range = None; + if paint { + let fill_on = !matches!(appearance.fill, craft_color::ui::Paint::None); + let check = Checkbox::new(Bind::given(fill_on)).label(words.fill.clone()).show(ui).events; + pass.events.extend(check.map(ShapeChange::FillOn)); + let hidden = SideLabel::new().kind(LabelKind::Hidden); + let fill = Field::new(words.fill_color.clone()) + .id_salt("fill") + .side(hidden) + .sizing(Sizing::Content) + .show(ui, |ui, _| pass.chip(ui, ShapePaint::Fill)); + if let Some(out) = fill.inner { + pass.take_chip(ShapePaint::Fill, out); + } + let stroke = + Field::new(words.stroke.clone()).id_salt("stroke").sizing(Sizing::Content).show(ui, |ui, _| pass.chip(ui, ShapePaint::Stroke)); + if let Some(out) = stroke.inner { + pass.take_chip(ShapePaint::Stroke, out); + } + let mut cells = StrokeCells::new(appearance, pixels_per_inch).corners(kind != ShapeKind::Ellipse); + if let Some(open) = stroke_open.as_mut() { + cells = cells.stroke_open(open.reborrowed()); + } + let events = cells.show(ui); + pass.events.extend(events); } - let stroke = - Field::new(words.stroke.clone()).id_salt("stroke").sizing(Sizing::Content).show(ui, |ui, _| pass.chip(ui, ShapePaint::Stroke)); - if let Some(out) = stroke.inner { - pass.take_chip(ShapePaint::Stroke, out); - } - let width = pass.width_cell(); - let event = - Field::new(width.caption.clone()).id_salt(width.key).side(hidden).sizing(Sizing::Content).show(ui, |ui, _| width.show(ui)).inner; - pass.take_width(event.unwrap_or_default()); - pass.style_button(ui, kind != ShapeKind::Ellipse); let cell = match kind { ShapeKind::Rectangle | ShapeKind::RoundedRectangle => Some(( - NumberCell::pixels(&units, pixels_per_inch, "radius", &words.radius, settings.corner_radius, super::RADIUS_RANGE), + NumberCell::pixels(&units, pixels_per_inch, "radius", &words.radius, settings.corner_radius, RADIUS_RANGE), ShapeChange::CornerRadius as fn(f64) -> ShapeChange, )), ShapeKind::Polygon | ShapeKind::Star => Some(( @@ -145,7 +151,7 @@ impl<'a> ShapeBar<'a> { sides_change as fn(f64) -> ShapeChange, )), ShapeKind::Line => Some(( - NumberCell::pixels(&units, pixels_per_inch, "weight", &words.weight, settings.line_weight, super::LINE_WEIGHT_RANGE), + NumberCell::pixels(&units, pixels_per_inch, "weight", &words.weight, settings.line_weight, LINE_WEIGHT_RANGE), ShapeChange::Weight as fn(f64) -> ShapeChange, )), _ => None, @@ -153,18 +159,12 @@ impl<'a> ShapeBar<'a> { if let Some((cell, change)) = cell { Divider::vertical().show(ui); let side = SideLabel::new().scrub(true); - let event = - Field::new(cell.caption.clone()).id_salt(cell.key).side(side).sizing(Sizing::Content).show(ui, |ui, _| cell.show(ui)).inner; - pass.events.extend(event.unwrap_or_default().map(change)); + let (events, alert) = + Field::new(cell.caption.clone()).id_salt(cell.key).side(side).sizing(Sizing::Content).show(ui, |ui, _| cell.show(ui)).inner.unwrap_or_default(); + pass.events.extend(events.map(change)); + out_of_range = alert; } }); - ShapeBarOutput { events: pass.events, screen_pick: pass.screen_pick, pick_color: None, out_of_range: None } + ShapeBarOutput { events: pass.events, screen_pick: pass.screen_pick, pick_color: pass.pick_color, out_of_range } } } - -/// The largest corner radius of the bar's Radius cell, in pixels. -#[allow(dead_code)] // P3(tools-w8): tl.T27 -const RADIUS_MAX: f64 = 10_000.0; -/// The largest weight of the bar's Line cell, in pixels. -#[allow(dead_code)] // P3(tools-w8): tl.T27 -const LINE_WEIGHT_MAX: f64 = 1_000.0; diff --git a/crates/draw/src/ui/shape/mod.rs b/crates/draw/src/ui/shape/mod.rs index 1bbfbbabe..6bc13edea 100644 --- a/crates/draw/src/ui/shape/mod.rs +++ b/crates/draw/src/ui/shape/mod.rs @@ -49,9 +49,9 @@ pub struct Arrowheads { pub start: bool, /// An arrowhead at the end. pub end: bool, - /// The head's width as a percentage of the line weight. + /// The head's width in document pixels. pub width: f64, - /// The head's length as a percentage of the line weight. + /// The head's length in document pixels. pub length: f64, /// The head's concavity in percent. pub concavity: f64, @@ -59,10 +59,8 @@ pub struct Arrowheads { impl Arrowheads { /// The range of the width and length fields, in document pixels (production and engine units). - // P3(tools-w8): tl.T27 production units pub const ARROW_SIZE: RangeInclusive = 1.0..=4096.0; /// The range of the concavity field, in percent. - // P3(tools-w8): tl.T27 production units pub const ARROW_CONCAVITY: RangeInclusive = 0.0..=100.0; /// No arrowheads at the default size. @@ -266,7 +264,7 @@ pub struct ShapeToolSettings { pub corner_radius: f64, /// A polygon's sides or a star's points. pub sides: u32, - /// A star's inner over outer radius; 1 for a plain polygon. + /// A star's inner over outer radius. pub star_ratio: f64, /// The Line's weight. pub line_weight: f64, @@ -277,14 +275,14 @@ pub struct ShapeToolSettings { } impl Default for ShapeToolSettings { - /// Fill on, square corners, 5 sides, a plain polygon, weight 3, no stroke (PhotoCraft's - /// `ToolOptions::default`, `state/tool_options.rs:405-412`). + /// Fill on, square corners, 5 sides, a star ratio of 0.5 (production's Star), weight 3, no stroke, no + /// arrowheads. fn default() -> Self { ShapeToolSettings { fill_on: true, corner_radius: 0.0, sides: 5, - star_ratio: 1.0, + star_ratio: 0.5, line_weight: 3.0, stroke_width: 0.0, arrowheads: Arrowheads::default(), diff --git a/crates/draw/src/ui/shape/mode_select.rs b/crates/draw/src/ui/shape/mode_select.rs index 12a256267..3d7024e7e 100644 --- a/crates/draw/src/ui/shape/mode_select.rs +++ b/crates/draw/src/ui/shape/mode_select.rs @@ -1,7 +1,9 @@ //! [`VectorModeSelect`]: the Shape, Path and Pixels mode choice of the vector tools. -use super::VectorMode; -use craft_ui::contract::{Bind, EditResponse}; +use super::{ShapeWords, VectorMode}; +use craft_ui::contract::{Bind, Entry, EditResponse, Show as _}; +use craft_ui::pickers::Select; +use craft_ui::runtime::env::Env; use egui::Ui; /// The mode select of the vector tools' bars; a mode in `offered` with `false` shows disabled. @@ -21,7 +23,18 @@ impl<'a> VectorModeSelect<'a> { /// Shows the select and reports the picked mode. pub fn show(self, ui: &mut Ui) -> EditResponse { let VectorModeSelect { mode, offered } = self; - let _ = (ui, mode, offered); - todo!("tl.T29") + let words = Env::of(ui).words::(); + let entries: Vec> = offered + .iter() + .map(|&(offered_mode, enabled)| { + let label = match offered_mode { + VectorMode::Shape => &words.shape_mode, + VectorMode::Path => &words.path_mode, + VectorMode::Pixels => &words.pixels_mode, + }; + Entry::new(offered_mode, label.clone()).enabled(enabled) + }) + .collect(); + Select::new(words.mode.clone(), mode, &entries).show(ui) } } diff --git a/crates/draw/src/ui/shape/panel.rs b/crates/draw/src/ui/shape/panel.rs index d3a897651..212e65e42 100644 --- a/crates/draw/src/ui/shape/panel.rs +++ b/crates/draw/src/ui/shape/panel.rs @@ -3,18 +3,20 @@ use std::ops::RangeInclusive; -use super::{LiveShape, RADIUS_RANGE, ShapeAppearance, ShapeChange, ShapeWords}; -use crate::ui::stroke::StrokeButton; +use super::arrowheads::arrow_rows; +use super::stroke_cells::{style_button, take_width, width_cell}; +use super::{LINE_WEIGHT_RANGE, LiveShape, RADIUS_RANGE, ShapeAppearance, ShapeChange, ShapeWords}; use craft_behavior::{EditEvent, EditEvents, NumberCodec}; use craft_color::ui::{Paint, PaintChip, PaintChipOutput, ScreenPickGesture}; use craft_theme::Srgba; +use craft_ui::choice::Checkbox; use craft_ui::contract::{Bind, GlyphLabel, LabelKind, LabelScheme, Props as _, Show as _, ShowContainer as _, SideLabel}; use craft_ui::form::{Field, FieldGroup}; use craft_ui::layout_components::Row; use craft_ui::runtime::env::{Env, Label, LengthUnits, UnitKind, Units, with_env}; use craft_ui::runtime::requests::ColorRequest; use craft_ui::sections::Section; -use craft_ui::text::NumberField; +use craft_ui::text::{NumberField, RangeAlert}; use egui::Ui; /// Which paint a chip edits, for [`ShapePanel::chips`] and [`ShapeBar::chips`](super::ShapeBar::chips). @@ -58,9 +60,11 @@ pub struct ShapePanelOutput { /// [`stroke_open`](Self::stroke_open)). Stroke width 0 is no stroke; an edit that turns a stroke on at 0 carries /// [`ShapeChange::ENABLED_STROKE_WIDTH`] in the same change; an arrow step that clamps at 0 reports nothing. /// - Shape (a collapsible section), by the [`LiveShape`]: W and H (1 to 300,000 px, whole pixels) for a rect, -/// ellipse or polygon; a rect's "Corner radius" (0 to 100,000, sets all four) then Top Left, Top Right, Bottom +/// ellipse or polygon; a rect's "Corner radius" (0 to 150,000, sets all four) then Top Left, Top Right, Bottom /// Left, Bottom Right rows (PhotoCraft's row order, mapped to the radii order TL, TR, BR, BL); a polygon's Corner -/// radius, Sides (3 to 100) and Star ratio (1 to 100 %, stored 0.01 to 1); a line's Weight (1 to 10,000). +/// radius, Sides (3 to 100) and Star ratio (1 to 100 %, stored 0.01 to 1); a line's Weight (1 to 10,000), and with +/// arrowheads its Start and End check boxes, Width, Length and Concavity, then the "Set as default" check box +/// ([`arrow_default`](Self::arrow_default)). /// - A locked layer ([`ShapeAppearance::locked`]) disables the whole panel. /// - Keyboard: every field and chip is a Tab stop in reading order; sections fold with their title rows. Right to /// left the rows mirror; the corner names stay. @@ -136,8 +140,7 @@ impl<'a> ShapePanel<'a> { /// Adds the sections to `ui` and reports the changed fields. pub fn show(self, ui: &mut Ui) -> ShapePanelOutput { - let ShapePanel { label, shape, appearance, stroke_open, chips, fallbacks, sections, sampled, pixels_per_inch, arrow_default } = self; - let _ = arrow_default; // P3(tools-w8): tl.T28 + let ShapePanel { label, shape, appearance, stroke_open, chips, fallbacks, sections, sampled, pixels_per_inch, mut arrow_default } = self; let env = Env::of(ui); let (words, units) = (env.words::(), env.units()); let mut pass = Cells::new(&words, &units, pixels_per_inch, appearance, fallbacks, sampled, chips); @@ -154,7 +157,7 @@ impl<'a> ShapePanel<'a> { }); } if sections.1 { - Section::new(words.shape.clone()).id_salt("liveShape").show(ui, |ui, _| pass.shape_rows(ui, shape)); + Section::new(words.shape.clone()).id_salt("liveShape").show(ui, |ui, _| pass.shape_rows(ui, shape, arrow_default.as_mut())); } }); }; @@ -163,7 +166,7 @@ impl<'a> ShapePanel<'a> { } else { body(ui); } - ShapePanelOutput { events: pass.events, screen_pick: pass.screen_pick, pick_color: None } + ShapePanelOutput { events: pass.events, screen_pick: pass.screen_pick, pick_color: pass.pick_color } } } @@ -235,10 +238,19 @@ impl NumberCell { field.range(self.range.clone()).codec(self.codec.clone()) } - /// The edit of the field shown in `ui`; an emptied field keeps the value. - pub fn show(&self, ui: &mut Ui) -> EditEvents { + /// The edit of the field shown in `ui` and the alert of a typed value that was clamped; an emptied field keeps the + /// value. + pub fn show(&self, ui: &mut Ui) -> (EditEvents, Option) { let kept = self.value; - self.field().scrub_by_label().show(ui).edit.events.map(|value| value.unwrap_or(kept)) + let out = self.field().scrub_by_label().show(ui); + let alert = out.out_of_range; + (out.edit.events.map(|value| value.unwrap_or(kept)), alert) + } + + /// The field in a row under its caption, which scrubs it: the edit of the field. + pub fn labelled(&self, ui: &mut Ui) -> EditEvents { + let side = SideLabel::new().scrub(true); + Field::new(self.caption.clone()).id_salt(self.key).side(side).show(ui, |ui, _| self.show(ui).0).inner.unwrap_or_default() } } @@ -260,6 +272,7 @@ pub(super) struct Cells<'p, 'a> { pub(super) open: Option>, pub events: Vec>, pub screen_pick: Option<(ShapePaint, ScreenPickGesture)>, + pub pick_color: Option<(ShapePaint, ColorRequest)>, } impl<'p, 'a> Cells<'p, 'a> { @@ -272,13 +285,26 @@ impl<'p, 'a> Cells<'p, 'a> { sampled: Option<(ShapePaint, Srgba)>, chips: Option>, ) -> Self { - Cells { words, units, pixels_per_inch, appearance, fallbacks, sampled, chips, open: None, events: Vec::new(), screen_pick: None } + Cells { + words, + units, + pixels_per_inch, + appearance, + fallbacks, + sampled, + chips, + open: None, + events: Vec::new(), + screen_pick: None, + pick_color: None, + } } /// Starts a run of the body: it may run more than once in a pass, and each run starts clean. pub fn begin(&mut self) { self.events.clear(); self.screen_pick = None; + self.pick_color = None; } /// The paint chip of `which`, decorated by the app's setup. @@ -297,11 +323,14 @@ impl<'p, 'a> Cells<'p, 'a> { chip.show(ui) } - /// Takes a chip's output: its edit as a change, its eyedropper press. + /// Takes a chip's output: its edit as a change, its eyedropper press and its full colour picker request. pub fn take_chip(&mut self, which: ShapePaint, out: PaintChipOutput) { if let Some(gesture) = out.screen_pick { self.screen_pick = Some((which, gesture)); } + if let Some(request) = out.pick_color { + self.pick_color = Some((which, request)); + } for event in out.edit.events { let paints = match &event { EditEvent::Set { after, .. } => !matches!(after, Paint::None), @@ -335,58 +364,21 @@ impl<'p, 'a> Cells<'p, 'a> { } } - /// The stroke width cell: 0 to 288 px. - pub fn width_cell(&self) -> NumberCell { - NumberCell::pixels( - self.units, - self.pixels_per_inch, - "stroke-width", - &self.words.stroke_width, - self.appearance.stroke_width, - 0.0..=STROKE_WIDTH_MAX, - ) - } - - /// Takes the stroke width field's event. An arrow step that stays at 0 changes nothing, so it adds no stroke. - pub fn take_width(&mut self, events: EditEvents) { - for event in events { - let unchanged = matches!(&event, EditEvent::Set { after, .. } | EditEvent::Update { value: after, .. } if *after <= 0.0 && self.appearance.stroke_width <= 0.0); - if !unchanged { - self.events.push(event.map(ShapeChange::StrokeWidth)); - } - } - } - fn width_row(&mut self, ui: &mut Ui) { - let cell = self.width_cell(); - let side = SideLabel::new().scrub(true); - let events = Field::new(cell.caption.clone()).id_salt(cell.key).side(side).show(ui, |ui, _| cell.show(ui)).inner.unwrap_or_default(); - self.take_width(events); - } - - /// The Stroke style button over the appearance's stroke style, when the app gave the popover's open flag. It is - /// off while the width is 0; a pick then also carries the stroke's width in the same change. - pub fn style_button(&mut self, ui: &mut Ui, corners: bool) { - let off = self.appearance.stroke_width <= 0.0; - let Some(open) = self.open.as_mut() else { return }; - let style = Bind::given(self.appearance.stroke_style.clone()); - let button = StrokeButton::new(self.words.stroke_style.clone(), style, open.reborrowed()).corners(corners).stroked(!off).enabled(!off); - for event in button.show(ui).events { - let width = (off && matches!(event, EditEvent::Set { .. } | EditEvent::Begin { .. })).then_some(ShapeChange::ENABLED_STROKE_WIDTH); - self.events.push(event.map(|style| ShapeChange::StrokeStyle { style, width })); - } + let cell = width_cell(self.words, self.units, self.pixels_per_inch, self.appearance); + let events = cell.labelled(ui); + take_width(self.appearance, events, &mut self.events); } fn style_row(&mut self, ui: &mut Ui, corners: bool) { - if self.open.is_some() { - Field::new(self.words.stroke_style.clone()).id_salt("stroke-style").show(ui, |ui, _| self.style_button(ui, corners)); - } + let Some(open) = self.open.as_mut() else { return }; + let (words, appearance, events) = (self.words, self.appearance, &mut self.events); + Field::new(words.stroke_style.clone()).id_salt("stroke-style").show(ui, |ui, _| style_button(ui, words, appearance, open, corners, events)); } /// A labelled row with `cell`; its edit goes out through `change`. fn number_row(&mut self, ui: &mut Ui, cell: NumberCell, change: impl Fn(f64) -> ShapeChange) { - let side = SideLabel::new().scrub(true); - let events = Field::new(cell.caption.clone()).id_salt(cell.key).side(side).show(ui, |ui, _| cell.show(ui)).inner.unwrap_or_default(); + let events = cell.labelled(ui); self.events.extend(events.map(&change)); } @@ -402,7 +394,7 @@ impl<'p, 'a> Cells<'p, 'a> { Row::new().fill_width().show(ui, |ui, _| { for ((cell, glyph), edit) in cells.iter().zip(glyphs).zip(edits.iter_mut()) { let side = SideLabel::new().kind(LabelKind::Glyph(GlyphLabel::text(glyph.clone()))).scrub(true); - *edit = Field::new(cell.caption.clone()).id_salt(cell.key).side(side).show(ui, |ui, _| cell.show(ui)).inner.unwrap_or_default(); + *edit = Field::new(cell.caption.clone()).id_salt(cell.key).side(side).show(ui, |ui, _| cell.show(ui).0).inner.unwrap_or_default(); } }); let [w, h] = edits; @@ -411,7 +403,7 @@ impl<'p, 'a> Cells<'p, 'a> { } /// The Shape section's rows for `shape`. - fn shape_rows(&mut self, ui: &mut Ui, shape: &LiveShape) { + fn shape_rows(&mut self, ui: &mut Ui, shape: &LiveShape, arrow_default: Option<&mut Bind<'_, bool>>) { let (units, ppi, words) = (self.units, self.pixels_per_inch, self.words); match shape { LiveShape::Rect { width, height, radii } => { @@ -445,9 +437,22 @@ impl<'p, 'a> Cells<'p, 'a> { let ratio = NumberCell::percent(units, "star-ratio", &words.star_ratio, star_ratio * 100.0, RATIO_PERCENT); self.number_row(ui, ratio, |percent| ShapeChange::StarRatio(percent / 100.0)); } - LiveShape::Line { weight, .. } => { - let cell = NumberCell::pixels(units, ppi, "weight", &words.weight, *weight, super::LINE_WEIGHT_RANGE); - self.number_row(ui, cell, ShapeChange::Weight); + LiveShape::Line { weight, arrows } => { + let cell = NumberCell::pixels(units, ppi, "weight", &words.weight, *weight, LINE_WEIGHT_RANGE); + match arrows { + None => self.number_row(ui, cell, ShapeChange::Weight), + Some(arrows) => { + // PhotoCraft's order puts the weight between the head's length and its concavity. + let edits = arrow_rows(ui, words, units, ppi, *arrows, |ui| self.number_row(ui, cell, ShapeChange::Weight)); + self.events.extend(edits.into_iter().map(|edit| edit.map(ShapeChange::Arrowheads))); + if let Some(link) = arrow_default { + let _ = Checkbox::new(link.reborrowed()) + .label(words.set_as_default.clone()) + .tooltip(words.set_as_default_tip.clone()) + .show(ui); + } + } + } } } } @@ -458,13 +463,8 @@ pub(super) fn sides_change(sides: f64) -> ShapeChange { ShapeChange::Sides(sides.round().clamp(*SIDES_RANGE.start(), *SIDES_RANGE.end()) as u32) } -/// The largest stroke width in pixels. -const STROKE_WIDTH_MAX: f64 = 288.0; /// The range of a shape's width and height in whole pixels. const SIZE_RANGE: RangeInclusive = 1.0..=300_000.0; -/// The range of a corner radius in pixels. -#[allow(dead_code)] // P3(tools-w8): tl.T27 -const RADIUS_RANGE_OLD: RangeInclusive = 0.0..=100_000.0; /// The number of sides of a polygon or points of a star. pub(super) const SIDES_RANGE: RangeInclusive = 3.0..=100.0; /// The star ratio in percent. diff --git a/crates/draw/src/ui/shape/stories.rs b/crates/draw/src/ui/shape/stories.rs index 07cd9cca0..ae6404360 100644 --- a/crates/draw/src/ui/shape/stories.rs +++ b/crates/draw/src/ui/shape/stories.rs @@ -1,7 +1,10 @@ //! Stories of the shape panel and the options bar. A fake shape layer (a `LiveShape` and a `ShapeAppearance`) stands //! for the document, and the panel and the bar edit it as an app does: each field's change is applied to the fake. -use super::{LiveShape, ShapeAppearance, ShapeBar, ShapeChange, ShapePanel, ShapeToolSettings}; +use super::{ + Arrowheads, ArrowheadsPopover, LiveShape, ShapeAppearance, ShapeBar, ShapeChange, ShapePanel, ShapeToolSettings, StrokeCells, VectorMode, + VectorModeSelect, +}; use crate::ui::shape_drag::ShapeKind; use craft_behavior::EditEvent; use craft_color::ui::Paint; @@ -47,6 +50,7 @@ fn apply(change: ShapeChange, shape: &mut LiveShape, look: &mut ShapeAppearance) (ShapeChange::Sides(next), LiveShape::Polygon { sides, .. }) => *sides = next, (ShapeChange::StarRatio(next), LiveShape::Polygon { star_ratio, .. }) => *star_ratio = next, (ShapeChange::Weight(next), LiveShape::Line { weight, .. }) => *weight = next, + (ShapeChange::Arrowheads(next), LiveShape::Line { arrows, .. }) => *arrows = Some(next), _ => {} } } @@ -67,8 +71,13 @@ fn panel(ui: &mut Ui, data: &mut StoryData, start: LiveShape) -> StoryOutput { let shape = data.value("shape", start).clone(); let appearance = data.value("look", look()).clone(); let mut open = *data.value("open", false); - let out = ShapePanel::new("Shape properties", &shape, &appearance, DOCUMENT_PIXELS_PER_INCH).stroke_open(Bind::bound(&mut open)).show(ui); + let mut linked = *data.value("linked", false); + let out = ShapePanel::new("Shape properties", &shape, &appearance, DOCUMENT_PIXELS_PER_INCH) + .stroke_open(Bind::bound(&mut open)) + .arrow_default(Bind::bound(&mut linked)) + .show(ui); *data.value("open", false) = open; + *data.value("linked", false) = linked; let (mut next, mut next_look) = (shape, appearance); apply_all(out.events, &mut next, &mut next_look); *data.value("shape", rectangle()) = next; @@ -91,12 +100,21 @@ fn shape_panel_line(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { panel(ui, data, LiveShape::line(3.0)) } -fn bar(ui: &mut Ui, data: &mut StoryData, kind: ShapeKind) -> StoryOutput { +#[story(ShapePanel<'static>, covers = [Default], drive = Drive::Never)] +fn shape_panel_arrow_line(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let mut arrows = Arrowheads::new(); + arrows.end = true; + panel(ui, data, LiveShape::arrow_line(3.0, arrows)) +} + +fn bar(ui: &mut Ui, data: &mut StoryData, kind: ShapeKind, paint: bool) -> StoryOutput { let settings = *data.value("settings", ShapeToolSettings::default()); let appearance = data.value("look", look()).clone(); let mut open = *data.value("open", false); let out = Bar::new("Shape options", BarKind::Options) - .show(ui, |ui, _| ShapeBar::new(kind, &settings, &appearance, DOCUMENT_PIXELS_PER_INCH).stroke_open(Bind::bound(&mut open)).show(ui)) + .show(ui, |ui, _| { + ShapeBar::new(kind, &settings, &appearance, DOCUMENT_PIXELS_PER_INCH).paint(paint).stroke_open(Bind::bound(&mut open)).show(ui) + }) .inner; *data.value("open", false) = open; let (mut shape, mut next_look) = (rectangle(), appearance); @@ -118,10 +136,62 @@ fn bar(ui: &mut Ui, data: &mut StoryData, kind: ShapeKind) -> StoryOutput { #[story(ShapeBar<'static>, covers = [Default], drive = Drive::Never)] fn shape_bar(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - bar(ui, data, ShapeKind::Rectangle) + bar(ui, data, ShapeKind::Rectangle, true) +} + +#[story(ShapeBar<'static>, covers = [Default], drive = Drive::Never)] +fn shape_bar_path_mode(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + bar(ui, data, ShapeKind::Rectangle, false) } #[story(ShapeBar<'static>, covers = [Default], drive = Drive::Never)] fn shape_bar_line(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - bar(ui, data, ShapeKind::Line) + bar(ui, data, ShapeKind::Line, true) +} + +#[story(StrokeCells<'static>, covers = [Default], drive = Drive::Never)] +fn stroke_cells(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + stroke_cells_with(ui, data, true) +} + +#[story(StrokeCells<'static>, covers = [Default], drive = Drive::Never)] +fn stroke_cells_ellipse(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + stroke_cells_with(ui, data, false) +} + +fn stroke_cells_with(ui: &mut Ui, data: &mut StoryData, corners: bool) -> StoryOutput { + let appearance = data.value("look", look()).clone(); + let mut open = *data.value("open", false); + let events = Bar::new("Stroke options", BarKind::Options) + .show(ui, |ui, _| StrokeCells::new(&appearance, DOCUMENT_PIXELS_PER_INCH).corners(corners).stroke_open(Bind::bound(&mut open)).show(ui)) + .inner + .unwrap_or_default(); + *data.value("open", false) = open; + let (mut shape, mut next_look) = (rectangle(), appearance); + apply_all(events, &mut shape, &mut next_look); + *data.value("look", look()) = next_look; + StoryOutput::default() +} + +#[story(ArrowheadsPopover<'static>, covers = [Default], drive = Drive::Never)] +fn arrowheads_popover_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let value = *data.value("arrows", Arrowheads::default()); + let mut open = *data.value("open", true); + let out = ArrowheadsPopover::new(Bind::given(value), Bind::bound(&mut open), DOCUMENT_PIXELS_PER_INCH).show(ui); + *data.value("open", true) = open; + if let Some(next) = out.edits.iter().rev().find_map(|event| event.value()) { + *data.value("arrows", Arrowheads::default()) = *next; + } + StoryOutput::default() +} + +#[story(VectorModeSelect<'static>, covers = [Default], drive = Drive::Never)] +fn vector_mode_select_greyed_pixels(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let mode = *data.value("mode", VectorMode::Shape); + let offered = [(VectorMode::Shape, true), (VectorMode::Path, true), (VectorMode::Pixels, false)]; + let out = VectorModeSelect::new(Bind::given(mode), &offered).show(ui); + if let Some(next) = out.value().copied() { + *data.value("mode", VectorMode::Shape) = next; + } + StoryOutput::default() } diff --git a/crates/draw/src/ui/shape/stroke_cells.rs b/crates/draw/src/ui/shape/stroke_cells.rs index ea4be2582..4d89c97be 100644 --- a/crates/draw/src/ui/shape/stroke_cells.rs +++ b/crates/draw/src/ui/shape/stroke_cells.rs @@ -1,13 +1,58 @@ -//! [`StrokeCells`]: the stroke width cell and the Stroke style button, shared by the Shape bar and the Pen tools' -//! Shape mode. +//! [`StrokeCells`]: the stroke width cell and the Stroke style button, shared by the Shape bar, the Appearance section +//! of the panel and the Pen tools' Shape mode. -use super::{ShapeAppearance, ShapeChange}; -use craft_behavior::EditEvent; -use craft_ui::contract::Bind; +use super::panel::NumberCell; +use super::{ShapeAppearance, ShapeChange, ShapeWords}; +use crate::ui::stroke::StrokeButton; +use craft_behavior::{EditEvent, EditEvents}; +use craft_ui::contract::{Bind, LabelKind, Props as _, Show as _, ShowContainer as _, SideLabel, Sizing}; +use craft_ui::form::Field; +use craft_ui::runtime::env::{Env, Units}; use egui::Ui; +/// The largest stroke width in pixels. +const STROKE_WIDTH_MAX: f64 = 288.0; + +/// The stroke width cell of `appearance`: 0 to 288 px. +pub(super) fn width_cell(words: &ShapeWords, units: &Units, pixels_per_inch: f64, appearance: &ShapeAppearance) -> NumberCell { + NumberCell::pixels(units, pixels_per_inch, "stroke-width", &words.stroke_width, appearance.stroke_width, 0.0..=STROKE_WIDTH_MAX) +} + +/// Adds the stroke width field's events to `out`. An arrow step that stays at 0 changes nothing, so it adds no stroke. +pub(super) fn take_width(appearance: &ShapeAppearance, events: EditEvents, out: &mut Vec>) { + for event in events { + let unchanged = matches!(&event, EditEvent::Set { after, .. } | EditEvent::Update { value: after, .. } if *after <= 0.0 && appearance.stroke_width <= 0.0); + if !unchanged { + out.push(event.map(ShapeChange::StrokeWidth)); + } + } +} + +/// Shows the Stroke style button over the appearance's stroke style and adds its events to `out`. It is off while the +/// width is 0; a pick then also carries the stroke's width in the same change. +pub(super) fn style_button( + ui: &mut Ui, + words: &ShapeWords, + appearance: &ShapeAppearance, + open: &mut Bind<'_, bool>, + corners: bool, + out: &mut Vec>, +) { + let off = appearance.stroke_width <= 0.0; + let style = Bind::given(appearance.stroke_style.clone()); + let button = StrokeButton::new(words.stroke_style.clone(), style, open.reborrowed()).corners(corners).stroked(!off).enabled(!off); + for event in button.show(ui).events { + let width = (off && matches!(event, EditEvent::Set { .. } | EditEvent::Begin { .. })).then_some(ShapeChange::ENABLED_STROKE_WIDTH); + out.push(event.map(|style| ShapeChange::StrokeStyle { style, width })); + } +} + /// The stroke width cell and the Stroke style button of a shape's stroke, as one pattern shown as children of a /// `Bar`. +/// +/// - The width is 0 to 288 px; 0 is no stroke, and an edit that turns the stroke on carries +/// [`ShapeChange::ENABLED_STROKE_WIDTH`]. +/// - The style button shows only with [`stroke_open`](Self::stroke_open) and is off while the width is 0. #[must_use = "show the cells with `show`"] #[derive(craft_ui::contract::Pattern)] pub struct StrokeCells<'a> { @@ -37,8 +82,17 @@ impl<'a> StrokeCells<'a> { /// Adds the cells to the bar's row `ui` and reports each change. pub fn show(self, ui: &mut Ui) -> Vec> { - let StrokeCells { appearance, pixels_per_inch, corners, stroke_open } = self; - let _ = (ui, appearance, pixels_per_inch, corners, stroke_open); - todo!("tl.T29") + let StrokeCells { appearance, pixels_per_inch, corners, mut stroke_open } = self; + let env = Env::of(ui); + let (words, units) = (env.words::(), env.units()); + let mut events = Vec::new(); + let cell = width_cell(&words, &units, pixels_per_inch, appearance); + let hidden = SideLabel::new().kind(LabelKind::Hidden); + let width = Field::new(cell.caption.clone()).id_salt(cell.key).side(hidden).sizing(Sizing::Content).show(ui, |ui, _| cell.show(ui).0).inner; + take_width(appearance, width.unwrap_or_default(), &mut events); + if let Some(open) = stroke_open.as_mut() { + style_button(ui, &words, appearance, open, corners, &mut events); + } + events } } diff --git a/crates/draw/src/ui/shape/words.rs b/crates/draw/src/ui/shape/words.rs index f7c5197e1..b62199d35 100644 --- a/crates/draw/src/ui/shape/words.rs +++ b/crates/draw/src/ui/shape/words.rs @@ -38,5 +38,29 @@ craft_ui::words! { weight: "shape.weight" = "Weight"; /// The options bar's corner radius cell. radius: "shape.radius" = "Radius"; + /// The vector mode select's accessible name. + mode: "shape.mode" = "Mode"; + /// The mode entry that draws a shape layer. + shape_mode: "shape.shapeMode" = "Shape"; + /// The mode entry that draws a path. + path_mode: "shape.pathMode" = "Path"; + /// The mode entry that draws filled pixels. + pixels_mode: "shape.pixelsMode" = "Pixels"; + /// The arrowhead popover's name and its button's accessible name. + arrowheads: "shape.arrowheads" = "Arrowheads"; + /// The check box for an arrowhead at the start. + arrow_start: "shape.arrowStart" = "Start"; + /// The check box for an arrowhead at the end. + arrow_end: "shape.arrowEnd" = "End"; + /// The arrowhead width field. + arrow_width: "shape.arrowWidth" = "Width"; + /// The arrowhead length field. + arrow_length: "shape.arrowLength" = "Length"; + /// The arrowhead concavity field. + arrow_concavity: "shape.arrowConcavity" = "Concavity"; + /// The check box that makes the arrowhead values the defaults of new arrows. + set_as_default: "shape.setAsDefault" = "Set as default"; + /// The tooltip of that check box. + set_as_default_tip: "shape.setAsDefaultTip" = "Use these settings for new arrows"; } } diff --git a/crates/draw/src/ui/shape_drag/tool.rs b/crates/draw/src/ui/shape_drag/tool.rs index 85617c886..4ee333c9a 100644 --- a/crates/draw/src/ui/shape_drag/tool.rs +++ b/crates/draw/src/ui/shape_drag/tool.rs @@ -126,9 +126,8 @@ impl ShapeDragTool { } /// The shape of the last `Update` while a drag has begun; `None` otherwise. - // P3(tools-w8): tl.P2 decision (tools-w33), `ShapeDragTool::shape` pub fn shape(&self) -> Option<&ShapeGeometry> { - todo!("tools-w8") + self.drag.as_ref().filter(|drag| drag.began).and_then(|drag| drag.shape.as_ref()) } /// The events since the last call, in order. @@ -147,7 +146,6 @@ impl ShapeDragTool { /// Star with the options' sides and ratio, Custom a `Custom` box keeping proportions with ⇧), /// [`line_drag`] for a Line (weight at least 1, ⇧ turning the end to 45° steps), and /// [`RadialFrame::drag`] in the radial frame. - // P3(tools-w8): renamed from `shape` for the public `ShapeDragTool::shape` (plan error, fixed) fn shape_of(&self, drag: &Drag, mods: Mods) -> Option { // pc: crates/ui-egui/src/tools/vector_ui/shapes.rs:50-82 `shape_geometry`. // inv-vectorcraft: crates/tools/src/shape.rs:131-145 (the radial kinds). diff --git a/crates/draw/tests/it/corner.rs b/crates/draw/tests/it/corner.rs new file mode 100644 index 000000000..fef95148d --- /dev/null +++ b/crates/draw/tests/it/corner.rs @@ -0,0 +1,62 @@ +//! The corner widgets' drag reports its edit on the pass that commits it. + +use craft_behavior::CanvasView; +use craft_behavior::kurbo::Point; +use craft_draw::ui::corner::{CornerPoint, CornerTarget}; +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 egui::vec2; +use std::cell::RefCell; +use std::rc::Rc; + +const START_RADIUS: f64 = 4.0; + +struct Host { + targets: Vec, + /// Per pass: whether it carried a `Commit`, and the `change` it reported. + passes: Vec<(bool, Option)>, +} + +fn square() -> CornerTarget { + let vertices = [Point::new(130.0, 150.0), Point::new(290.0, 150.0), Point::new(290.0, 250.0), Point::new(130.0, 250.0)]; + let corners = (0..4) + .map(|i| CornerPoint::new(vertices[i], vertices[(i + 3) % 4], vertices[(i + 1) % 4], START_RADIUS, CornerKind::Round)) + .collect(); + CornerTarget::new(1, corners, true) +} + +#[trial] +fn a_drag_reports_its_change_on_the_commit_pass() { + let host = Rc::new(RefCell::new(Host { targets: vec![square()], passes: Vec::new() })); + let shown = Rc::clone(&host); + let mut fixture = Fixture::new(move |ui| { + let mut held = shown.borrow_mut(); + let st = &mut *held; + let room = ui.available_rect_before_wrap(); + let view = CanvasView::new(room, Point::new(210.0, 200.0), 1.0); + let canvas = Canvas::new("Document") + .view(view) + .show(ui, |ui, body| CornerWidgets::new("Corner radius", Bind::bound(&mut st.targets)).show_at(ui, body.rect)); + let Some(out) = canvas.inner else { return }; + let committed = out.edit.events.iter().any(|event| matches!(EditKind::of(event), Some(EditKind::Commit))); + st.passes.push((committed, out.change)); + }); + fixture.settle(); + let widget = fixture.by_label("Corner 1 of 4").expect("the first corner has a widget"); + // Toward the inside of the corner: the radius grows. + fixture.drag(&widget, vec2(30.0, 30.0)); + + let held = host.borrow(); + let commits: Vec<&Option> = held.passes.iter().filter(|(committed, _)| *committed).map(|(_, change)| change).collect(); + assert!(!commits.is_empty(), "the drag committed"); + for change in &commits { + assert!(change.is_some(), "the commit pass reports the edit"); + } + let change = commits.last().and_then(|change| change.as_ref()).expect("a commit with a change"); + let reported = change.targets.first().and_then(|target| target.radii.first()).copied().expect("the change names the first corner"); + let taken = held.targets[0].corners[0].radius; + assert!(taken > START_RADIUS, "the drag rounded the corner"); + assert_eq!(reported, taken, "the reported change is the last move the targets took"); +} diff --git a/crates/draw/tests/it/main.rs b/crates/draw/tests/it/main.rs index b47ed446f..96666b200 100644 --- a/crates/draw/tests/it/main.rs +++ b/crates/draw/tests/it/main.rs @@ -2,6 +2,8 @@ // draw-shape mod add_beside; +mod corner; +mod shape_cells; // draw-gradient-b mod gradient_fill; diff --git a/crates/draw/tests/it/shape_cells.rs b/crates/draw/tests/it/shape_cells.rs new file mode 100644 index 000000000..8b364cec7 --- /dev/null +++ b/crates/draw/tests/it/shape_cells.rs @@ -0,0 +1,100 @@ +//! The arrowhead rows: one builder behind the popover and the Shape panel. + +use craft_behavior::EditEvent; +use craft_color::ui::Paint; +use craft_draw::ui::{Arrowheads, ArrowheadsPopover, LiveShape, ShapeAppearance, ShapeChange, ShapePanel}; +use craft_ui::contract::{Bind, Show as _}; +use craft_ui::testing::{Fixture, trial}; +use egui::vec2; +use std::cell::RefCell; +use std::rc::Rc; + +fn start_value() -> Arrowheads { + let mut arrows = Arrowheads::new(); + arrows.start = true; + arrows.end = true; + arrows.width = 6.0; + arrows.length = 12.0; + arrows.concavity = 25.0; + arrows +} + +/// A scrub of Width is one gesture, `Begin` to `Commit`, and every value it carries is the whole `from` with only the +/// width replaced; the gesture ends on another width. +fn assert_width_scrub(events: &[EditEvent], whole: impl Fn(&T) -> Option, from: Arrowheads, source: &str) { + assert!(matches!(events.first(), Some(EditEvent::Begin { .. })), "{source}: the scrub begins"); + assert!(matches!(events.last(), Some(EditEvent::Commit { .. })), "{source}: the scrub commits"); + let mut last = None; + for event in events { + let Some(value) = event.value() else { continue }; + let arrows = whole(value).unwrap_or_else(|| panic!("{source}: every event carries the whole Arrowheads")); + assert_eq!((arrows.start, arrows.end), (from.start, from.end), "{source}: the ends stay"); + assert_eq!((arrows.length, arrows.concavity), (from.length, from.concavity), "{source}: length and concavity stay"); + last = Some(arrows); + } + let last = last.unwrap_or_else(|| panic!("{source}: the scrub reports a value")); + assert_ne!(last.width, from.width, "{source}: the width moved"); +} + +struct PopoverHost { + value: Arrowheads, + open: bool, + events: Vec>, +} + +struct PanelHost { + shape: LiveShape, + look: ShapeAppearance, + events: Vec>, +} + +#[trial] +fn an_arrowhead_row_scrub_reports_the_whole_value_from_the_popover_and_the_panel() { + // The open popover. + let host = Rc::new(RefCell::new(PopoverHost { value: start_value(), open: false, events: Vec::new() })); + let shown = Rc::clone(&host); + let mut fixture = Fixture::new(move |ui| { + let mut held = shown.borrow_mut(); + let PopoverHost { value, open, events } = &mut *held; + let out = ArrowheadsPopover::new(Bind::given(*value), Bind::bound(open), 72.0).show(ui); + for event in out.edits { + if let Some(next) = event.value() { + *value = *next; + } + events.push(event); + } + }); + fixture.settle(); + host.borrow_mut().open = true; + fixture.idle(3); + let width = fixture.by_label("Width").expect("the open popover shows the Width field"); + fixture.drag(&width, vec2(40.0, 0.0)); + assert_width_scrub(&host.borrow().events, |value| Some(*value), start_value(), "popover"); + + // The panel on a line with arrowheads. + let host = Rc::new(RefCell::new(PanelHost { + shape: LiveShape::arrow_line(3.0, start_value()), + look: ShapeAppearance::new(Paint::None, Paint::None, 2.0), + events: Vec::new(), + })); + let shown = Rc::clone(&host); + let mut fixture = Fixture::new(move |ui| { + let mut held = shown.borrow_mut(); + let PanelHost { shape, look, events } = &mut *held; + let out = ShapePanel::new("Shape properties", shape, look, 72.0).show(ui); + for event in out.events { + if let Some(ShapeChange::Arrowheads(next)) = event.value() { + *shape = LiveShape::arrow_line(3.0, *next); + } + events.push(event); + } + }); + fixture.settle(); + let width = fixture.by_label("Width").expect("the panel shows the arrowhead Width field"); + fixture.drag(&width, vec2(40.0, 0.0)); + let whole = |change: &ShapeChange| match change { + ShapeChange::Arrowheads(arrows) => Some(*arrows), + _ => None, + }; + assert_width_scrub(&host.borrow().events, whole, start_value(), "panel"); +}