Live tool stories: tool_story keeps the tool and the document it edits across passes and runs the tool on a canvas over the story picture; the selection tool stories run on it with a selection of combined shapes that starts round the house, the marquee kind and style and the magnetic options as story values, and a status line; the mock Move tool moves the current layer with MoveGesture

This commit is contained in:
aiongg
2026-11-12 14:32:42 +00:00
parent 523d6687ea
commit 64d03f8ef9
11 changed files with 697 additions and 141 deletions
+6 -1
View File
@@ -77,7 +77,7 @@ impl MoveValue {
/// A Move-tool drag in progress: the press, whether ⌥ was held at it, and the last locked
/// offset. The tool keeps it between events and drops it after [`release`](Self::release) or on
/// cancel.
#[derive(Clone, Debug)]
#[derive(Clone, Debug, PartialEq)]
pub struct MoveGesture {
start: Point,
directions: Directions,
@@ -119,6 +119,11 @@ impl MoveGesture {
self.value
}
/// The direction ⇧ holds the offset to, as the last locked offset; `None` while the move is free.
pub fn locked(&self) -> Option<Vec2> {
self.locked
}
/// The value at `at`, updating the remembered lock; `copy` stays on once on.
fn value_at(&mut self, at: Point, mods: Mods, zoom: f64) -> MoveValue {
let d = at - self.start;
+283 -100
View File
@@ -1,50 +1,73 @@
//! Stories of the selection tools: one per tool, on a canvas over the mock picture, run by `ToolHost::run` as an app
//! does. The events each tool reports are applied to a story selection (a rectangle in the hard coverage a marquee or
//! outline gives), which the selection overlay shows. The first press inside the selection drags it.
//! Stories of the selection tools: one per tool, run live on a canvas over the mock picture by the tool story host,
//! as an app runs them. The events each tool reports are applied to the story selection: the shapes the tools
//! committed, combined in order by their operations (so Shift adds and Alt subtracts) and moved by the selection
//! drags, which the selection overlay shows. It starts as a rectangle round the picture's house, so the first press
//! inside it drags it. The Magnetic Lasso's tracer follows the house's outline where its contrast is strong enough.
use craft_behavior::EditEvent;
use craft_behavior::kurbo::{Point, Rect, Size};
use craft_ui::canvas::{Canvas, CanvasOutput, RasterSource as _, ToolHost};
use craft_ui::contract::ShowContainer as _;
use craft_behavior::geometry::{Constraint, SelectionOperation};
use craft_behavior::kurbo::{Point, Rect, Vec2};
use craft_behavior::{CanvasView, EditEvent};
use craft_ui::canvas::RasterSource as _;
use craft_ui::runtime::env::Env;
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
use craft_ui::testing::{Drive, StoryData, StoryHost, StoryOutput, ToolStory, story, tool_story};
use egui::Ui;
use std::sync::{Arc, Mutex};
use super::{
EdgeSearch, EdgeTracer, LassoTool, MagneticLassoTool, MarqueeKind, MarqueeTool, PolygonLassoTool, SelectEvent, SelectToolPass, SelectionProbe,
SelectionShape,
EdgeSearch, EdgeTracer, LassoTool, MagneticLassoTool, MarqueeKind, MarqueeTool, PolygonLassoTool, SelectEvent, SelectPhase, SelectToolPass,
SelectionProbe, SelectionShape,
};
use crate::trace::{MaskRect, MaskSource};
use crate::ui::mock_image::{MockImage, StoryView};
use crate::ui::mock_image::MockImage;
use crate::ui::selection::SelectionOverlay;
craft_ui::words! {
/// The captions of the selection tool stories.
/// The captions and the status line of the selection tool stories.
#[non_exhaustive]
pub(crate) struct SelectToolStoryWords {
/// The name of the selection overlay.
selection: "selectToolStory.selection" = "Selection";
/// The status line under the picture: the tool's phase and the last event it reported.
status: template "selectToolStory.status" = "{phase}. Last event: {event}.";
/// Nothing under way.
idle: "selectToolStory.idle" = "Idle";
/// A marquee being dragged.
marquee: "selectToolStory.marquee" = "Dragging a marquee";
/// An outline being drawn.
outline: "selectToolStory.outline" = "Drawing an outline";
/// The selection being dragged.
dragging: "selectToolStory.dragging" = "Dragging the selection";
/// No event so far.
no_event: "selectToolStory.noEvent" = "none yet";
/// A shape was selected.
selected: "selectToolStory.selected" = "Selected";
/// A click deselected.
deselected: "selectToolStory.deselected" = "Deselected";
/// The selection was dragged.
dragged: "selectToolStory.dragged" = "Dragged the selection";
}
}
/// A tool a story runs, with the events it reports.
trait Shown: Send + 'static {
fn run(&mut self, ui: &Ui, canvas: &CanvasOutput, probe: &dyn SelectionProbe);
/// A selection tool a story runs: its pass for the host, its events and its phase.
trait Shown: 'static {
fn run(&mut self, host: &StoryHost<'_>, probe: &dyn SelectionProbe);
fn take(&mut self) -> Vec<SelectEvent>;
fn phase(&self) -> SelectPhase;
}
macro_rules! shown {
($tool:ty $(, $param:ident: $bound:path)?) => {
impl$(<$param: $bound + Send + 'static>)? Shown for $tool {
fn run(&mut self, ui: &Ui, canvas: &CanvasOutput, probe: &dyn SelectionProbe) {
let mut pass = SelectToolPass::new(self, probe);
let _ = ToolHost::new().run(ui, canvas, &mut pass);
impl$(<$param: $bound + 'static>)? Shown for $tool {
fn run(&mut self, host: &StoryHost<'_>, probe: &dyn SelectionProbe) {
let _ = host.run(&mut SelectToolPass::new(self, probe));
}
fn take(&mut self) -> Vec<SelectEvent> {
self.take_events()
}
fn phase(&self) -> SelectPhase {
<$tool>::phase(self)
}
}
};
}
@@ -54,62 +77,146 @@ shown!(LassoTool);
shown!(PolygonLassoTool);
shown!(MagneticLassoTool<T>, T: EdgeTracer);
/// A tool held across the passes of a story; clones share it.
struct Held(Arc<Mutex<Box<dyn Shown>>>);
impl Clone for Held {
fn clone(&self) -> Self {
Held(Arc::clone(&self.0))
}
/// What a story keeps of its tool: the tool and the kind of the last event it reported.
struct Kept<T> {
tool: T,
last: Option<Last>,
}
impl PartialEq for Held {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
/// The kind of event the status line names.
#[derive(Clone, Copy, Debug)]
enum Last {
Selected,
Deselected,
Dragged,
}
/// The story's selection: a rectangle, or nothing.
/// The story selection: shapes combined in order by their operations, then moved by `offset`. It is the tools'
/// [`SelectionProbe`] and the overlay's [`MaskSource`].
#[derive(Clone, Debug, PartialEq)]
struct Selection(Option<Rect>);
/// The selection as the probe and the overlay's mask see it.
struct RectMask {
rect: Option<Rect>,
struct Selection {
size: [u32; 2],
parts: Vec<(SelectionOperation, SelectionShape)>,
offset: Vec2,
revision: u64,
}
impl RectMask {
fn pixels(&self) -> Option<MaskRect> {
self.rect.map(|rect| MaskRect::new(rect.x0.floor() as i32, rect.y0.floor() as i32, rect.x1.ceil() as i32, rect.y1.ceil() as i32))
impl Selection {
/// A rectangle round the picture's house.
fn house(image: &MockImage) -> Self {
let b = image.subject_bounds();
let rect = Rect::new(f64::from(b.x0), f64::from(b.y0), f64::from(b.x1), f64::from(b.y1));
let size = image.size();
Selection {
size: [size.width, size.height],
parts: vec![(SelectionOperation::New, SelectionShape::Rectangle(rect))],
offset: Vec2::ZERO,
revision: 1,
}
}
/// Applies what a tool reported, as an app does; returns the kind of the last event.
fn apply(&mut self, events: Vec<SelectEvent>) -> Option<Last> {
let mut last = None;
for event in events {
match event {
SelectEvent::Commit { shape, operation } => {
if operation == SelectionOperation::New {
self.parts.clear();
self.offset = Vec2::ZERO;
}
self.parts.push((operation, shape));
last = Some(Last::Selected);
}
SelectEvent::Deselect => {
self.parts.clear();
self.offset = Vec2::ZERO;
last = Some(Last::Deselected);
}
SelectEvent::DragSelection(EditEvent::Commit { after, .. }) => {
self.offset += Vec2::new(f64::from(after.delta[0]), f64::from(after.delta[1]));
last = Some(Last::Dragged);
}
SelectEvent::DragSelection(_) => continue,
}
self.revision += 1;
}
last
}
/// The coverage at the document point `p`: 0 or 1, the hard coverage a marquee or an outline gives.
fn coverage(&self, p: Point) -> f32 {
let p = p - self.offset;
self.parts.iter().fold(0.0, |acc, (operation, shape)| {
let c = f32::from(inside(shape, p));
match operation {
SelectionOperation::Add => acc.max(c),
SelectionOperation::Subtract => acc * (1.0 - c),
SelectionOperation::Intersect => acc.min(c),
_ => c,
}
})
}
}
impl MaskSource for RectMask {
/// Whether `p` is inside `shape`: an outline by the even-odd rule.
fn inside(shape: &SelectionShape, p: Point) -> bool {
match shape {
SelectionShape::Rectangle(r) => r.x0 <= p.x && p.x < r.x1 && r.y0 <= p.y && p.y < r.y1,
SelectionShape::Ellipse(r) => {
let (c, rx, ry) = (r.center(), r.width() / 2.0, r.height() / 2.0);
rx > 0.0 && ry > 0.0 && ((p.x - c.x) / rx).powi(2) + ((p.y - c.y) / ry).powi(2) <= 1.0
}
SelectionShape::Polygon(points) => {
let mut inside = false;
for (i, a) in points.iter().enumerate() {
let b = points[(i + 1) % points.len()];
if (a.y > p.y) != (b.y > p.y) && p.x < a.x + (p.y - a.y) / (b.y - a.y) * (b.x - a.x) {
inside = !inside;
}
}
inside
}
}
}
/// The document rectangle `shape` covers.
fn bounds(shape: &SelectionShape) -> Rect {
match shape {
SelectionShape::Rectangle(r) | SelectionShape::Ellipse(r) => *r,
SelectionShape::Polygon(points) => {
let first = points.first().copied().unwrap_or(Point::ZERO);
points.iter().fold(Rect::from_points(first, first), |rect, &p| rect.union_pt(p))
}
}
}
impl MaskSource for Selection {
fn size(&self) -> [u32; 2] {
self.size
}
fn revision(&self) -> u64 {
self.rect.map_or(0, |rect| {
rect.x0.to_bits() ^ rect.y0.to_bits().rotate_left(16) ^ rect.x1.to_bits().rotate_left(32) ^ rect.y1.to_bits().rotate_left(48)
})
self.revision
}
fn content_bounds(&self) -> MaskRect {
self.pixels().unwrap_or(MaskRect::new(0, 0, 0, 0))
let grown = self.parts.iter().filter(|(operation, _)| !matches!(operation, SelectionOperation::Subtract | SelectionOperation::Intersect));
match grown.map(|(_, shape)| bounds(shape) + self.offset).reduce(|a, b| a.union(b)) {
Some(r) => MaskRect::new(r.x0.floor() as i32, r.y0.floor() as i32, r.x1.ceil() as i32, r.y1.ceil() as i32),
None => MaskRect::new(0, 0, 0, 0),
}
}
fn read_row(&self, y: i32, x0: i32, step: u32, out: &mut [f32]) {
let bounds = self.content_bounds();
for (index, value) in out.iter_mut().enumerate() {
let x = x0 + i32::try_from(index as u32 * step).unwrap_or(i32::MAX);
*value = if (bounds.x0..bounds.x1).contains(&x) && (bounds.y0..bounds.y1).contains(&y) { 1.0 } else { 0.0 };
let x = f64::from(x0) + (index as f64) * f64::from(step);
*value = self.coverage(Point::new(x + 0.5, f64::from(y) + 0.5));
}
}
}
impl SelectionProbe for RectMask {
impl SelectionProbe for Selection {
fn document(&self) -> u64 {
1
}
@@ -119,84 +226,160 @@ impl SelectionProbe for RectMask {
}
fn has_selection(&self) -> bool {
self.rect.is_some()
!self.parts.is_empty()
}
fn inside_selection(&self, at: Point) -> bool {
self.rect.is_some_and(|rect| rect.contains(at))
self.coverage(at) > 0.0
}
}
/// Edges at the picture's house: the tracer snaps to the selection's rectangle where it is near.
struct Edges;
impl EdgeTracer for Edges {
fn snap(&mut self, _: Point, _: EdgeSearch) -> Option<Point> {
None
}
fn trace(&mut self, from: Point, to: Point, _: &[Point], _: EdgeSearch) -> Vec<Point> {
vec![from, to]
}
/// An [`EdgeTracer`] over the picture: the edges are the house's outline, and an edge counts where the brightness
/// across it differs by at least the search's contrast.
struct PictureEdges {
image: MockImage,
}
/// Applies what the tool reported to the story selection.
fn apply(selection: &mut Selection, events: Vec<SelectEvent>) {
for event in events {
match event {
SelectEvent::Commit { shape: SelectionShape::Rectangle(rect) | SelectionShape::Ellipse(rect), .. } => selection.0 = Some(rect),
SelectEvent::Commit { shape: SelectionShape::Polygon(points), .. } => {
let first = points.first().copied().unwrap_or_default();
selection.0 = Some(points.iter().fold(Rect::from_points(first, first), |rect, &p| rect.union_pt(p)));
}
SelectEvent::Deselect => selection.0 = None,
SelectEvent::DragSelection(EditEvent::Commit { after, .. }) => {
let delta = (f64::from(after.delta[0]), f64::from(after.delta[1]));
selection.0 = selection.0.map(|rect| rect + craft_behavior::kurbo::Vec2::new(delta.0, delta.1));
}
SelectEvent::DragSelection(_) => {}
impl PictureEdges {
/// How far either side of the outline the brightness is compared, as a share of the picture's width.
const PROBE: f64 = 0.002;
fn luma(&self, p: Point) -> f64 {
let [r, g, b, _] = self.image.pixel(p.x, p.y);
(0.299 * f64::from(r) + 0.587 * f64::from(g) + 0.114 * f64::from(b)) / 255.0
}
/// The outline's unit normal at `p`, pointing out of the house.
fn normal(&self, p: Point) -> Vec2 {
let d = |dx: f64, dy: f64| self.image.subject_distance(p.x + dx, p.y + dy);
let g = Vec2::new(d(1.0, 0.0) - d(-1.0, 0.0), d(0.0, 1.0) - d(0.0, -1.0));
if g.hypot() > 0.0 { g / g.hypot() } else { Vec2::new(0.0, -1.0) }
}
/// The point of the outline nearest `p`; `None` beyond the search's width or where the edge is weaker than its
/// contrast.
fn edge_near(&self, p: Point, search: EdgeSearch) -> Option<Point> {
let mut q = p;
for _ in 0..4 {
q -= self.normal(q) * self.image.subject_distance(q.x, q.y);
}
let reach = Self::PROBE * f64::from(self.image.size().width);
let n = self.normal(q);
let contrast = (self.luma(q + n * reach) - self.luma(q - n * reach)).abs();
((q - p).hypot() <= search.width && contrast >= search.contrast).then_some(q)
}
}
/// Runs the tool `name` on a canvas over the mock picture, with the story selection drawn by the overlay.
fn on_canvas(ui: &mut Ui, data: &mut StoryData, name: &'static str, init: fn() -> Box<dyn Shown>) -> StoryOutput {
let held = data.value(name, Held(Arc::new(Mutex::new(init())))).clone();
let selection = data.value("selection", Selection(Some(Rect::new(200.0, 150.0, 600.0, 450.0))));
let image = MockImage::default();
let size = image.size();
let room = craft_ui::testing::stage(ui);
let view = StoryView::Fit.of(room, size, ui.pixels_per_point());
let words = Env::of(ui).words::<SelectToolStoryWords>();
let mask = RectMask { rect: selection.0, size: [size.width, size.height] };
let document = Size::new(f64::from(size.width), f64::from(size.height));
let shown = Canvas::new("Document").document(document).view(view).show_at(ui, room, |ui, body| {
craft_ui::testing::canvas_story::show_document(ui, body.rect, &image);
SelectionOverlay::new(words.selection.clone(), &mask).show_at(ui, body.rect);
});
if let Ok(mut tool) = held.0.lock() {
tool.run(ui, &shown.output, &mask);
apply(selection, tool.take());
impl EdgeTracer for PictureEdges {
fn snap(&mut self, at: Point, search: EdgeSearch) -> Option<Point> {
self.edge_near(at, search)
}
StoryOutput::default()
fn trace(&mut self, from: Point, to: Point, _: &[Point], search: EdgeSearch) -> Vec<Point> {
// Walks the straight line a pixel at a time and pulls each sample onto the edge.
let steps = from.distance(to).ceil().max(1.0) as usize;
let mut path = vec![from];
for i in 1..steps {
let sample = from.lerp(to, i as f64 / steps as f64);
let point = self.edge_near(sample, search).unwrap_or(sample);
if path.last().is_none_or(|last| last.distance(point) >= 1.0) {
path.push(point);
}
}
path.push(to);
path
}
}
/// The status line: the tool's phase and the last event.
fn status(words: &SelectToolStoryWords, phase: SelectPhase, last: Option<Last>) -> String {
let phase = match phase {
SelectPhase::Marquee { .. } => &words.marquee,
SelectPhase::Outline { .. } => &words.outline,
SelectPhase::Dragging(_) => &words.dragging,
_ => &words.idle,
};
let event = match last {
None => &words.no_event,
Some(Last::Selected) => &words.selected,
Some(Last::Deselected) => &words.deselected,
Some(Last::Dragged) => &words.dragged,
};
craft_i18n::fmt(words.status.as_str(), &[("phase", phase.as_str()), ("event", event.as_str())])
}
/// Runs the tool `init` makes, set up each pass by `options`, live over the mock picture, with the story selection
/// drawn by the overlay.
fn on_canvas<T: Shown>(ui: &mut Ui, data: &mut StoryData, init: impl FnOnce() -> T, options: impl FnOnce(&mut T)) -> StoryOutput {
let image = MockImage::default();
let words = Env::of(ui).words::<SelectToolStoryWords>();
let overlay = |ui: &mut Ui, at: egui::Rect, _: &CanvasView, _: &mut Kept<T>, selection: &Selection| {
let _ = SelectionOverlay::new(words.selection.clone(), selection).show_at(ui, at);
};
let story = ToolStory::new("Document", &image).fit();
tool_story(
ui,
data,
story,
|| Kept { tool: init(), last: None },
Selection::house(&image),
overlay,
|run| {
options(&mut run.tool.tool);
run.tool.tool.run(&run.host, &*run.document);
if let Some(last) = run.document.apply(run.tool.tool.take()) {
run.tool.last = Some(last);
}
StoryOutput::default().readout(status(&words, run.tool.tool.phase(), run.tool.last))
},
)
}
#[story(SelectionOverlay<'static>, covers = [], drive = Drive::Never)]
fn marquee(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
on_canvas(ui, data, "marquee", || Box::new(MarqueeTool::new(MarqueeKind::Rectangle)))
let kinds = [
("Rectangular", MarqueeKind::Rectangle),
("Elliptical", MarqueeKind::Ellipse),
("Single Row", MarqueeKind::SingleRow),
("Single Column", MarqueeKind::SingleColumn),
];
let kind = *data.choice("kind", MarqueeKind::Rectangle, &kinds);
let styles = [("Normal", Constraint::Free), ("Fixed Ratio", Constraint::Ratio(4.0, 3.0)), ("Fixed Size", Constraint::Size(400.0, 300.0))];
let style = *data.choice("style", Constraint::Free, &styles);
on_canvas(
ui,
data,
|| MarqueeTool::new(kind),
|tool| {
tool.kind(kind).constraint(style);
},
)
}
#[story(SelectionOverlay<'static>, covers = [], drive = Drive::Never)]
fn lasso(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
on_canvas(ui, data, "lasso", || Box::new(LassoTool::new()))
on_canvas(ui, data, LassoTool::new, |_| {})
}
#[story(SelectionOverlay<'static>, covers = [], drive = Drive::Never)]
fn polygonal_lasso(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
on_canvas(ui, data, "polygon", || Box::new(PolygonLassoTool::new()))
on_canvas(ui, data, PolygonLassoTool::new, |_| {})
}
#[story(SelectionOverlay<'static>, covers = [], drive = Drive::Never)]
fn magnetic_lasso(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
on_canvas(ui, data, "magnetic", || Box::new(MagneticLassoTool::new(Edges)))
let width = *data.ranged("width", 10.0_f32, 1.0..=256.0);
let contrast = *data.ranged("contrast", 10.0_f32, 1.0..=100.0);
let frequency = *data.ranged("frequency", 57.0_f32, 0.0..=100.0);
on_canvas(
ui,
data,
|| MagneticLassoTool::new(PictureEdges { image: MockImage::default() }),
|tool| {
let settings = tool.settings_mut();
settings.width = width;
settings.contrast = contrast;
settings.frequency = frequency;
},
)
}
+128 -16
View File
@@ -1,21 +1,133 @@
//! The story host of canvas tools: a tool is no component, so its story shows it on a canvas over the story document.
//! The story host of canvas tools: a tool is no component, so its story runs it live on a canvas over a document the
//! story keeps, as an app runs it.
use crate::canvas::{Canvas, CanvasTool, ToolHost};
use crate::canvas::{Canvas, CanvasOutput, CanvasTool, RasterSource, ToolHost, ToolHostResponse};
use crate::contract::ShowContainer as _;
use crate::testing::{StoryOutput, stage};
use egui::Ui;
use crate::testing::{StoryData, StoryOutput, stage};
use craft_behavior::kurbo::{Point, Size};
use craft_behavior::{CanvasView, Value};
use egui::{Rect, Ui};
use std::cell::RefCell;
use std::rc::Rc;
/// Shows `tool` on a canvas named `label` over the [`stage`] of `ui` and the story document, and runs it as the canvas's active tool. The
/// output is the canvas's, so the suite reads the nodes the tool and the canvas left. The story builds the tool
/// anew each pass: it shows the tool's idle state, and a gesture belongs in a trial on [`ToolFixture`](super::tool_fixture::ToolFixture).
///
/// The tool's type registers as a story host with `#[derive(Pattern)]` and `#[pattern(tool)]`.
pub fn tool_story(ui: &mut Ui, label: &'static str, tool: &mut dyn CanvasTool) -> StoryOutput {
/// The canvas a tool story shows: its name, the picture under the document, and the view of it.
pub struct ToolStory<'a> {
label: &'static str,
picture: &'a dyn RasterSource,
view: StoryZoom,
/// The view's rotation in degrees, its mirroring and its pixel aspect.
turn: (f64, bool, f64),
}
/// How a tool story's view shows its picture.
#[derive(Clone, Copy, Debug)]
enum StoryZoom {
/// The document point at the canvas's middle, at a percent ([`story_view`](super::canvas_story::story_view)).
At(Point, f64),
/// The whole picture fits the canvas, centred.
Fit,
}
impl<'a> ToolStory<'a> {
/// A canvas named `label` over `picture` (shown on the story document's ground), at 100 % centred on the picture.
pub fn new(label: &'static str, picture: &'a dyn RasterSource) -> Self {
let size = picture.size();
let centre = Point::new(f64::from(size.width) / 2.0, f64::from(size.height) / 2.0);
ToolStory { label, picture, view: StoryZoom::At(centre, 100.0), turn: (0.0, false, 1.0) }
}
/// The same canvas with the document point `centre` at its middle at `percent`
/// ([`story_view`](super::canvas_story::story_view)).
#[must_use]
pub fn view(mut self, centre: Point, percent: f64) -> Self {
self.view = StoryZoom::At(centre, percent);
self
}
/// The same canvas with the whole picture fitted to it, centred.
#[must_use]
pub fn fit(mut self) -> Self {
self.view = StoryZoom::Fit;
self
}
/// The same canvas with its view turned `rotation` degrees clockwise, mirrored when `flip_x`, with the pixel
/// aspect `aspect`.
#[must_use]
pub fn turned(mut self, rotation: f64, flip_x: bool, aspect: f64) -> Self {
self.turn = (rotation, flip_x, aspect);
self
}
fn view_of(&self, room: Rect, pixels_per_point: f32) -> CanvasView {
let size = self.picture.size();
let (width, height) = (f64::from(size.width.max(1)), f64::from(size.height.max(1)));
let (centre, percent) = match self.view {
StoryZoom::At(centre, percent) => (centre, percent),
StoryZoom::Fit => {
let points_per_pixel = (f64::from(room.width()) / width).min(f64::from(room.height()) / height);
(Point::new(width / 2.0, height / 2.0), points_per_pixel * f64::from(pixels_per_point) * 100.0)
}
};
let mut view = super::canvas_story::story_view(room, pixels_per_point, centre, percent);
(view.rotation, view.flip_x, view.aspect) = self.turn;
view
}
}
/// One pass of a tool story, after the canvas showed: the kept tool, the kept document, what the body's controls
/// reported, and the host that runs a tool on this pass's canvas.
#[non_exhaustive]
pub struct ToolRun<'a, T, D, R> {
/// The tool, kept across passes.
pub tool: &'a mut T,
/// The document the tool edits, kept across passes as the story's value `"document"`.
pub document: &'a mut D,
/// What the body returned in the drawing pass: the outputs of the document's canvas controls.
pub shown: Option<R>,
/// The view the canvas showed.
pub view: CanvasView,
/// Runs a tool on the canvas.
pub host: StoryHost<'a>,
}
/// The tool host of a tool story's canvas for one pass.
pub struct StoryHost<'a> {
ui: &'a Ui,
canvas: &'a CanvasOutput,
}
impl StoryHost<'_> {
/// Runs `tool` as the canvas's active tool, as an app's [`ToolHost::run`] does.
pub fn run(&self, tool: &mut dyn CanvasTool) -> ToolHostResponse {
ToolHost::new().run(self.ui, self.canvas, tool)
}
}
/// Shows a tool live on the canvas `story` over the stage of `ui`. The tool `tool` makes is kept as a note of `data`
/// (a note: Reset and the runner's drives compare values, and a tool's state in a gesture is no value); `document`
/// is kept as the value `"document"`, so Reset puts it back. Each pass `body` shows the document's canvas controls at
/// the canvas rect from the tool and the document (a tool whose pass shows its own controls shows them here), and `run` runs the tool through [`ToolRun::host`] and applies what it reported
/// to the document, as the app does, returning the story's output with its readout.
pub fn tool_story<T: 'static, D: Value, R>(
ui: &mut Ui,
data: &mut StoryData,
story: ToolStory<'_>,
tool: impl FnOnce() -> T,
document: D,
mut body: impl FnMut(&mut Ui, Rect, &CanvasView, &mut T, &D) -> R,
run: impl FnOnce(ToolRun<'_, T, D, R>) -> StoryOutput,
) -> StoryOutput {
let kept = Rc::clone(data.note::<Option<Rc<RefCell<T>>>>("tool", None).get_or_insert_with(|| Rc::new(RefCell::new(tool()))));
let document = data.value("document", document);
let room = stage(ui);
let document = &super::canvas_story::StoryDocument::STANDARD;
let shown = Canvas::new(label)
.view(document.view(room, ui.pixels_per_point(), 100.0))
.show_at(ui, room, |ui, body| super::canvas_story::show_document(ui, body.rect, document));
let _ = ToolHost::new().run(ui, &shown.output, tool);
shown.output.into()
let view = story.view_of(room, ui.pixels_per_point());
let size = story.picture.size();
let canvas = Canvas::new(story.label).document(Size::new(f64::from(size.width), f64::from(size.height))).view(view);
let shown = canvas.show_at(ui, room, |ui, body_cx| {
super::canvas_story::show_document(ui, body_cx.rect, story.picture);
body(ui, body_cx.rect, &view, &mut kept.borrow_mut(), document)
});
let mut tool = kept.borrow_mut();
run(ToolRun { tool: &mut tool, document, shown: shown.inner, view, host: StoryHost { ui, canvas: &shown.output } })
}
+7 -3
View File
@@ -39,11 +39,15 @@ pub mod dialog {
pub use craft_ui_panels::dialog::*;
}
/// The fixture, the suite runner and the story helpers, with the canvas helpers: `ToolFixture`, `tool_story` and
/// `canvas_story`.
/// The fixture, the suite runner and the story helpers, with the canvas helpers: `ToolFixture`, the live tool story
/// host (`tool_story`) and `canvas_story`.
#[cfg(feature = "testing")]
pub mod testing {
pub use crate::canvas::testing::{canvas_story, tool_fixture, tool_fixture::ToolFixture, tool_story::tool_story};
pub use crate::canvas::testing::{
canvas_story, tool_fixture,
tool_fixture::ToolFixture,
tool_story::{StoryHost, ToolRun, ToolStory, tool_story},
};
pub use craft_ui_panels::testing::*;
crate::testing_registered!();
+2
View File
@@ -16,4 +16,6 @@ mod tool;
mod tool_keys;
mod tool_story;
mod tools;
@@ -0,0 +1,107 @@
//! The live tool story: the tool and the document it edits outlive the pass, so a gesture over several frames edits
//! the story's document, and Reset puts the document back while the tool stays.
use craft_behavior::kurbo::Point;
use craft_behavior::{CancelReason, PointerButton};
use craft_ui::canvas::{CanvasTool, ToolAction, ToolContext, ToolPath, ToolPointer};
use craft_ui::primitives::Draw;
use craft_ui::runtime::access::Role;
use craft_ui::testing::canvas_story::StoryDocument;
use craft_ui::testing::{Fixture, Story, StoryData, StoryOutput, ToolStory, pointer, tool_story, trial};
use egui::{Pos2, Vec2};
/// A tool that draws a line from the press to the release and reports each line it drew.
#[derive(Default)]
struct Liner {
start: Option<Point>,
drawn: Vec<(Point, Point)>,
}
impl CanvasTool for Liner {
fn press(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) -> ToolAction {
let Some(space) = cx.space() else { return ToolAction::Ignored };
self.start = Some(space.view.to_doc(pointer.pos));
ToolAction::Claimed
}
fn drag(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {}
fn release(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) {
if let (Some(start), Some(space)) = (self.start.take(), cx.space()) {
self.drawn.push((start, space.view.to_doc(pointer.pos)));
}
}
fn cancel(&mut self, _: CancelReason, _: &mut ToolContext<'_>) {
self.start = None;
}
fn takes(&self, button: PointerButton, _: craft_keymap::Mods) -> bool {
button == PointerButton::Primary
}
fn paint(&self, _: &Draw<'_>, _: &ToolContext<'_>) {}
fn command_form(&self) -> ToolPath {
ToolPath::Freehand("a story's line tool")
}
}
type Lines = Vec<(Point, Point)>;
fn show(ui: &mut egui::Ui, data: &mut StoryData) -> StoryOutput {
let picture = StoryDocument::STANDARD;
tool_story(
ui,
data,
ToolStory::new("Document", &picture),
Liner::default,
Lines::new(),
|_, _, _, _, _| (),
|run| {
let _ = run.host.run(run.tool);
run.document.append(&mut run.tool.drawn);
StoryOutput::default()
},
)
}
fn lines(fixture: &Fixture) -> Lines {
fixture.data().present::<Lines>("document").cloned().unwrap_or_default()
}
fn drag(fixture: &mut Fixture, from: Pos2, by: Vec2) {
fixture.frame(vec![pointer::moved(from)]);
fixture.frame(vec![pointer::press(from)]);
for step in 1..=4 {
fixture.frame(vec![pointer::moved(from + by * (step as f32 / 4.0))]);
}
fixture.frame(vec![pointer::release(from + by)]);
fixture.frame(Vec::new());
}
#[trial]
fn a_drag_over_several_frames_edits_the_kept_document_and_reset_puts_it_back() {
let mut fixture = Fixture::story(&Story::new("live tool", show));
fixture.settle();
let canvas = fixture.by_role(Role::CANVAS)[0].rect;
let before = fixture.data().snapshot();
drag(&mut fixture, canvas.center(), Vec2::new(60.0, 0.0));
let drawn = lines(&fixture);
assert_eq!(drawn.len(), 1, "a drag draws one line into the story's document: {drawn:?}");
assert!(drawn[0].1.x > drawn[0].0.x, "the line runs from the press towards the release: {drawn:?}");
fixture.idle(3);
assert_eq!(lines(&fixture), drawn, "later passes keep the document");
drag(&mut fixture, canvas.center() + Vec2::new(0.0, 40.0), Vec2::new(-50.0, 0.0));
assert_eq!(lines(&fixture).len(), 2, "a second drag adds to the document");
fixture.data().restore(&before);
fixture.idle(1);
assert!(lines(&fixture).is_empty(), "Reset puts the document back");
drag(&mut fixture, canvas.center(), Vec2::new(0.0, 50.0));
assert_eq!(lines(&fixture).len(), 1, "the kept tool draws again after Reset");
}
+1 -1
View File
@@ -11,4 +11,4 @@ mod words;
pub use commands::AppCommand;
pub use editor::EditorMock;
pub use model::{ColorPair, Document, Layer, LayerId, MarqueeDrag, MockState, Panel, Tool, ToolKey};
pub use model::{ColorPair, Document, Layer, LayerId, LayerMove, MarqueeDrag, MockState, Panel, Tool, ToolKey};
+44
View File
@@ -1,6 +1,7 @@
//! What the mock editor reads and edits: a tool, a layer list, a canvas view, a document title and a dirty flag.
use craft_behavior::dock::{Column, DockEdge, Group, Layout, Node, SplitSize, Workspace};
use craft_behavior::geometry::{MoveGesture, MoveValue};
use craft_behavior::kurbo::Rect as DocRect;
use craft_behavior::kurbo::{Point, Size};
use craft_behavior::{Axis, PixelSize};
@@ -207,6 +208,18 @@ impl MarqueeDrag {
}
}
/// A layer being moved with the Move tool: the layer, its bounds at the press, and the drag.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct LayerMove {
/// The moved layer.
pub layer: LayerId,
/// The layer's bounds at the press.
pub from: PixelRect,
/// The drag, with its Shift lock and Alt copy.
pub gesture: MoveGesture,
}
/// The open document.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
@@ -235,6 +248,8 @@ pub struct Document {
pub marquee: Option<DocRect>,
/// The marquee being dragged out.
pub dragging: Option<MarqueeDrag>,
/// The layer being moved.
pub moving: Option<LayerMove>,
/// Whether the rulers show.
pub rulers: bool,
/// The number the next layer gets as its identity.
@@ -264,6 +279,7 @@ impl Default for Document {
guide: None,
marquee: None,
dragging: None,
moving: None,
rulers: true,
next_layer: 3,
}
@@ -328,6 +344,34 @@ impl Document {
self.dirty = true;
}
/// Shows the layer `id` moved from `from` by `value`'s offset, rounded to whole pixels.
pub fn show_move(&mut self, id: LayerId, from: PixelRect, value: MoveValue) {
let (dx, dy) = (value.delta.x.round() as i32, value.delta.y.round() as i32);
if let Some(layer) = self.layers.iter_mut().find(|layer| layer.id == id) {
layer.bounds = PixelRect::new(from.x0 + dx, from.y0 + dy, from.x1 + dx, from.y1 + dy);
}
}
/// Ends the move of the layer `id` from `from` at `value`: the layer stays where it was moved, or with `copy` a
/// copy above it takes the moved place, becomes the current layer and the layer goes back. A move that changed
/// something marks the document changed.
pub fn end_move(&mut self, id: LayerId, from: PixelRect, value: MoveValue) {
self.show_move(id, from, value);
if !value.changed() {
return;
}
self.dirty = true;
let Some(at) = self.layers.iter().position(|layer| layer.id == id).filter(|_| value.copy) else { return };
let number = self.next_layer;
self.next_layer += 1;
let mut copy = self.layers[at].clone();
copy.id = LayerId(number);
copy.name = format!("{} copy", copy.name);
self.layers[at].bounds = from;
self.selected = Selection::single(copy.id);
self.layers.insert(at, copy);
}
/// Shows or hides the layer `id`, which marks the document changed.
pub fn set_visible(&mut self, id: LayerId, visible: bool) {
if let Some(layer) = self.layers.iter_mut().find(|layer| layer.id == id).filter(|layer| layer.visible != visible) {
+11 -5
View File
@@ -4,6 +4,7 @@ use super::model::{Document, Layer, Panel, Tool};
use super::tools::{MarqueeTool, MoveTool, Tools};
use super::words::MockWords;
use craft_behavior::dock::Permissions;
use craft_behavior::geometry::Directions;
use craft_behavior::kurbo::Rect as DocRect;
use craft_behavior::{ColumnKey, ColumnWidth, PixelSize, RulerUnits, Ticks, keyed};
use craft_ui::canvas::{
@@ -115,6 +116,14 @@ fn ruler_text(kind: UnitKind) -> RulerText {
RulerText::new(RulerUnits::new(per_doc, Ticks::decimal(kind == UnitKind::Pixels)), kind)
}
/// The visible layers of a document of `size` pixels, bottom first, at the canvas rect `at`.
pub(super) fn show_layers(ui: &mut Ui, at: egui::Rect, layers: &[Layer], size: PixelSize) {
for layer in layers.iter().rev().filter(|layer| layer.visible) {
let source = LayerFill { layer, size };
let _ = RasterDisplay::new(layer.name.clone(), &source).show_at(ui, at);
}
}
/// A layer as the raster display reads it: its colour over its bounds, transparent elsewhere.
struct LayerFill<'a> {
layer: &'a Layer,
@@ -170,10 +179,7 @@ fn canvas(ui: &mut Ui, document: &mut Document, tool: Tool, tools: &mut Tools) {
let Document { layers, guides, guide, marquee, zero, units: unit, .. } = &mut *document;
Canvas::new("Document").view(view).document(page.size()).show_rulers(show_rulers).rulers(units, units, *zero).show(ui, |ui, body| {
let _ = Pasteboard::new("Pasteboard", &pages).show_at(ui, body.rect);
for layer in layers.iter().rev().filter(|layer| layer.visible) {
let source = LayerFill { layer, size: pixels };
let _ = RasterDisplay::new(layer.name.clone(), &source).show_at(ui, body.rect);
}
show_layers(ui, body.rect, layers, pixels);
if let Some(rect) = *marquee {
let _ = Marquee::rect("Selection", rect).show_at(ui, body.rect);
}
@@ -206,7 +212,7 @@ fn canvas(ui: &mut Ui, document: &mut Document, tool: Tool, tools: &mut Tools) {
let reported = match tool {
Tool::Hand => host.run(ui, &shown.output, &mut tools.hand),
Tool::Zoom => host.run(ui, &shown.output, &mut tools.zoom),
Tool::Move => host.run(ui, &shown.output, &mut MoveTool),
Tool::Move => host.run(ui, &shown.output, &mut MoveTool::new(document, Directions::Four)),
Tool::Marquee => host.run(ui, &shown.output, &mut MarqueeTool::new(document)),
Tool::Brush | Tool::Pencil | Tool::Eraser | Tool::Stamp => host.run(ui, &shown.output, &mut NoTool),
};
+64 -5
View File
@@ -1,17 +1,76 @@
//! The story of the mock editor window.
//! The stories of the mock editor window and its Move tool.
use super::model::Document;
use super::panels::show_layers;
use super::tools::MoveTool;
use super::{EditorMock, MockState};
use craft_ui::testing::{Drive, StoryData, StoryOutput, story, tool_story};
use craft_behavior::geometry::Directions;
use craft_ui::runtime::env::Env;
use craft_ui::testing::canvas_story::StoryDocument;
use craft_ui::testing::{Drive, StoryData, StoryOutput, ToolStory, story, tool_story};
use egui::Ui;
craft_ui::words! {
/// The readout of the Move tool's story.
#[non_exhaustive]
pub(crate) struct MoveStoryWords {
/// No move runs.
idle: "moveStory.idle" = "Drag to move the current layer";
/// A move runs: `{lock}` is the direction Shift holds it to.
moving: template "moveStory.moving" = "Lock: {lock}";
/// A move of a copy runs: `{lock}` is the direction Shift holds it to.
copying: template "moveStory.copying" = "Lock: {lock} · Copy";
/// The move is free.
free: "moveStory.free" = "Free";
/// Shift holds the move level.
horizontal: "moveStory.horizontal" = "Horizontal";
/// Shift holds the move upright.
vertical: "moveStory.vertical" = "Vertical";
/// Shift holds the move on a diagonal.
diagonal: "moveStory.diagonal" = "Diagonal";
}
}
/// The view's zoom, in percent: the mock page fits a card.
const ZOOM: f64 = 50.0;
#[story(EditorMock<'static>, covers = [])]
fn editor_window(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let state = data.value("mock", MockState::default());
EditorMock::new("Editor", state).show(ui).into()
}
#[story(MoveTool, covers = [], drive = Drive::Never)]
fn move_tool(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
tool_story(ui, "Document", &mut MoveTool)
#[story(MoveTool<'static>, covers = [], drive = Drive::Never)]
fn move_tool(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let directions = *data.choice("directions", Directions::Four, &[("Layers", Directions::Four), ("Pixels", Directions::Eight)]);
let words = Env::of(ui).words::<MoveStoryWords>();
let document = Document::default();
let size = document.pixel_size();
let page = StoryDocument::new(size.width, size.height);
let story = ToolStory::new("Document", &page).view(page.centre(), ZOOM);
tool_story(
ui,
data,
story,
|| (),
document,
|ui, at, _, _, document| show_layers(ui, at, &document.layers, size),
|run| {
let _ = run.host.run(&mut MoveTool::new(run.document, directions));
StoryOutput::default().readout(readout(&words, run.document))
},
)
}
/// The lock and the copy flag of the move in progress.
fn readout(words: &MoveStoryWords, document: &Document) -> String {
let Some(moving) = &document.moving else { return words.idle.as_str().to_owned() };
let lock = match moving.gesture.locked() {
None => &words.free,
Some(d) if d.y == 0.0 => &words.horizontal,
Some(d) if d.x == 0.0 => &words.vertical,
Some(_) => &words.diagonal,
};
let template = if moving.gesture.value().copy { &words.copying } else { &words.moving };
craft_i18n::fmt(template.as_str(), &[("lock", lock.as_str())])
}
+44 -10
View File
@@ -1,7 +1,8 @@
//! The canvas tools of the mock: what the window keeps across passes in its root container, the Move tool and the
//! rectangular Marquee.
use super::model::{Document, MarqueeDrag};
use super::model::{Document, LayerMove, MarqueeDrag};
use craft_behavior::geometry::{ConstrainStyle, Directions, MoveGesture, MoveValue};
use craft_behavior::kurbo::{Point, Rect as DocRect};
use craft_behavior::{CancelReason, Cursor, CursorIcon};
use craft_ui::canvas::{CanvasTool, HandTool, Momentary, NavigationOptions, ToolAction, ToolContext, ToolKey, ToolPath, ToolPointer, ZoomTool};
@@ -24,25 +25,58 @@ impl Default for Tools {
}
}
/// The Move tool: it takes no press of its own (the guides over the canvas take theirs) and its command form is
/// moving the current layer.
/// The Move tool: a drag moves the current layer, Shift holds the move to `directions`, and Alt held at the press
/// moves a copy. The guides over the canvas take their own presses. Its command form is moving the current layer.
#[derive(Debug, craft_ui::contract::Pattern)]
#[pattern(tool)]
pub(super) struct MoveTool;
pub(super) struct MoveTool<'a> {
document: &'a mut Document,
directions: Directions,
}
impl CanvasTool for MoveTool {
fn press(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) -> ToolAction {
ToolAction::Ignored
impl<'a> MoveTool<'a> {
pub(super) fn new(document: &'a mut Document, directions: Directions) -> Self {
MoveTool { document, directions }
}
}
impl CanvasTool for MoveTool<'_> {
fn press(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) -> ToolAction {
let (Some(space), Some(layer)) = (cx.space(), self.document.current_layer().filter(|layer| layer.visible)) else {
return ToolAction::Ignored;
};
let style = ConstrainStyle::new(f64::from(cx.slop), f64::from(cx.slop));
let gesture = MoveGesture::press(&style, space.view.to_doc(pointer.pos), pointer.mods, self.directions);
self.document.moving = Some(LayerMove { layer: layer.id, from: layer.bounds, gesture });
ToolAction::Claimed
}
fn drag(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {}
fn drag(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) {
let (Some(space), Some(moving)) = (cx.space(), self.document.moving.as_mut()) else { return };
let Some(value) = moving.gesture.follow(space.view.to_doc(pointer.pos), pointer.mods, space.view.zoom) else { return };
let (layer, from) = (moving.layer, moving.from);
self.document.show_move(layer, from, value);
cx.readout(vec![(Label::from("X"), format!("{:.0}", value.delta.x)), (Label::from("Y"), format!("{:.0}", value.delta.y))]);
}
fn release(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {}
fn release(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) {
let (Some(space), Some(moving)) = (cx.space(), self.document.moving.take()) else { return };
let value = moving.gesture.release(space.view.to_doc(pointer.pos), pointer.mods, space.view.zoom);
self.document.end_move(moving.layer, moving.from, value);
}
fn cancel(&mut self, _: CancelReason, _: &mut ToolContext<'_>) {}
fn cancel(&mut self, _: CancelReason, _: &mut ToolContext<'_>) {
if let Some(moving) = self.document.moving.take() {
self.document.show_move(moving.layer, moving.from, MoveValue::default());
}
}
fn paint(&self, _: &Draw<'_>, _: &ToolContext<'_>) {}
fn cursor(&self, _: &ToolContext<'_>) -> Cursor {
Cursor::System(CursorIcon::Move)
}
fn command_form(&self) -> ToolPath {
ToolPath::Command("the Move Layer command")
}