mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-17 20:25:06 +00:00
canvas-widgets-w1: net change of 7 commits
- canvas-widgets-w1: written from its sheet - canvas-widgets-w1: repair 1 - canvas-widgets-w1: review fixes (review-1) - canvas-widgets-w1: review fixes (review-1), test compile fixes - canvas-widgets-w1: drags follow the pass's own moves (per-frame input rule) - canvas-widgets-w1: the run lends the tool and stand-ins for the pass only, so the host's state is free after it (combine) - canvas-widgets-w1: the stand-in cursor trial's selected tool refuses Command, and the claimed-chord trial gives the canvas focus back from the opener (fwcw round 3)
This commit is contained in:
@@ -69,7 +69,6 @@ mod momentary;
|
||||
mod navigate;
|
||||
mod rotate;
|
||||
mod tools;
|
||||
mod zoom_field;
|
||||
mod zoom_motion;
|
||||
|
||||
pub use momentary::{Momentary, MomentaryCommands, MomentaryTool};
|
||||
@@ -100,22 +99,23 @@ pub use navigator::NavigatorStyle;
|
||||
pub mod navigator_panel;
|
||||
|
||||
use crate::contract::{
|
||||
Bind, Common, Component, Container, ContainerProps, Cx, Focus as _, NoValue, Outcome, PartsCx, Pointer as _, Props as _, Role, Sizing,
|
||||
Bind, Common, Component, Container, ContainerProps, Cx, Focus as _, NoValue, Outcome, PaintUi, PartsCx, Pointer as _, Props as _, Role, Sizing,
|
||||
};
|
||||
use crate::runtime::commands::{CommandSet as _, CommandState, Commands as _};
|
||||
use crate::runtime::env::Label;
|
||||
use crate::runtime::focus::KeyUse;
|
||||
use crate::runtime::motion::{Animate as _, spec};
|
||||
use crate::style::{ComponentStyle, StyleCx, SurfaceKind};
|
||||
use craft_behavior::geometry::crop::normalized_angle;
|
||||
use craft_behavior::kurbo::{Point, Rect as DocRect, Size};
|
||||
use craft_behavior::{
|
||||
CanvasTransform, CanvasView, EditEvent, HitLevel, HitPriority, Intent, Metrics, Mixed, PartKey, PointerButton, PressPhase, PressState, Sense,
|
||||
WheelNotch,
|
||||
};
|
||||
use egui::{Pos2, Rect, Response, Vec2};
|
||||
use egui::{Pos2, Rect, Response, Shape, Vec2};
|
||||
use zoom_motion::{Steer, ViewMotion};
|
||||
|
||||
const BACKGROUND: PartKey = PartKey::new("background");
|
||||
pub(crate) const BACKGROUND: PartKey = PartKey::new("background");
|
||||
|
||||
/// Why the background part is pointer-only: the keyboard path of the running tool is its command form
|
||||
/// ([`CanvasTool::command_form`]), the one owner of that fact.
|
||||
@@ -176,9 +176,10 @@ pub struct Canvas<'a> {
|
||||
keys_to_body: bool,
|
||||
/// The rulers' units and zero point, published to the body in its [`CanvasSpace`].
|
||||
rulers: Option<CanvasRulers>,
|
||||
/// The snapping of the coordinates the pointer sets on this canvas (View > Snap To): one function that the rulers
|
||||
/// snap their zero point with, the guides snap a guide with and the tool host hands to the tool
|
||||
/// ([`ToolContext::snap`]). Without it nothing snaps.
|
||||
/// The snapping of the coordinates the pointer sets on this canvas (View > Snap To), as data over the document's
|
||||
/// targets: the rulers snap their zero point with it, the guides snap a guide with it and the tool host hands it to
|
||||
/// the tool ([`ToolContext::snap`]). The canvas sets its tolerance each pass from the view it shows. Without it
|
||||
/// nothing snaps.
|
||||
#[prop]
|
||||
snap: Option<Snap>,
|
||||
/// The pasteboard colour, set once here; the pasteboard and the crop shield read it from the space.
|
||||
@@ -192,6 +193,8 @@ pub struct Canvas<'a> {
|
||||
ease: Option<Steer>,
|
||||
/// The app's tool moves the view with the pointer this pass ([`view_follows_pointer`](Self::view_follows_pointer)).
|
||||
follows_pointer: bool,
|
||||
/// The slot the body's paint reserved for the picture, published in the [`CanvasSpace`]; none in a measuring pass.
|
||||
picture: Option<space::PictureSlot>,
|
||||
}
|
||||
|
||||
/// A canvas's view in one pass.
|
||||
@@ -228,6 +231,7 @@ impl<'a> Canvas<'a> {
|
||||
context_key: false,
|
||||
ease: None,
|
||||
follows_pointer: false,
|
||||
picture: None,
|
||||
}
|
||||
.label(label)
|
||||
.ltr_axis()
|
||||
@@ -340,13 +344,19 @@ impl<'a> Canvas<'a> {
|
||||
}
|
||||
}
|
||||
let mut jumped = false;
|
||||
if let Some(wheel) = cx.take_wheel()
|
||||
&& let Some(action) = motion.wheel.read(&wheel, WheelNavigation::LINE, cx.env.shell().os, &self.navigation)
|
||||
{
|
||||
// The pointer the wheel came at: the canvas's own widget is not hovered where an app widget in its body
|
||||
// covers it.
|
||||
let at = wheel.at.unwrap_or_else(|| view.rect.center());
|
||||
jumped |= WheelNavigation::apply(&mut view, action, at, size, pixels_per_point);
|
||||
if let Some(wheel) = cx.take_wheel() {
|
||||
let os = cx.env.shell().os;
|
||||
if let Some(action) = motion.wheel.read(&wheel, WheelNavigation::LINE, os, &self.navigation) {
|
||||
// The pointer the wheel came at: the canvas's own widget is not hovered where an app widget in its body
|
||||
// covers it.
|
||||
let at = wheel.at.unwrap_or_else(|| view.rect.center());
|
||||
jumped |= WheelNavigation::apply(&mut view, action, at, size, pixels_per_point);
|
||||
}
|
||||
// A trackpad rotation or a twist of two fingers turns the view; a mirrored view turns the other way.
|
||||
if let Some(degrees) = WheelNavigation::rotation(&WheelInput::of(&wheel, WheelNavigation::LINE, os), &self.navigation) {
|
||||
view.rotation = normalized_angle(view.rotation + ViewTurn::screen_delta(degrees, view.flip_x));
|
||||
jumped = true;
|
||||
}
|
||||
}
|
||||
if let Some(delta) = Self::background_press(cx).1 {
|
||||
pan(&mut view, delta);
|
||||
@@ -378,12 +388,11 @@ impl<'a> Canvas<'a> {
|
||||
}
|
||||
// A pan or a scroll takes over from an ease, here or in a tool.
|
||||
let mut steer = motion.steer.take();
|
||||
match self.ease {
|
||||
Some(Steer::Ease { .. }) if !self.navigation.animated_zoom => steer = Some(Steer::Stop),
|
||||
Some(ease) => steer = Some(ease),
|
||||
None => {}
|
||||
if let Some(ease) = self.ease {
|
||||
steer = Some(ease);
|
||||
}
|
||||
if jumped {
|
||||
// With Animated Zoom off no ease runs, whether the app passed one this pass or one was running.
|
||||
if jumped || !self.navigation.animated_zoom {
|
||||
steer = Some(Steer::Stop);
|
||||
}
|
||||
let before = view;
|
||||
@@ -432,15 +441,23 @@ impl<'a> Canvas<'a> {
|
||||
if easing {
|
||||
space.ease_through(shown);
|
||||
}
|
||||
Some(
|
||||
space
|
||||
.with_keys(keys)
|
||||
.with_document(self.document_size())
|
||||
.with_rulers(self.rulers)
|
||||
.with_pasteboard(self.pasteboard)
|
||||
.with_background(background)
|
||||
.with_canvas(id),
|
||||
)
|
||||
let space = space
|
||||
.with_keys(keys)
|
||||
.with_document(self.document_size())
|
||||
.with_rulers(self.rulers)
|
||||
.with_pasteboard(self.pasteboard)
|
||||
.with_background(background)
|
||||
.with_canvas(id);
|
||||
Some(match self.picture {
|
||||
Some(slot) => space.with_picture(slot),
|
||||
None => space,
|
||||
})
|
||||
}
|
||||
|
||||
/// The snap of this pass: the app's with the tolerance of the view on screen and the OS the pass runs on.
|
||||
fn snapped(&self, os: craft_keymap::Platform) -> Option<Snap> {
|
||||
let view = self.settled.map(|settled| settled.shown).or(self.given)?;
|
||||
self.snap.clone().map(|snap| snap.at(&view, os))
|
||||
}
|
||||
|
||||
/// The press on the background part as the canvas reports it, and the pan of a middle-button drag: a middle press
|
||||
@@ -529,6 +546,13 @@ impl Component for Canvas<'_> {
|
||||
WheelNotch::Points(WheelNavigation::LINE)
|
||||
}
|
||||
|
||||
/// Reserves the slot the picture paints into, under every canvas control of the body (`CanvasSpace::paint_picture`).
|
||||
fn paint(&mut self, _ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let layer = cx.response.layer_id;
|
||||
let idx = cx.core.ctx.graphics_mut(|graphics| graphics.entry(layer).add(cx.content_rect, Shape::Noop));
|
||||
self.picture = Some(space::PictureSlot { layer, idx });
|
||||
}
|
||||
|
||||
/// The view of this pass, kept for the body and `finish`.
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
// Left untaken: the canvas's generic context request is recorded as for a secondary click.
|
||||
@@ -555,7 +579,7 @@ impl Component for Canvas<'_> {
|
||||
/// The canvas's [`CanvasSpace`] for its body; a canvas without a view hides an outer canvas's.
|
||||
fn content_env(&self, cx: &Cx<'_, Self>, values: &mut crate::runtime::env::AppValues) {
|
||||
space::publish(values, self.space(cx.response.id, cx.env.scale().0, BackgroundPress::of(&Self::background_press(cx).0, self.context_key)));
|
||||
snap::publish(values, self.snap.clone());
|
||||
snap::publish(values, self.snapped(cx.env.shell().os));
|
||||
}
|
||||
|
||||
/// The background part the active tool gets. It sits in the canvas root's space, the parent layer's. A press on it
|
||||
@@ -572,7 +596,8 @@ impl Component for Canvas<'_> {
|
||||
let space = self.space(cx.response.id, cx.env.scale().0, BackgroundPress::of(&press, self.context_key));
|
||||
let view = self.settled.map(|settled| settled.target).filter(|target| Some(*target) != self.given);
|
||||
let document = self.document_size();
|
||||
CanvasOutput { response: cx.response.clone(), press, space, view, snap: self.snap, document, navigation: self.navigation }
|
||||
let snap = self.snapped(cx.env.shell().os);
|
||||
CanvasOutput { response: cx.response.clone(), press, space, view, snap, document, navigation: self.navigation }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -34,6 +34,7 @@ use craft_behavior::kurbo::{Point as Point64, Rect as Rect64};
|
||||
use craft_behavior::{CanvasView, Metrics, PixelSize};
|
||||
use detail::{texel_extent, texel_origin};
|
||||
use egui::epaint::{Mesh, Vertex};
|
||||
use egui::layers::ShapeIdx;
|
||||
use egui::{Color32, ColorImage, Context, Id, Pos2, Response, Shape, TextureFilter, TextureOptions, Vec2, pos2};
|
||||
use std::collections::HashMap;
|
||||
use std::ops::RangeInclusive;
|
||||
@@ -261,7 +262,10 @@ pub struct RasterDisplay<'a> {
|
||||
/// How far the picture reaches past the document's edge.
|
||||
#[prop]
|
||||
extent: Extent,
|
||||
/// The display paints in the canvas's picture slot, under every canvas control of the body.
|
||||
/// The display paints in the canvas's picture slot, under every canvas control of the body, when the canvas
|
||||
/// space carries a slot; otherwise it paints in place. A display under the controls fills its canvas, so the
|
||||
/// canvas content rect, the slot's clip, is its clip. It declares no faded look of its own (`DisabledLook::States`):
|
||||
/// the canvas's own veil covers the slot.
|
||||
#[prop(flag, name = "picture")]
|
||||
under_controls: bool,
|
||||
read: PixelRect,
|
||||
@@ -507,6 +511,11 @@ impl Component for RasterDisplay<'_> {
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let Some(shown) = &self.shown else { return };
|
||||
let painter = ui.content_painter(cx);
|
||||
// A display that paints under the controls marks where its shapes start; they move into the canvas's picture
|
||||
// slot at the end, in show order with every other picture. Outside a canvas, or in a space with no slot, it
|
||||
// paints in place.
|
||||
let space = canvas_space(&cx.env);
|
||||
let first = (self.under_controls && space.and_then(|space| space.picture_slot()).is_some()).then(|| painter.painter.add(Shape::Noop));
|
||||
// The picture's area on screen: the document, or the mapped area. A mapped area with nothing of the unit
|
||||
// square in it has no checkerboard and no edge.
|
||||
let corners = match &self.mapping {
|
||||
@@ -558,6 +567,21 @@ impl Component for RasterDisplay<'_> {
|
||||
{
|
||||
painter.with_draw(|draw| edge(draw, corners));
|
||||
}
|
||||
if let (Some(first), Some(space)) = (first, space) {
|
||||
let last = painter.painter.add(Shape::Noop);
|
||||
let (ctx, layer) = (painter.painter.ctx().clone(), painter.painter.layer_id());
|
||||
let shapes: Vec<Shape> = ctx.graphics_mut(|layers| {
|
||||
let list = layers.entry(layer);
|
||||
(first.0 + 1..last.0)
|
||||
.map(|at| {
|
||||
let mut taken = Shape::Noop;
|
||||
list.mutate_shape(ShapeIdx(at), |clipped| std::mem::swap(&mut clipped.shape, &mut taken));
|
||||
taken
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
space.paint_picture(&ctx, shapes);
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> RasterDisplayOutput {
|
||||
|
||||
@@ -27,7 +27,17 @@ impl EnvValue for ShowReadouts {
|
||||
/// label and the widest value a section gap apart. Labels are in the muted ink and values in the normal one. No rows
|
||||
/// paint nothing.
|
||||
pub fn readout(cx: &impl StageAccess, at: Pos2, rows: &[(Label, String)]) {
|
||||
paint_readout(cx.stage().ctx(), at, rows);
|
||||
let ctx = cx.stage().ctx();
|
||||
if !shown(ctx) {
|
||||
return;
|
||||
}
|
||||
paint_readout(ctx, at, rows);
|
||||
}
|
||||
|
||||
/// Whether the root env's [`ShowReadouts`] lets value readouts paint: the one reading of the gate, shared by [`readout`]
|
||||
/// and the tool host.
|
||||
pub(super) fn shown(ctx: &Context) -> bool {
|
||||
Env::of_root(ctx).view().get::<ShowReadouts>().0
|
||||
}
|
||||
|
||||
/// [`readout`] that the Show Transformation Values gate ([`ShowReadouts`]) never silences: brush size readouts.
|
||||
|
||||
@@ -218,6 +218,10 @@ pub(crate) struct ToolRequests {
|
||||
pub(crate) ease: Option<ViewEase>,
|
||||
pub(crate) snapped: Vec<SnapLine>,
|
||||
pub(crate) autoscroll_at: Option<Pos2>,
|
||||
/// The pan's scroll-all-windows choice, from [`ToolContext::pan_view`].
|
||||
pub(crate) pan: Option<bool>,
|
||||
/// Rows the Show Transformation Values gate never silences, from [`ToolContext::hud`].
|
||||
pub(crate) hud: Option<Vec<(Label, String)>>,
|
||||
}
|
||||
|
||||
/// What a tool sees and may ask for during a call.
|
||||
@@ -406,7 +410,7 @@ impl<'a> ToolContext<'a> {
|
||||
|
||||
/// `point`, a document point under the pointer, moved to what the canvas snaps it to (View > Snap To) with the
|
||||
/// modifiers held now; the point itself when the canvas has no snapping or the Control key suspends it
|
||||
/// ([`snap_suspended`](super::snap_suspended)). The tool builds no snapping of its own.
|
||||
/// ([`Snap::apply`] decides). The tool builds no snapping of its own.
|
||||
pub fn snap(&self, point: Point) -> Point {
|
||||
Point::new(self.snap_along(Axis::Y, point.x), self.snap_along(Axis::X, point.y))
|
||||
}
|
||||
@@ -414,17 +418,16 @@ impl<'a> ToolContext<'a> {
|
||||
/// The coordinate `position` across a guide that would run along `along`, snapped as [`snap`](Self::snap) does:
|
||||
/// an x coordinate is across `Axis::Y`.
|
||||
pub fn snap_along(&self, along: Axis, position: f64) -> f64 {
|
||||
match self.snap {
|
||||
Some(snap) if !super::snap_suspended(self.mods, self.os(), false) => snap.apply(along, position, self.mods),
|
||||
_ => position,
|
||||
}
|
||||
self.snap.map_or(position, |snap| snap.apply(along, position, self.mods))
|
||||
}
|
||||
|
||||
/// The offset that moves `rect` (document units) onto a View > Snap To target with the modifiers held now; zero
|
||||
/// when Control suspends snapping or the canvas has no snap.
|
||||
pub fn snap_rect(&mut self, rect: kurbo::Rect) -> kurbo::Vec2 {
|
||||
let _ = rect;
|
||||
todo!("cw.C8")
|
||||
let Some(snap) = self.snap else { return kurbo::Vec2::ZERO };
|
||||
let (offset, lines) = snap.rect(rect, self.mods);
|
||||
self.requests.snapped.extend(lines);
|
||||
offset
|
||||
}
|
||||
|
||||
/// Adds the snap lines a canvas control the tool shows snapped this pass, handed to the host in the same pass.
|
||||
@@ -434,8 +437,8 @@ impl<'a> ToolContext<'a> {
|
||||
|
||||
/// Sets the view for a pan (as [`set_view`](Self::set_view)); the host reports it as [`ViewPan`].
|
||||
pub fn pan_view(&mut self, view: CanvasView, scroll_all: bool) {
|
||||
let _ = (view, scroll_all);
|
||||
todo!("cw.C10")
|
||||
self.set_view(view);
|
||||
self.requests.pan = Some(scroll_all);
|
||||
}
|
||||
|
||||
/// A canvas control the tool shows asks the app to scroll: the host reports `past_edge` for `pointer` through the
|
||||
@@ -521,10 +524,9 @@ impl<'a> ToolContext<'a> {
|
||||
}
|
||||
|
||||
/// Labelled values to show beside the pointer this pass, never gated by Show Transformation Values (brush size
|
||||
/// readouts). The last request of a pass wins.
|
||||
/// readouts). The last request of a pass wins. A hud asked for in the same pass as a readout replaces it.
|
||||
pub fn hud(&mut self, rows: Vec<(Label, String)>) {
|
||||
let _ = rows;
|
||||
todo!("cw.C2")
|
||||
self.requests.hud = Some(rows);
|
||||
}
|
||||
|
||||
/// Asks for another pass (an animation, a held key that repeats).
|
||||
@@ -675,7 +677,8 @@ pub trait CanvasTool {
|
||||
}
|
||||
|
||||
/// Whether the host calls `drag` once per pointer move of a pass (the freehand family) instead of once at the
|
||||
/// latest position. Default: `false`.
|
||||
/// latest position. `each_pass` runs before the pass's `drag` calls, so a tool that takes every move updates its
|
||||
/// live stroke once per pass after `run` returns, never per `drag` call. Default: `false`.
|
||||
fn takes_every_move(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
@@ -43,6 +43,15 @@
|
||||
//! place of the selected tool, and a gesture keeps the tool it began with. An app that switches tools itself from
|
||||
//! other input asks [`ToolHost::in_gesture`] first and keeps the tool it started the gesture with.
|
||||
//!
|
||||
//! Stand-ins: [`ToolHost::stand_in`] gives the tool a press runs while Command or Alt is held and the selected tool
|
||||
//! does not take the press, or answers it [`ToolAction::Ignored`]. The order is the momentary tool, then the Command
|
||||
//! stand-in, then the Alt stand-in, then the selected tool, and the gesture keeps the tool it began with. While the key
|
||||
//! is held and no gesture runs, hover, cursor and paint are the stand-in's.
|
||||
//!
|
||||
//! Readouts: a tool's [`ToolContext::readout`] rows paint only while the root env's `ShowReadouts` holds; its
|
||||
//! [`ToolContext::hud`] rows always paint. A secondary press the tool did not take is reported in
|
||||
//! [`ToolHostResponse::context`], and so is the Menu key.
|
||||
//!
|
||||
//! ```no_run
|
||||
//! # extern crate craft_ui_canvas as craft_ui;
|
||||
//! use craft_ui::canvas::{Canvas, CanvasTool, Momentary, ToolHost};
|
||||
@@ -57,11 +66,14 @@
|
||||
use super::frame_step;
|
||||
use super::momentary::{Momentary, MomentaryCommands, MomentaryTool};
|
||||
use super::navigate::Autoscroll;
|
||||
use super::readout::paint_readout;
|
||||
use super::readout::{paint_readout, shown as readouts_shown};
|
||||
use super::tool::{CanvasTool, March, ToolAccess, ToolAction, ToolClaims, ToolContext, ToolKey, ToolPointer, ToolRequests};
|
||||
use super::tools::HandTool;
|
||||
use super::zoom_motion::{self, Steer};
|
||||
use super::{CanvasOutput, CanvasSpace, Snap};
|
||||
use super::{CanvasOutput, CanvasSpace, Snap, context_click};
|
||||
use crate::canvas_controls::paint_lines;
|
||||
use crate::canvas_controls::{SmartGuides, SmartLine};
|
||||
use crate::contract::{Component, Meta as _};
|
||||
use crate::primitives::{ContentPainterCx, Draw, DrawEnv, PaintRecord};
|
||||
use crate::runtime::access::{self, Name, Role, SubDecl, SubNode};
|
||||
use crate::runtime::commands;
|
||||
@@ -69,17 +81,20 @@ use crate::runtime::edit::next_gesture_id;
|
||||
use crate::runtime::env::{Env, Label};
|
||||
use crate::runtime::memory::{global, with_session};
|
||||
use crate::runtime::pointer::{self, PointerFrame};
|
||||
use crate::runtime::overlay::{self, OpenFilter};
|
||||
use crate::runtime::sampler::{self, CanvasGesture};
|
||||
use crate::runtime::{cursor, frame, keys, lock_keys, measure};
|
||||
use crate::style::{DataColor, StyleCx};
|
||||
use crate::style::{DataColor, StyleCx, resolve_style};
|
||||
use craft_behavior::geometry::SnapLine;
|
||||
use craft_behavior::kurbo;
|
||||
use craft_behavior::{
|
||||
AccessAction, AccessRequest, CancelReason, CanvasView, Cursor, CursorPriority, GestureId, GesturePhase, Intent, PartKey, PartRef, PointerButton,
|
||||
PointerSample, PressCancel, PressPhase, PressStart, PressState,
|
||||
PointerEvent, PointerSample, PressCancel, PressPhase, PressStart, PressState,
|
||||
};
|
||||
use craft_keymap::{Chord, Key, Mods};
|
||||
use craft_theme::Variant;
|
||||
use egui::{Context, Id, Pos2, Rect, Ui, Vec2};
|
||||
use crate::runtime::windows::WindowHost;
|
||||
use egui::{Context, Id, Pos2, Rect, Ui, Vec2, ViewportId};
|
||||
use std::cell::RefCell;
|
||||
|
||||
/// A pointer event from automation, queued with [`ToolHost::inject`] and delivered on the next pass as if the
|
||||
@@ -98,6 +113,8 @@ pub enum ToolInput {
|
||||
sample: PointerSample,
|
||||
/// The modifiers held.
|
||||
mods: Mods,
|
||||
/// How many presses make up the click run: 1 for a lone press, 2 for a double press.
|
||||
clicks: u32,
|
||||
},
|
||||
/// The pointer moved: a drag while a gesture runs, else a hover.
|
||||
#[non_exhaustive]
|
||||
@@ -122,7 +139,7 @@ pub enum ToolInput {
|
||||
impl ToolInput {
|
||||
/// A mouse press of `button` at `pos`, with no modifiers.
|
||||
pub const fn down(button: PointerButton, pos: Pos2) -> Self {
|
||||
ToolInput::Down { button, pos, sample: PointerSample::new(1.0), mods: Mods::NONE }
|
||||
ToolInput::Down { button, pos, sample: PointerSample::new(1.0), mods: Mods::NONE, clicks: 1 }
|
||||
}
|
||||
|
||||
/// A mouse move to `pos`, with no modifiers.
|
||||
@@ -153,6 +170,15 @@ impl ToolInput {
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// A `Down` as the `count`th press of a click run (2 for a double press); the other inputs are unchanged.
|
||||
#[must_use]
|
||||
pub fn clicks(mut self, count: u32) -> Self {
|
||||
if let ToolInput::Down { clicks, .. } = &mut self {
|
||||
*clicks = count;
|
||||
}
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Labelled values for the pointer's side, as a tool handed them over with [`ToolContext::readout`].
|
||||
@@ -252,6 +278,17 @@ struct Active {
|
||||
injected: bool,
|
||||
/// The tool has had a `drag` call in this gesture.
|
||||
dragged: bool,
|
||||
/// The stand-in the gesture runs with, latched at the press until the gesture ends; `None` is the selected tool.
|
||||
stand_in: Option<StandInKey>,
|
||||
}
|
||||
|
||||
/// A secondary press the selected tool refused: what its menu request carries when the button comes up.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct SecondaryPress {
|
||||
/// The modifiers held when the button went down.
|
||||
mods: Mods,
|
||||
/// The momentary tool in effect at the press.
|
||||
momentary: Option<MomentaryTool>,
|
||||
}
|
||||
|
||||
/// What the host keeps between passes, in a session slot keyed by the canvas's id.
|
||||
@@ -268,26 +305,34 @@ struct HostState {
|
||||
space: Option<CanvasSpace>,
|
||||
/// The view a tool set while [`ToolHost::cancel`] ended its gesture outside a pass: the next pass reports it.
|
||||
cancelled_view: Option<CanvasView>,
|
||||
/// The viewport the canvas last ran in: an injected input owes that viewport a pass.
|
||||
viewport: ViewportId,
|
||||
/// The pass clock of the last pass that was not a measuring pass: an autoscroll moves by the time since.
|
||||
time: Option<f64>,
|
||||
/// The open secondary press the tool refused: its release asks for the canvas menu.
|
||||
secondary: Option<SecondaryPress>,
|
||||
}
|
||||
|
||||
fn state_id(canvas: Id) -> Id {
|
||||
global("craft-ui tool host", canvas)
|
||||
}
|
||||
|
||||
/// Whether the key of a stand-in is held in `mods`.
|
||||
fn held_at(key: StandInKey, mods: Mods) -> bool {
|
||||
match key {
|
||||
StandInKey::Command => mods.cmd,
|
||||
StandInKey::Alt => mods.alt,
|
||||
}
|
||||
}
|
||||
|
||||
/// The on-canvas tool host. Built each pass, shown once with the canvas's output and the tool.
|
||||
#[derive(Default)]
|
||||
pub struct ToolHost<'m> {
|
||||
disabled: bool,
|
||||
momentary: Option<&'m mut Momentary>,
|
||||
#[allow(dead_code)] // P3(canvas-widgets-w2): cw.C1
|
||||
command_stand_in: Option<&'m mut (dyn CanvasTool + 'm)>,
|
||||
#[allow(dead_code)] // P3(canvas-widgets-w2): cw.C1
|
||||
alt_stand_in: Option<&'m mut (dyn CanvasTool + 'm)>,
|
||||
#[allow(dead_code)] // P3(canvas-widgets-w2): cw.C3
|
||||
smart_guide_color: Option<DataColor>,
|
||||
#[allow(dead_code)] // P3(canvas-widgets-w2): cw.C4
|
||||
precise_cursors: bool,
|
||||
}
|
||||
|
||||
@@ -344,7 +389,7 @@ impl<'m> ToolHost<'m> {
|
||||
/// Delivers the pass's pointer and key events to `tool`, paints it over the canvas, and paints the readout it
|
||||
/// asked for beside the pointer.
|
||||
pub fn run(self, ui: &Ui, canvas: &CanvasOutput, tool: &mut dyn CanvasTool) -> ToolHostResponse {
|
||||
let ToolHost { disabled, momentary, .. } = self; // P3(canvas-widgets-w2): cw.C1, cw.C3, cw.C4
|
||||
let ToolHost { disabled, momentary, mut command_stand_in, mut alt_stand_in, smart_guide_color, precise_cursors } = self;
|
||||
let ctx = ui.ctx().clone();
|
||||
let env = Env::of(ui);
|
||||
let key = state_id(canvas.response.id);
|
||||
@@ -372,11 +417,13 @@ impl<'m> ToolHost<'m> {
|
||||
}
|
||||
commands::take_around::<MomentaryCommands>(&ctx, canvas.response.id, env.view().command_chain())
|
||||
});
|
||||
let mut momentary_tool = None;
|
||||
let tool: &mut dyn CanvasTool = match momentary {
|
||||
Some(momentary) => {
|
||||
for (command, event) in fired {
|
||||
momentary.fired(command, event.phase);
|
||||
}
|
||||
momentary_tool = momentary.tool(input.mods, state.gesture.is_some());
|
||||
let (tool, hand) = momentary.substitute(tool, input.mods, state.gesture.is_some());
|
||||
glide = hand;
|
||||
tool
|
||||
@@ -386,8 +433,30 @@ impl<'m> ToolHost<'m> {
|
||||
tool
|
||||
}
|
||||
};
|
||||
if !measuring && tool.view_only() {
|
||||
sampler::pass_tool_gesture(&ctx, canvas.response.id, CanvasGesture::PRIMARY);
|
||||
}
|
||||
// With no gesture and no momentary tool, a held stand-in key makes the stand-in the tool of hover, cursor and
|
||||
// paint while the selected tool does not take a primary press.
|
||||
let lent = if state.gesture.is_none() && momentary_tool.is_none() && !tool.takes(PointerButton::Primary, input.mods) {
|
||||
[StandInKey::Command, StandInKey::Alt].into_iter().find(|key| {
|
||||
let set = match key {
|
||||
StandInKey::Command => command_stand_in.is_some(),
|
||||
StandInKey::Alt => alt_stand_in.is_some(),
|
||||
};
|
||||
set && held_at(*key, input.mods)
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut run = Run {
|
||||
tool: &mut *tool,
|
||||
command: command_stand_in.as_deref_mut(),
|
||||
alt: alt_stand_in.as_deref_mut(),
|
||||
lent: None,
|
||||
stand_ins: momentary_tool.is_none(),
|
||||
momentary: momentary_tool,
|
||||
precise: precise_cursors,
|
||||
space,
|
||||
slop: input.slop,
|
||||
down: &down,
|
||||
@@ -408,6 +477,7 @@ impl<'m> ToolHost<'m> {
|
||||
if !measuring {
|
||||
run.call(None, |tool, cx| tool.each_pass(cx));
|
||||
run.hover_scrolls = run.tool.autoscrolls_on_hover();
|
||||
run.lent = lent;
|
||||
if let Some(hand) = glide {
|
||||
run.glide(hand);
|
||||
}
|
||||
@@ -416,13 +486,16 @@ impl<'m> ToolHost<'m> {
|
||||
run.state.spent |= canvas.press.phase.is_press();
|
||||
} else {
|
||||
run.phase(&canvas.press, &input);
|
||||
run.hover_outside(canvas.response.id, &canvas.press, &input);
|
||||
for event in queued {
|
||||
run.injected(event);
|
||||
}
|
||||
run.keys(&ctx, canvas.response.id, env.direction.is_rtl());
|
||||
run.menu_key();
|
||||
}
|
||||
}
|
||||
let Run { mut response, requests, .. } = run;
|
||||
let before = space.map(|space| space.target());
|
||||
if !measuring {
|
||||
if let Some(past) = response.past_edge {
|
||||
let step = frame_step(input.time - state.time.unwrap_or(input.time));
|
||||
@@ -437,6 +510,9 @@ impl<'m> ToolHost<'m> {
|
||||
// jumps stops that ease.
|
||||
if let Some(view) = response.view.as_mut() {
|
||||
*view = canvas.clamped(*view);
|
||||
if let (Some(scroll_all), Some(before)) = (requests.pan, before) {
|
||||
response.pan = Some(ViewPan::new(view.center - before.center, scroll_all));
|
||||
}
|
||||
let steer = match (requests.ease, canvas.space) {
|
||||
(Some(ease), Some(drawn)) => Steer::Ease { from: drawn.view, anchor: ease.anchor },
|
||||
_ => Steer::Stop,
|
||||
@@ -450,6 +526,13 @@ impl<'m> ToolHost<'m> {
|
||||
let phase = canvas.press.phase;
|
||||
let over = phase.is_press() || matches!(phase, PressPhase::Hover) || state.gesture.is_some();
|
||||
let current = state.gesture.map(|active| active.last).or_else(|| over.then(|| hover_pointer(&input, canvas.press)).flatten());
|
||||
// The tool of hover, cursor, paint and claims: the one the running gesture latched, else the stand-in lent for
|
||||
// the held key, else the selected tool.
|
||||
let effective: &dyn CanvasTool = match state.gesture.map_or(lent, |active| active.stand_in) {
|
||||
Some(StandInKey::Command) => command_stand_in.as_deref().unwrap_or(&*tool),
|
||||
Some(StandInKey::Alt) => alt_stand_in.as_deref().unwrap_or(&*tool),
|
||||
None => &*tool,
|
||||
};
|
||||
let context = || {
|
||||
let cx = ToolContext::new(rect, space)
|
||||
.pointer(current)
|
||||
@@ -458,6 +541,7 @@ impl<'m> ToolHost<'m> {
|
||||
.slop(input.slop)
|
||||
.down(&down)
|
||||
.caps_lock(caps)
|
||||
.precise_cursors(precise_cursors)
|
||||
.gesture(state.gesture.map(|active| active.id))
|
||||
.env(&env);
|
||||
match canvas.snap.as_ref() {
|
||||
@@ -465,21 +549,32 @@ impl<'m> ToolHost<'m> {
|
||||
None => cx,
|
||||
}
|
||||
};
|
||||
paint_tool(ui, &env, tool, context());
|
||||
paint_tool(ui, &env, effective, context());
|
||||
if canvas.snap.as_ref().is_some_and(|snap| snap.options().smart_guides) {
|
||||
paint_smart_lines(ui, &env, rect, space, &requests.snapped, smart_guide_color);
|
||||
}
|
||||
response.snapped = requests.snapped;
|
||||
let cx = context();
|
||||
// A disabled host delivers no key, so it holds none from the app.
|
||||
state.claims = if disabled { ToolClaims::NONE } else { tool.claims() };
|
||||
if let Some(access) = tool.access(&cx) {
|
||||
state.claims = if disabled { ToolClaims::NONE } else { effective.claims() };
|
||||
if let Some(access) = effective.access(&cx) {
|
||||
report_access(&ctx, canvas, rect, &access, state.claims.nudges);
|
||||
}
|
||||
if over {
|
||||
let wanted = tool.cursor(&cx);
|
||||
let wanted = effective.cursor(&cx);
|
||||
cursor::request(&ctx, wanted.clone(), CursorPriority::Tool);
|
||||
response.cursor = Some(wanted);
|
||||
}
|
||||
if let (Some(rows), Some(at)) = (requests.readout, current) {
|
||||
paint_readout(&ctx, at.pos, &rows);
|
||||
response.readout = Some(ToolReadout { at: at.pos, rows });
|
||||
if let Some(at) = current.map(|pointer| pointer.pos) {
|
||||
let gate = readouts_shown(&ctx);
|
||||
// One box per pass: a hud replaces a readout asked for in the same pass.
|
||||
let (rows, paints) = if requests.hud.is_some() { (requests.hud, true) } else { (requests.readout, gate) };
|
||||
if let Some(rows) = rows {
|
||||
if paints {
|
||||
paint_readout(&ctx, at, &rows);
|
||||
}
|
||||
response.readout = Some(ToolReadout { at, rows });
|
||||
}
|
||||
}
|
||||
if requests.repaint {
|
||||
frame::request_repaint(&ctx);
|
||||
@@ -492,6 +587,7 @@ impl<'m> ToolHost<'m> {
|
||||
}
|
||||
state.rect = Some(rect);
|
||||
state.space = space;
|
||||
state.viewport = WindowHost::of(&ctx).current();
|
||||
with_session(&ctx, key, |slot: &mut HostState| {
|
||||
let later = std::mem::take(&mut slot.queued);
|
||||
*slot = state;
|
||||
@@ -503,7 +599,11 @@ impl<'m> ToolHost<'m> {
|
||||
/// Queues an automation pointer event for the host of the canvas `canvas` (`CanvasOutput::response.id`); it is
|
||||
/// delivered on the next pass, after the pointer's own events. A `Down` while a gesture runs is dropped.
|
||||
pub fn inject(ctx: &Context, canvas: Id, input: ToolInput) {
|
||||
with_session(ctx, state_id(canvas), |state: &mut HostState| state.queued.push(input));
|
||||
let viewport = with_session(ctx, state_id(canvas), |state: &mut HostState| {
|
||||
state.queued.push(input);
|
||||
state.viewport
|
||||
});
|
||||
WindowHost::of(ctx).inject_pass(viewport);
|
||||
frame::request_repaint(ctx);
|
||||
}
|
||||
|
||||
@@ -540,8 +640,7 @@ impl<'m> ToolHost<'m> {
|
||||
|
||||
/// The canvas space the host of `canvas` used in its last pass, `None` before its first.
|
||||
pub fn shown_space(ctx: &Context, canvas: Id) -> Option<CanvasSpace> {
|
||||
let _ = (ctx, canvas);
|
||||
todo!("canvas-widgets-w1")
|
||||
with_session(ctx, state_id(canvas), |state: &mut HostState| state.space)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -601,7 +700,13 @@ fn paint_tool(ui: &Ui, env: &Env, tool: &dyn CanvasTool, cx: ToolContext<'_>) {
|
||||
let record = RefCell::new(PaintRecord::default());
|
||||
let draw = Draw::new(&painter, &record, DrawEnv { tokens: &env.tokens, direction: env.direction, ink: env.ink });
|
||||
let content = ContentPainterCx::new(painter.clone(), env, env.ink);
|
||||
let style = StyleCx::new(
|
||||
let march = March { policy: env.motion, dash: env.tokens.stroke.dash };
|
||||
tool.paint(&draw, &cx.painter(&content, march).styled(host_style(ui, env)));
|
||||
}
|
||||
|
||||
/// The style context the host paints with: the secondary variant of the pass's env.
|
||||
fn host_style<'a>(ui: &'a Ui, env: &'a Env) -> StyleCx<'a> {
|
||||
StyleCx::new(
|
||||
ui.ctx(),
|
||||
&env.tokens,
|
||||
&env.values,
|
||||
@@ -613,9 +718,20 @@ fn paint_tool(ui: &Ui, env: &Env, tool: &dyn CanvasTool, cx: ToolContext<'_>) {
|
||||
env.active,
|
||||
env.key,
|
||||
env.line_ratio,
|
||||
);
|
||||
let march = March { policy: env.motion, dash: env.tokens.stroke.dash };
|
||||
tool.paint(&draw, &cx.painter(&content, march).styled(style));
|
||||
)
|
||||
}
|
||||
|
||||
/// Paints the smart kinds of the snap `lines` over the canvas through the smart guides' one line loop, in `color` or
|
||||
/// the theme's smart guide colour. `SmartGuides` itself paints only inside a canvas body, which the host is not in.
|
||||
fn paint_smart_lines(ui: &Ui, env: &Env, rect: Rect, space: Option<CanvasSpace>, lines: &[SnapLine], color: Option<DataColor>) {
|
||||
let Some(space) = space else { return };
|
||||
let smart: Vec<SmartLine> = lines.iter().filter(|line| line.kind.is_smart()).map(|line| SmartLine::of(line, space.view.visible())).collect();
|
||||
if smart.is_empty() {
|
||||
return;
|
||||
}
|
||||
let content = ContentPainterCx::new(ui.painter().with_clip_rect(rect), env, env.ink);
|
||||
let style = resolve_style(&host_style(ui, env), SmartGuides::new(&[], &[]).style_key(), ui.ctx(), <SmartGuides<'static> as Component>::style);
|
||||
paint_lines(&content, &space.view, &smart, &style, color);
|
||||
}
|
||||
|
||||
/// The hover sample of the pass: the pointer's latest position with the pen's reading.
|
||||
@@ -653,7 +769,7 @@ fn delete_chords(claims: ToolClaims) -> impl Iterator<Item = Chord> {
|
||||
|
||||
/// Every chord `claims` holds from the app's shortcuts.
|
||||
fn claimed_chords(claims: ToolClaims) -> impl Iterator<Item = Chord> {
|
||||
kept_chords().filter(move |_| claims.keyboard).chain(delete_chords(claims))
|
||||
kept_chords().filter(move |_| claims.keyboard).chain(delete_chords(claims)).chain(claims.keys.iter().copied())
|
||||
}
|
||||
|
||||
/// The sample of a press at `pos` taken at `time`: the button the press runs with, and its sample.
|
||||
@@ -671,7 +787,9 @@ fn cancel_reason(reason: PressCancel) -> CancelReason {
|
||||
}
|
||||
|
||||
/// One pass of the host: the tool, the state and what the calls produced.
|
||||
struct Run<'a> {
|
||||
///
|
||||
/// `'t` is the stand-ins' own lifetime: the host lends them for one run, so `Run`'s borrows need not outlive the host.
|
||||
struct Run<'a, 't> {
|
||||
tool: &'a mut dyn CanvasTool,
|
||||
space: Option<CanvasSpace>,
|
||||
slop: f32,
|
||||
@@ -693,9 +811,22 @@ struct Run<'a> {
|
||||
ending: Option<GestureId>,
|
||||
/// The tool autoscrolls on hover, in its state after `each_pass`.
|
||||
hover_scrolls: bool,
|
||||
/// The Command stand-in.
|
||||
command: Option<&'a mut (dyn CanvasTool + 't)>,
|
||||
/// The Alt stand-in.
|
||||
alt: Option<&'a mut (dyn CanvasTool + 't)>,
|
||||
/// The stand-in lent to hover, cursor and paint while no gesture runs (its key is held and the selected tool does
|
||||
/// not take a primary press).
|
||||
lent: Option<StandInKey>,
|
||||
/// A press may run a stand-in: no momentary tool is in effect.
|
||||
stand_ins: bool,
|
||||
/// The momentary tool in effect this pass.
|
||||
momentary: Option<MomentaryTool>,
|
||||
/// Preferences > Cursors > Other Cursors is Precise.
|
||||
precise: bool,
|
||||
}
|
||||
|
||||
impl<'a> Run<'a> {
|
||||
impl<'a, 't: 'a> Run<'a, 't> {
|
||||
fn context(&self, pointer: Option<ToolPointer>) -> ToolContext<'a> {
|
||||
let cx = ToolContext::new(self.rect, self.space)
|
||||
.pointer(pointer)
|
||||
@@ -704,6 +835,7 @@ impl<'a> Run<'a> {
|
||||
.slop(self.slop)
|
||||
.down(self.down)
|
||||
.caps_lock(self.caps)
|
||||
.precise_cursors(self.precise)
|
||||
.gesture(self.state.gesture.map(|active| active.id).or(self.ending));
|
||||
let cx = cx.env(self.env);
|
||||
match self.snap {
|
||||
@@ -717,6 +849,12 @@ impl<'a> Run<'a> {
|
||||
let asked = cx.take_requests();
|
||||
self.requests.readout = asked.readout.or(self.requests.readout.take());
|
||||
self.requests.repaint |= asked.repaint;
|
||||
self.requests.hud = asked.hud.or(self.requests.hud.take());
|
||||
self.requests.snapped.extend(asked.snapped);
|
||||
self.requests.pan = asked.pan.or(self.requests.pan);
|
||||
if let Some(at) = asked.autoscroll_at {
|
||||
self.scroll_past(at);
|
||||
}
|
||||
if let Some(view) = asked.view {
|
||||
if let Some(space) = self.space.as_mut() {
|
||||
space.set_view(view);
|
||||
@@ -726,13 +864,62 @@ impl<'a> Run<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The tool `who` names: a stand-in, or the selected tool for `None` and for a stand-in that is not set.
|
||||
fn pick_as(&mut self, who: Option<StandInKey>) -> &mut (dyn CanvasTool + 'a) {
|
||||
let stand = match who {
|
||||
Some(StandInKey::Command) => self.command.as_deref_mut(),
|
||||
Some(StandInKey::Alt) => self.alt.as_deref_mut(),
|
||||
None => None,
|
||||
};
|
||||
match stand {
|
||||
Some(stand) => stand,
|
||||
None => &mut *self.tool,
|
||||
}
|
||||
}
|
||||
|
||||
/// A call on the tool of the moment: the running gesture's, else the lent stand-in, else the selected tool.
|
||||
fn call<R>(&mut self, pointer: Option<ToolPointer>, run: impl FnOnce(&mut dyn CanvasTool, &mut ToolContext<'_>) -> R) -> R {
|
||||
let who = self.state.gesture.map_or(self.lent, |active| active.stand_in);
|
||||
self.call_as(who, pointer, run)
|
||||
}
|
||||
|
||||
fn call_as<R>(
|
||||
&mut self,
|
||||
who: Option<StandInKey>,
|
||||
pointer: Option<ToolPointer>,
|
||||
run: impl FnOnce(&mut dyn CanvasTool, &mut ToolContext<'_>) -> R,
|
||||
) -> R {
|
||||
let mut cx = self.context(pointer);
|
||||
let out = run(&mut *self.tool, &mut cx);
|
||||
let out = run(self.pick_as(who), &mut cx);
|
||||
self.absorb(cx);
|
||||
out
|
||||
}
|
||||
|
||||
/// The stand-in whose key `pointer` holds and which takes the press.
|
||||
fn stand_for(&self, pointer: &ToolPointer) -> Option<StandInKey> {
|
||||
if !self.stand_ins {
|
||||
return None;
|
||||
}
|
||||
[StandInKey::Command, StandInKey::Alt].into_iter().find(|key| {
|
||||
let stand = match key {
|
||||
StandInKey::Command => self.command.as_deref(),
|
||||
StandInKey::Alt => self.alt.as_deref(),
|
||||
};
|
||||
held_at(*key, pointer.mods) && stand.is_some_and(|tool| tool.takes(pointer.button, pointer.mods))
|
||||
})
|
||||
}
|
||||
|
||||
/// The one past-edge rule: how far `pos` lies past the canvas edge, for a drag and for a canvas control that asks to
|
||||
/// scroll. An empty canvas (a window shrunk to nothing) has no edge to scroll past.
|
||||
fn scroll_past(&mut self, pos: Pos2) {
|
||||
if self.rect.is_positive() {
|
||||
let past = pos - self.rect.clamp(pos);
|
||||
if past != Vec2::ZERO {
|
||||
self.response.past_edge = Some(past);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Advances the glide of a momentary Hand that is not the tool of this pass.
|
||||
fn glide(&mut self, hand: &mut HandTool) {
|
||||
let mut cx = self.context(None);
|
||||
@@ -747,19 +934,34 @@ impl<'a> Run<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Offers a press to the tool when it takes the button; a refused, ignored or whole press is spent.
|
||||
/// Offers a press to the tool when it takes the button, else to the stand-in whose key is held; a press the selected
|
||||
/// tool answers `Ignored` goes to that stand-in too. A refused, ignored or whole press is spent.
|
||||
fn begin(&mut self, pointer: ToolPointer, injected: bool) {
|
||||
let mut who = None;
|
||||
if !self.tool.takes(pointer.button, pointer.mods) {
|
||||
self.state.spent = true;
|
||||
return;
|
||||
who = self.stand_for(&pointer);
|
||||
if who.is_none() {
|
||||
self.state.spent = true;
|
||||
if pointer.button == PointerButton::Secondary {
|
||||
self.state.secondary = Some(SecondaryPress { mods: pointer.mods, momentary: self.momentary });
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
let id = next_gesture_id(self.ctx);
|
||||
self.ending = Some(id);
|
||||
let action = self.call(Some(pointer), |tool, cx| tool.press(&pointer, cx));
|
||||
let mut action = self.call_as(who, Some(pointer), |tool, cx| tool.press(&pointer, cx));
|
||||
if action == ToolAction::Ignored
|
||||
&& who.is_none()
|
||||
&& let Some(key) = self.stand_for(&pointer)
|
||||
{
|
||||
who = Some(key);
|
||||
action = self.call_as(who, Some(pointer), |tool, cx| tool.press(&pointer, cx));
|
||||
}
|
||||
self.ending = None;
|
||||
match action {
|
||||
ToolAction::Claimed => {
|
||||
self.state.gesture = Some(Active { id, button: pointer.button, last: pointer, injected, dragged: false });
|
||||
self.state.gesture = Some(Active { id, button: pointer.button, last: pointer, injected, dragged: false, stand_in: who });
|
||||
self.report(GesturePhase::Begin);
|
||||
}
|
||||
ToolAction::Done => {
|
||||
@@ -779,19 +981,85 @@ impl<'a> Run<'a> {
|
||||
active.dragged = true;
|
||||
self.call(Some(pointer), |tool, cx| tool.drag(&pointer, cx));
|
||||
self.report(GesturePhase::Update);
|
||||
// An empty canvas (a window shrunk to nothing) has no edge to scroll past.
|
||||
if self.tool.autoscrolls() && self.rect.is_positive() {
|
||||
let past = pointer.pos - self.rect.clamp(pointer.pos);
|
||||
if past != Vec2::ZERO {
|
||||
self.response.past_edge = Some(past);
|
||||
}
|
||||
let who = self.state.gesture.and_then(|active| active.stand_in);
|
||||
if self.pick_as(who).autoscrolls() {
|
||||
self.scroll_past(pointer.pos);
|
||||
}
|
||||
}
|
||||
|
||||
/// The drag of this pass: one call per pointer move of the pass for a tool that takes every move, their times
|
||||
/// spread from the last delivered sample to the pass time; one call at `pos` for any other tool.
|
||||
fn drag_moves(&mut self, start: PressStart, pos: Pos2, press: &PressState) {
|
||||
let Some(active) = self.state.gesture else { return };
|
||||
// A pass delivers only the moves it was handed: a rerun pass has none. A held pointer resting past the edge
|
||||
// keeps one drag per pass, since the view scrolls under it.
|
||||
let stirred = pointer::with_pass_pointer(self.ctx, |pass| pass.stirred);
|
||||
if !stirred && pos == self.rect.clamp(pos) {
|
||||
return;
|
||||
}
|
||||
let moves: Vec<(Pos2, Option<PointerSample>)> = if self.pick_as(active.stand_in).takes_every_move() {
|
||||
pointer::with_pass_pointer(self.ctx, |pass| {
|
||||
let from = pass.events.iter().rposition(|event| matches!(event, PointerEvent::Pressed { .. })).map_or(0, |at| at + 1);
|
||||
pass.events[from..]
|
||||
.iter()
|
||||
.filter_map(|event| match event {
|
||||
PointerEvent::Moved { at, sample } => Some((*at, *sample)),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
if moves.is_empty() {
|
||||
self.drag(press_pointer(start, pos, self.time, press));
|
||||
return;
|
||||
}
|
||||
let (from, count) = (active.last.time, moves.len());
|
||||
for (k, (at, sample)) in moves.into_iter().enumerate() {
|
||||
let time = if k + 1 == count { self.time } else { from + (self.time - from) * (k + 1) as f64 / count as f64 };
|
||||
self.drag(press_pointer(start, at, time, press).sample(sample.or(press.sample).unwrap_or(PointerSample::new(1.0))));
|
||||
}
|
||||
}
|
||||
|
||||
/// A hover with the pointer outside the canvas, for a tool that autoscrolls on hover: the tool follows the pointer
|
||||
/// and the view scrolls at the distance past the edge. Nothing runs with a button down, a momentary tool or stand-in
|
||||
/// in effect, an open modal or popup layer, another canvas's background under the pointer or the window unfocused.
|
||||
fn hover_outside(&mut self, canvas: Id, press: &PressState, frame: &PointerFrame) {
|
||||
let Some(pos) = frame.pos else { return };
|
||||
if !self.hover_scrolls
|
||||
|| self.state.gesture.is_some()
|
||||
|| self.lent.is_some()
|
||||
|| self.momentary.is_some()
|
||||
|| press.phase.is_press()
|
||||
|| pointer::shapes_at(self.ctx, pos).iter().any(|(owner, part)| *owner != canvas && part.is_some_and(|part| part.key == super::BACKGROUND))
|
||||
|| !self.rect.is_positive()
|
||||
|| self.rect.contains(pos)
|
||||
|| !frame.buttons.is_empty()
|
||||
|| !self.ctx.input(|input| input.focused)
|
||||
|| overlay::any_open(self.ctx, OpenFilter::Keys)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let pointer = ToolPointer::new(pos, PointerButton::Primary, frame.time)
|
||||
.mods(frame.mods)
|
||||
.sample(frame.sample.unwrap_or(PointerSample::new(1.0)));
|
||||
self.call(Some(pointer), |tool, cx| tool.hover(&pointer, cx));
|
||||
self.scroll_past(pos);
|
||||
}
|
||||
|
||||
/// The Menu key or Shift+F10 reached the focused canvas: the app opens its menu at the view's centre.
|
||||
fn menu_key(&mut self) {
|
||||
let Some(space) = self.space else { return };
|
||||
if space.background().context_key && self.response.context.is_none() {
|
||||
self.response.context = Some(ContextRequest { at: space.view.rect.center(), mods: self.mods, momentary: self.momentary });
|
||||
}
|
||||
}
|
||||
|
||||
fn end(&mut self, pointer: ToolPointer) {
|
||||
if let Some(active) = self.state.gesture.take() {
|
||||
self.ending = Some(active.id);
|
||||
self.call(Some(pointer), |tool, cx| tool.release(&pointer, cx));
|
||||
self.call_as(active.stand_in, Some(pointer), |tool, cx| tool.release(&pointer, cx));
|
||||
self.ending = None;
|
||||
self.report(GesturePhase::Commit);
|
||||
}
|
||||
@@ -800,7 +1068,7 @@ impl<'a> Run<'a> {
|
||||
fn cancel(&mut self, reason: CancelReason) {
|
||||
if let Some(active) = self.state.gesture.take() {
|
||||
self.ending = Some(active.id);
|
||||
self.call(Some(active.last), |tool, cx| tool.cancel(reason, cx));
|
||||
self.call_as(active.stand_in, Some(active.last), |tool, cx| tool.cancel(reason, cx));
|
||||
self.ending = None;
|
||||
self.report(GesturePhase::Cancel);
|
||||
self.cancelled = true;
|
||||
@@ -853,7 +1121,7 @@ impl<'a> Run<'a> {
|
||||
if self.state.gesture.is_none() && !self.state.spent {
|
||||
self.begin(press_pointer(start, start.origin, start.time, press), false);
|
||||
}
|
||||
self.drag(press_pointer(start, pos, self.time, press));
|
||||
self.drag_moves(start, pos, press);
|
||||
}
|
||||
PressPhase::Release { start, pos, click, .. } => {
|
||||
if self.state.gesture.is_none() && !self.state.spent {
|
||||
@@ -866,10 +1134,15 @@ impl<'a> Run<'a> {
|
||||
}
|
||||
self.end(pointer);
|
||||
self.state.spent = false;
|
||||
// A secondary press the tool refused asks for the menu when its button comes up.
|
||||
if let (Some(asked), Some(at)) = (self.state.secondary.take(), context_click(press)) {
|
||||
self.response.context = Some(ContextRequest { at, mods: asked.mods, momentary: asked.momentary });
|
||||
}
|
||||
}
|
||||
PressPhase::Cancel { reason, .. } => {
|
||||
self.cancel(cancel_reason(reason));
|
||||
self.state.spent = false;
|
||||
self.state.secondary = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -878,8 +1151,8 @@ impl<'a> Run<'a> {
|
||||
fn injected(&mut self, input: ToolInput) {
|
||||
let own = self.state.gesture.is_none_or(|active| active.injected);
|
||||
match input {
|
||||
ToolInput::Down { button, pos, sample, mods } if self.state.gesture.is_none() => {
|
||||
let pointer = ToolPointer::new(pos, button, self.time).mods(mods).sample(sample).clicks(1);
|
||||
ToolInput::Down { button, pos, sample, mods, clicks } if self.state.gesture.is_none() => {
|
||||
let pointer = ToolPointer::new(pos, button, self.time).mods(mods).sample(sample).clicks(clicks);
|
||||
self.begin(pointer, true);
|
||||
self.state.spent = false;
|
||||
}
|
||||
@@ -959,5 +1232,11 @@ impl<'a> Run<'a> {
|
||||
}
|
||||
}
|
||||
}
|
||||
for chord in claims.keys.iter().copied().filter(|chord| keys::take_claimed(ctx, canvas, *chord)) {
|
||||
let kept = ToolKey::Kept(chord);
|
||||
if self.call(None, |tool, cx| tool.key(&kept, cx)) {
|
||||
self.response.took_key = Some(kept);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ mod words;
|
||||
// Guides and smart guides.
|
||||
mod guides;
|
||||
mod smart_guides;
|
||||
pub(crate) use smart_guides::paint_lines;
|
||||
|
||||
pub use guides::{GuideCommands, GuideStyle, Guides, GuidesOutput, reading};
|
||||
pub use smart_guides::{Measure, SmartGuides, SmartGuidesStyle, SmartLine};
|
||||
|
||||
@@ -1,17 +1,29 @@
|
||||
//! `CanvasTool`, `ToolHost` and `tool_pick` (8.3): a drag is one `Begin`...`Commit`, Escape cancels it once, a press
|
||||
//! on a canvas control never reaches the tool, and a group's letter picks and cycles its tools.
|
||||
|
||||
use craft_behavior::geometry::{SnapKind, SnapLine, SnapOptions, SnapTarget, SnapTargets};
|
||||
use craft_behavior::kurbo::{Point, Size};
|
||||
use craft_behavior::{CancelReason, CanvasView, GesturePhase, PointerButton};
|
||||
use craft_behavior::{Axis, CancelReason, CanvasView, Cursor, CursorIcon, GesturePhase, PointerButton};
|
||||
use craft_keymap::Mods;
|
||||
use craft_ui::canvas::{Autoscroll, Canvas, CanvasTool, CropOverlay, ToolAction, ToolClaims, ToolContext, ToolHost, ToolKey, ToolPath, ToolPointer};
|
||||
use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
|
||||
use craft_ui::canvas::{
|
||||
Autoscroll, Canvas, CanvasScrollbars, CanvasTool, ContextRequest, CropOverlay, HandTool, Momentary, NavigationOptions, Snap,
|
||||
StandInKey, ToolAction, ToolClaims, ToolContext, ToolHost, ToolInput, ToolKey, ToolPath, ToolPointer,
|
||||
};
|
||||
use craft_ui::contract::{Bind, Sampler as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::dialog::Dialog;
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::primitives::Draw;
|
||||
use craft_ui::runtime::access::Role;
|
||||
use craft_ui::runtime::frame;
|
||||
use craft_ui::style::DataColor;
|
||||
use craft_ui::testing::input::key_press;
|
||||
use craft_ui::testing::{Fixture, ToolFixture, pointer, trial};
|
||||
use egui::{Pos2, Rect, Vec2};
|
||||
use egui::{Color32, Id, Key, Modifiers, Pos2, Rect, Shape, Vec2};
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
const DOCUMENT: Size = Size::new(1200.0, 900.0);
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Call {
|
||||
@@ -159,18 +171,21 @@ impl CanvasTool for Band {
|
||||
|
||||
type BandCanvas = (Fixture, Rc<RefCell<Band>>, Rc<Cell<Option<CanvasView>>>);
|
||||
|
||||
/// The hover autoscroll as an app runs it: the canvas shows a document zoomed in past the room, and the app moves its
|
||||
/// view by the host's `scroll`. Returns the fixture, the tool and the app's view.
|
||||
fn band_canvas(scrolls: bool) -> BandCanvas {
|
||||
const DOCUMENT: Size = Size::new(1200.0, 900.0);
|
||||
let tool = Rc::new(RefCell::new(Band { scrolls, hovers: 0 }));
|
||||
/// A canvas inset in the room, so the window has room outside it, shown as an app runs it: the document is zoomed in
|
||||
/// past the canvas, and the app moves its view by the host's `scroll`. The view starts turned by `rotation` degrees.
|
||||
/// Returns the fixture and the app's view.
|
||||
fn scroll_canvas<T: CanvasTool + 'static>(tool: Rc<RefCell<T>>, rotation: f64) -> (Fixture, Rc<Cell<Option<CanvasView>>>) {
|
||||
let view = Rc::new(Cell::new(None::<CanvasView>));
|
||||
let (shown_tool, shown_view) = (Rc::clone(&tool), Rc::clone(&view));
|
||||
let shown_view = Rc::clone(&view);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let room = ui.available_rect_before_wrap();
|
||||
let current = shown_view.get().unwrap_or_else(|| CanvasView::new(room, Point::new(600.0, 450.0), 4.0));
|
||||
let shown = Canvas::new("Document").document(DOCUMENT).view(current).show(ui, |_, _| {});
|
||||
let reply = ToolHost::new().run(ui, &shown.output, &mut *shown_tool.borrow_mut());
|
||||
let current = shown_view.get().unwrap_or_else(|| {
|
||||
let mut start = CanvasView::new(room, Point::new(600.0, 450.0), 4.0);
|
||||
start.rotation = rotation;
|
||||
start
|
||||
});
|
||||
let shown = Canvas::new("Document").document(DOCUMENT).view(current).show_at(ui, room.shrink(40.0), |_, _| {});
|
||||
let reply = ToolHost::new().run(ui, &shown.output, &mut *tool.borrow_mut());
|
||||
let mut next = reply.view.unwrap_or(current);
|
||||
if let Some(step) = reply.scroll
|
||||
&& Autoscroll::scroll(&mut next, step, DOCUMENT).is_some()
|
||||
@@ -180,6 +195,13 @@ fn band_canvas(scrolls: bool) -> BandCanvas {
|
||||
shown_view.set(Some(next));
|
||||
});
|
||||
fixture.settle();
|
||||
(fixture, view)
|
||||
}
|
||||
|
||||
/// The hover autoscroll rig: a `Band` tool. Returns the fixture, the tool and the app's view.
|
||||
fn band_canvas(scrolls: bool) -> BandCanvas {
|
||||
let tool = Rc::new(RefCell::new(Band { scrolls, hovers: 0 }));
|
||||
let (fixture, view) = scroll_canvas(Rc::clone(&tool), 0.0);
|
||||
(fixture, tool, view)
|
||||
}
|
||||
|
||||
@@ -188,22 +210,636 @@ fn a_tool_hovering_near_the_canvas_edge_scrolls_the_view_while_the_pointer_rests
|
||||
let (mut fixture, tool, view) = band_canvas(true);
|
||||
let canvas = fixture.by_role(Role::CANVAS)[0].rect;
|
||||
let centre = |view: &Rc<Cell<Option<CanvasView>>>| view.get().expect("the canvas ran").center;
|
||||
let edge = |dx: f32| Pos2::new(canvas.right() + dx, canvas.center().y);
|
||||
|
||||
let before = centre(&view);
|
||||
fixture.frame(vec![pointer::moved(canvas.center())]).idle(3);
|
||||
assert_eq!(centre(&view), before, "a hover away from the edge scrolls nothing");
|
||||
|
||||
fixture.frame(vec![pointer::moved(Pos2::new(canvas.right() - 4.0, canvas.center().y))]);
|
||||
fixture.frame(vec![pointer::moved(edge(-4.0))]);
|
||||
let (entered, hovers) = (centre(&view), tool.borrow().hovers);
|
||||
fixture.idle(3);
|
||||
let rested = centre(&view);
|
||||
assert!(rested.x > entered.x, "resting at the right edge scrolls the view right: {entered:?} -> {rested:?}");
|
||||
assert_eq!(rested.y, entered.y, "a scroll toward the right edge keeps the height");
|
||||
assert!(tool.borrow().hovers >= hovers + 3, "the tool follows the view as it scrolls under the resting pointer");
|
||||
let in_band = rested.x - entered.x;
|
||||
|
||||
// A pointer outside the canvas still hovers with its position and scrolls at full speed.
|
||||
let (mut fixture, tool, view) = band_canvas(true);
|
||||
fixture.frame(vec![pointer::moved(edge(30.0))]);
|
||||
let (entered, hovers) = (centre(&view), tool.borrow().hovers);
|
||||
fixture.idle(3);
|
||||
let outside = centre(&view).x - entered.x;
|
||||
assert!(outside > 0.0 && outside >= in_band, "outside the canvas the view scrolls at least as fast as in the band: {outside} vs {in_band}");
|
||||
assert!(tool.borrow().hovers >= hovers + 3, "the tool hovers while the pointer rests outside the canvas");
|
||||
|
||||
// A button down scrolls nothing from a hover.
|
||||
let (mut fixture, _, view) = band_canvas(true);
|
||||
fixture.frame(vec![pointer::press(edge(-4.0))]);
|
||||
let entered = centre(&view);
|
||||
fixture.idle(3);
|
||||
assert_eq!(centre(&view), entered, "a pointer with a button down is no hover");
|
||||
|
||||
let (mut fixture, _, view) = band_canvas(false);
|
||||
fixture.frame(vec![pointer::moved(Pos2::new(canvas.right() - 4.0, canvas.center().y))]);
|
||||
fixture.frame(vec![pointer::moved(edge(-4.0))]);
|
||||
let entered = centre(&view);
|
||||
fixture.idle(3);
|
||||
assert_eq!(centre(&view), entered, "a tool that does not autoscroll on hover leaves the view");
|
||||
|
||||
a_hover_past_the_edge_scrolls_nothing_under_a_momentary_tool_a_modal_or_another_canvas();
|
||||
an_open_polygon_keeps_its_vertices_while_the_view_scrolls_under_a_resting_pointer();
|
||||
}
|
||||
|
||||
/// A tool that keeps the points it was clicked at, as a polygon tool keeps its vertices, and autoscrolls on hover.
|
||||
#[derive(Default)]
|
||||
struct Lasso {
|
||||
vertices: Vec<Pos2>,
|
||||
}
|
||||
|
||||
impl CanvasTool for Lasso {
|
||||
fn press(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) -> ToolAction {
|
||||
ToolAction::Claimed
|
||||
}
|
||||
|
||||
fn drag(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {}
|
||||
|
||||
fn release(&mut self, pointer: &ToolPointer, _: &mut ToolContext<'_>) {
|
||||
self.vertices.push(pointer.pos);
|
||||
}
|
||||
|
||||
fn hover(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {}
|
||||
|
||||
fn cancel(&mut self, _: CancelReason, _: &mut ToolContext<'_>) {}
|
||||
|
||||
fn autoscrolls_on_hover(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn paint(&self, _: &Draw<'_>, _: &ToolContext<'_>) {}
|
||||
|
||||
fn command_form(&self) -> ToolPath {
|
||||
ToolPath::Freehand("the lasso only keeps its clicks")
|
||||
}
|
||||
}
|
||||
|
||||
/// What stands between a resting pointer and the hover autoscroll.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Crowd {
|
||||
Nothing,
|
||||
MomentaryHand,
|
||||
SecondCanvas,
|
||||
Modal,
|
||||
}
|
||||
|
||||
/// A `Band` canvas inset in the room with one `Crowd` around it. Returns the fixture, the app's view and the canvas's
|
||||
/// rect.
|
||||
fn crowded_canvas(crowd: Crowd) -> (Fixture, Rc<Cell<Option<CanvasView>>>, Rc<Cell<Rect>>) {
|
||||
let view = Rc::new(Cell::new(None::<CanvasView>));
|
||||
let canvas = Rc::new(Cell::new(Rect::NOTHING));
|
||||
let (shown_view, shown_canvas) = (Rc::clone(&view), Rc::clone(&canvas));
|
||||
let mut tool = Band { scrolls: true, hovers: 0 };
|
||||
let mut momentary = Momentary::new(NavigationOptions::default());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let room = ui.available_rect_before_wrap();
|
||||
let current = shown_view.get().unwrap_or_else(|| CanvasView::new(room, Point::new(600.0, 450.0), 4.0));
|
||||
let area = room.shrink(40.0);
|
||||
let (first, second) = if crowd == Crowd::SecondCanvas {
|
||||
let middle = area.center().x;
|
||||
(
|
||||
Rect::from_min_max(area.min, Pos2::new(middle - 2.0, area.max.y)),
|
||||
Some(Rect::from_min_max(Pos2::new(middle + 2.0, area.min.y), area.max)),
|
||||
)
|
||||
} else {
|
||||
(area, None)
|
||||
};
|
||||
shown_canvas.set(first);
|
||||
let shown = Canvas::new("Document").document(DOCUMENT).view(current).show_at(ui, first, |_, _| {});
|
||||
if let Some(second) = second {
|
||||
Canvas::new("Other").document(DOCUMENT).view(CanvasView::new(second, Point::new(600.0, 450.0), 4.0)).show_at(ui, second, |_, _| {});
|
||||
}
|
||||
if crowd == Crowd::Modal {
|
||||
let mut open = true;
|
||||
Dialog::new("Over the canvas").opened(Bind::bound(&mut open)).show(ui, |ui, _| {
|
||||
Text::new("Modal").show(ui);
|
||||
});
|
||||
}
|
||||
let mut host = ToolHost::new();
|
||||
if crowd == Crowd::MomentaryHand {
|
||||
host = host.momentary(&mut momentary);
|
||||
}
|
||||
let reply = host.run(ui, &shown.output, &mut tool);
|
||||
let mut next = reply.view.unwrap_or(current);
|
||||
if let Some(step) = reply.scroll
|
||||
&& Autoscroll::scroll(&mut next, step, DOCUMENT).is_some()
|
||||
{
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
shown_view.set(Some(next));
|
||||
});
|
||||
fixture.settle();
|
||||
(fixture, view, canvas)
|
||||
}
|
||||
|
||||
fn a_hover_past_the_edge_scrolls_nothing_under_a_momentary_tool_a_modal_or_another_canvas() {
|
||||
for crowd in [Crowd::Nothing, Crowd::MomentaryHand, Crowd::SecondCanvas, Crowd::Modal] {
|
||||
let (mut fixture, view, canvas) = crowded_canvas(crowd);
|
||||
let canvas = canvas.get();
|
||||
// Over the second canvas the pointer is past the first's edge and inside the other's background.
|
||||
let at = Pos2::new(canvas.right() + if crowd == Crowd::SecondCanvas { 10.0 } else { 30.0 }, canvas.center().y);
|
||||
let mut events = vec![pointer::moved(at)];
|
||||
if crowd == Crowd::MomentaryHand {
|
||||
events.push(key_press(Key::Space, Modifiers::NONE));
|
||||
}
|
||||
fixture.frame(events);
|
||||
let entered = view.get().expect("the canvas ran").center;
|
||||
fixture.idle(3);
|
||||
let rested = view.get().expect("the canvas ran").center;
|
||||
if crowd == Crowd::Nothing {
|
||||
assert!(rested.x > entered.x, "the rig scrolls when nothing is in the way: {entered:?} -> {rested:?}");
|
||||
} else {
|
||||
assert_eq!(rested, entered, "{crowd:?}: a pointer resting past the edge scrolls nothing");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn an_open_polygon_keeps_its_vertices_while_the_view_scrolls_under_a_resting_pointer() {
|
||||
let tool = Rc::new(RefCell::new(Lasso::default()));
|
||||
let (mut fixture, view) = scroll_canvas(Rc::clone(&tool), 0.0);
|
||||
let canvas = fixture.by_role(Role::CANVAS)[0].rect;
|
||||
let inside = [canvas.center(), canvas.center() + Vec2::new(30.0, 10.0), canvas.center() + Vec2::new(10.0, 40.0)];
|
||||
for at in inside {
|
||||
fixture.frame(vec![pointer::press(at)]).frame(vec![pointer::release(at)]);
|
||||
}
|
||||
let before = view.get().expect("the canvas ran").center;
|
||||
fixture.frame(vec![pointer::moved(Pos2::new(canvas.right() + 30.0, canvas.center().y))]).idle(4);
|
||||
let after = view.get().expect("the canvas ran").center;
|
||||
assert!(after.x > before.x, "the view scrolls while the polygon is open: {before:?} -> {after:?}");
|
||||
assert_eq!(tool.borrow().vertices, inside, "the vertices stay where they were clicked");
|
||||
}
|
||||
|
||||
type Log = Rc<RefCell<Vec<String>>>;
|
||||
|
||||
/// A tool that logs its calls under its name. It refuses a press while its `refuses` key is held, answers it `Ignored`
|
||||
/// while its `ignores` key is held, and takes the secondary button when `secondary`.
|
||||
struct Probe {
|
||||
name: &'static str,
|
||||
refuses: Option<StandInKey>,
|
||||
ignores: Option<StandInKey>,
|
||||
secondary: bool,
|
||||
every_move: bool,
|
||||
snaps: bool,
|
||||
drags: Vec<(Pos2, f64)>,
|
||||
pass_time: f64,
|
||||
log: Log,
|
||||
}
|
||||
|
||||
impl Probe {
|
||||
fn new(name: &'static str, log: &Log) -> Self {
|
||||
Probe {
|
||||
name,
|
||||
refuses: None,
|
||||
ignores: None,
|
||||
secondary: false,
|
||||
every_move: false,
|
||||
snaps: false,
|
||||
drags: Vec::new(),
|
||||
pass_time: 0.0,
|
||||
log: Rc::clone(log),
|
||||
}
|
||||
}
|
||||
|
||||
fn note(&self, call: &str) {
|
||||
self.log.borrow_mut().push(format!("{} {call}", self.name));
|
||||
}
|
||||
}
|
||||
|
||||
fn holds(key: Option<StandInKey>, mods: Mods) -> bool {
|
||||
match key {
|
||||
Some(StandInKey::Command) => mods.cmd,
|
||||
Some(StandInKey::Alt) => mods.alt,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
impl CanvasTool for Probe {
|
||||
fn each_pass(&mut self, cx: &mut ToolContext<'_>) {
|
||||
self.pass_time = cx.time;
|
||||
if self.snaps {
|
||||
let _ = cx.snap_rect(craft_behavior::kurbo::Rect::new(98.0, 40.0, 198.0, 90.0));
|
||||
}
|
||||
}
|
||||
|
||||
fn press(&mut self, pointer: &ToolPointer, _: &mut ToolContext<'_>) -> ToolAction {
|
||||
self.note("press");
|
||||
if holds(self.ignores, pointer.mods) { ToolAction::Ignored } else { ToolAction::Claimed }
|
||||
}
|
||||
|
||||
fn drag(&mut self, pointer: &ToolPointer, _: &mut ToolContext<'_>) {
|
||||
self.note("drag");
|
||||
self.drags.push((pointer.pos, pointer.time));
|
||||
}
|
||||
|
||||
fn release(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {
|
||||
self.note("release");
|
||||
}
|
||||
|
||||
fn hover(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {
|
||||
self.note("hover");
|
||||
}
|
||||
|
||||
fn cancel(&mut self, _: CancelReason, _: &mut ToolContext<'_>) {
|
||||
self.note("cancel");
|
||||
}
|
||||
|
||||
fn takes(&self, button: PointerButton, mods: Mods) -> bool {
|
||||
(button == PointerButton::Primary || (self.secondary && button == PointerButton::Secondary)) && !holds(self.refuses, mods)
|
||||
}
|
||||
|
||||
fn takes_every_move(&self) -> bool {
|
||||
self.every_move
|
||||
}
|
||||
|
||||
fn paint(&self, _: &Draw<'_>, _: &ToolContext<'_>) {}
|
||||
|
||||
fn cursor(&self, _: &ToolContext<'_>) -> Cursor {
|
||||
Cursor::System(match self.name {
|
||||
"command" => CursorIcon::Crosshair,
|
||||
"alt" => CursorIcon::Wait,
|
||||
_ => CursorIcon::Default,
|
||||
})
|
||||
}
|
||||
|
||||
fn command_form(&self) -> ToolPath {
|
||||
ToolPath::Freehand("the probe only logs")
|
||||
}
|
||||
}
|
||||
|
||||
/// What a `Rig` adds to the host: the momentary tools, a colour for smart guides.
|
||||
#[derive(Default)]
|
||||
struct Setup {
|
||||
momentary: Option<Momentary>,
|
||||
smart_color: Option<DataColor>,
|
||||
/// Set by a trial: the next pass is discarded after the host ran, so egui runs it again in the same frame.
|
||||
rerun: Rc<Cell<bool>>,
|
||||
}
|
||||
|
||||
/// A canvas at 100 % with a `Probe` as the selected tool and two stand-in probes, `command` and `alt`.
|
||||
struct Rig {
|
||||
fixture: Fixture,
|
||||
main: Rc<RefCell<Probe>>,
|
||||
canvas: Rc<Cell<Id>>,
|
||||
log: Log,
|
||||
contexts: Rc<RefCell<Vec<ContextRequest>>>,
|
||||
snapped: Rc<RefCell<Vec<SnapLine>>>,
|
||||
cursor: Rc<RefCell<Option<Cursor>>>,
|
||||
}
|
||||
|
||||
impl Rig {
|
||||
fn new(main: Probe, log: &Log, snap: Option<Snap>) -> Self {
|
||||
Self::with(main, log, snap, Setup::default())
|
||||
}
|
||||
|
||||
fn with(main: Probe, log: &Log, snap: Option<Snap>, mut setup: Setup) -> Self {
|
||||
let main = Rc::new(RefCell::new(main));
|
||||
let (canvas, contexts, snapped) = (Rc::new(Cell::new(Id::NULL)), Rc::new(RefCell::new(Vec::new())), Rc::new(RefCell::new(Vec::new())));
|
||||
let cursor = Rc::new(RefCell::new(None));
|
||||
let (shown_main, shown_canvas, shown_contexts, shown_snapped, shown_cursor) =
|
||||
(Rc::clone(&main), Rc::clone(&canvas), Rc::clone(&contexts), Rc::clone(&snapped), Rc::clone(&cursor));
|
||||
let (mut command, mut alt) = (Probe::new("command", log), Probe::new("alt", log));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let room = ui.available_rect_before_wrap();
|
||||
let mut shown = Canvas::new("Document").document(DOCUMENT).view(CanvasView::new(room, Point::new(600.0, 450.0), 1.0));
|
||||
if let Some(snap) = &snap {
|
||||
shown = shown.snap(snap.clone());
|
||||
}
|
||||
let shown = shown.show(ui, |_, _| {});
|
||||
shown_canvas.set(shown.output.response.id);
|
||||
let mut host = ToolHost::new().stand_in(StandInKey::Command, &mut command).stand_in(StandInKey::Alt, &mut alt).smart_guide_color(setup.smart_color);
|
||||
if let Some(momentary) = setup.momentary.as_mut() {
|
||||
host = host.momentary(momentary);
|
||||
}
|
||||
let reply = host.run(ui, &shown.output, &mut *shown_main.borrow_mut());
|
||||
shown_contexts.borrow_mut().extend(reply.context);
|
||||
shown_snapped.borrow_mut().extend(reply.snapped.iter().copied());
|
||||
if setup.rerun.replace(false) && frame::discardable(ui.ctx()) {
|
||||
frame::discard_pass(ui.ctx(), "a trial reruns the pass");
|
||||
}
|
||||
if reply.cursor.is_some() {
|
||||
*shown_cursor.borrow_mut() = reply.cursor.clone();
|
||||
}
|
||||
});
|
||||
fixture.settle();
|
||||
Rig { fixture, main, canvas, log: Rc::clone(log), contexts, snapped, cursor }
|
||||
}
|
||||
|
||||
fn centre(&mut self) -> Pos2 {
|
||||
self.fixture.by_role(Role::CANVAS)[0].rect.center()
|
||||
}
|
||||
|
||||
fn calls(&self) -> Vec<String> {
|
||||
self.log.borrow().clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_held_command_or_alt_runs_its_stand_in_for_one_gesture() {
|
||||
let log = Log::default();
|
||||
let mut main = Probe::new("main", &log);
|
||||
main.refuses = Some(StandInKey::Command);
|
||||
let mut rig = Rig::new(main, &log, None);
|
||||
let at = rig.centre();
|
||||
|
||||
// Command at the press, up mid-drag: the stand-in keeps the gesture to the release.
|
||||
rig.fixture.hold(Modifiers::COMMAND).frame(vec![pointer::press(at)]).frame(vec![pointer::moved(at + BY)]);
|
||||
rig.fixture.hold(Modifiers::NONE).frame(vec![pointer::moved(at + BY * 2.0)]).frame(vec![pointer::release(at + BY * 2.0)]);
|
||||
let calls = rig.calls();
|
||||
assert_eq!(calls.first().map(String::as_str), Some("command press"), "{calls:?}");
|
||||
assert_eq!(calls.last().map(String::as_str), Some("command release"), "{calls:?}");
|
||||
assert!(calls.iter().all(|call| call.starts_with("command")), "the selected tool saw none of it: {calls:?}");
|
||||
|
||||
// The next plain press is the selected tool's again.
|
||||
rig.log.borrow_mut().clear();
|
||||
rig.fixture.frame(vec![pointer::press(at)]).frame(vec![pointer::release(at)]);
|
||||
assert_eq!(rig.calls().first().map(String::as_str), Some("main press"), "{:?}", rig.calls());
|
||||
|
||||
// With the key held and no gesture, hover is the stand-in's.
|
||||
rig.log.borrow_mut().clear();
|
||||
rig.fixture.hold(Modifiers::COMMAND).frame(vec![pointer::moved(at + BY)]);
|
||||
assert!(rig.calls().iter().any(|call| call == "command hover"), "{:?}", rig.calls());
|
||||
rig.fixture.hold(Modifiers::NONE);
|
||||
|
||||
// A press injected through the host is substituted from its own modifiers.
|
||||
rig.log.borrow_mut().clear();
|
||||
let (ctx, canvas) = (rig.fixture.ctx().clone(), rig.canvas.get());
|
||||
ToolHost::inject(&ctx, canvas, ToolInput::down(PointerButton::Primary, at).mods(Mods::CMD));
|
||||
rig.fixture.idle(1);
|
||||
ToolHost::inject(&ctx, canvas, ToolInput::up(at));
|
||||
rig.fixture.idle(1);
|
||||
let calls = rig.calls();
|
||||
assert_eq!(calls.first().map(String::as_str), Some("command press"), "{calls:?}");
|
||||
assert_eq!(calls.last().map(String::as_str), Some("command release"), "{calls:?}");
|
||||
|
||||
// A selection tool's Ignored Command press reaches the stand-in.
|
||||
let log = Log::default();
|
||||
let mut main = Probe::new("main", &log);
|
||||
main.ignores = Some(StandInKey::Command);
|
||||
let mut rig = Rig::new(main, &log, None);
|
||||
let at = rig.centre();
|
||||
rig.fixture.hold(Modifiers::COMMAND).frame(vec![pointer::press(at)]).frame(vec![pointer::moved(at + BY)]).frame(vec![pointer::release(at + BY)]);
|
||||
let calls = rig.calls();
|
||||
assert_eq!(&calls[..2], ["main press", "command press"], "{calls:?}");
|
||||
assert_eq!(calls.last().map(String::as_str), Some("command release"), "{calls:?}");
|
||||
|
||||
// Alt runs the Alt stand-in.
|
||||
let log = Log::default();
|
||||
let mut main = Probe::new("main", &log);
|
||||
main.refuses = Some(StandInKey::Alt);
|
||||
let mut rig = Rig::new(main, &log, None);
|
||||
let at = rig.centre();
|
||||
rig.fixture.hold(Modifiers::ALT).frame(vec![pointer::press(at)]).frame(vec![pointer::release(at)]);
|
||||
assert_eq!(rig.calls().first().map(String::as_str), Some("alt press"), "{:?}", rig.calls());
|
||||
|
||||
// The hover cursor is the stand-in's while its key is held, no gesture runs and the selected tool does not take
|
||||
// the press.
|
||||
let log = Log::default();
|
||||
let mut main = Probe::new("main", &log);
|
||||
main.refuses = Some(StandInKey::Command);
|
||||
let mut rig = Rig::new(main, &log, None);
|
||||
let at = rig.centre();
|
||||
rig.fixture.hold(Modifiers::COMMAND).frame(vec![pointer::moved(at + BY)]);
|
||||
assert_eq!(*rig.cursor.borrow(), Some(Cursor::System(CursorIcon::Crosshair)), "the Command stand-in's cursor");
|
||||
rig.fixture.hold(Modifiers::NONE).frame(vec![pointer::moved(at + BY * 2.0)]);
|
||||
assert_eq!(*rig.cursor.borrow(), Some(Cursor::System(CursorIcon::Default)), "the selected tool's cursor again");
|
||||
|
||||
// Space's momentary Hand wins over both stand-ins: Command held with Space is the momentary tool's press.
|
||||
let log = Log::default();
|
||||
let mut main = Probe::new("main", &log);
|
||||
main.refuses = Some(StandInKey::Command);
|
||||
let mut rig = Rig::with(main, &log, None, Setup { momentary: Some(Momentary::new(NavigationOptions::default())), ..Setup::default() });
|
||||
let at = rig.centre();
|
||||
rig.fixture.hold(Modifiers::COMMAND).frame(vec![pointer::moved(at), key_press(Key::Space, Modifiers::COMMAND)]);
|
||||
rig.fixture.frame(vec![pointer::press(at)]).frame(vec![pointer::moved(at + BY)]).frame(vec![pointer::release(at + BY)]);
|
||||
assert!(rig.calls().is_empty(), "neither the selected tool nor a stand-in sees a press under a momentary tool: {:?}", rig.calls());
|
||||
|
||||
// With the Hand selected, Cmd at a press is Zoom In, not the Command stand-in.
|
||||
let log = Log::default();
|
||||
let mut main = Probe::new("main", &log);
|
||||
main.refuses = Some(StandInKey::Command);
|
||||
let mut momentary = Momentary::new(NavigationOptions::default());
|
||||
momentary.hand_selected(true);
|
||||
let mut rig = Rig::with(main, &log, None, Setup { momentary: Some(momentary), ..Setup::default() });
|
||||
let at = rig.centre();
|
||||
rig.fixture.hold(Modifiers::COMMAND).frame(vec![pointer::moved(at)]).frame(vec![pointer::press(at)]).frame(vec![pointer::release(at)]);
|
||||
assert!(!rig.calls().iter().any(|call| call == "command press"), "Cmd over the selected Hand is Zoom In: {:?}", rig.calls());
|
||||
}
|
||||
|
||||
/// A canvas under a dialog that keeps the canvas: returns the fixture, the app's view and the canvas's rect.
|
||||
fn kept_canvas<T: CanvasTool + 'static>(tool: Rc<RefCell<T>>) -> (Fixture, Rc<Cell<Option<CanvasView>>>, Rc<Cell<Rect>>) {
|
||||
let view = Rc::new(Cell::new(None::<CanvasView>));
|
||||
let rect = Rc::new(Cell::new(Rect::NOTHING));
|
||||
let (shown_view, shown_rect) = (Rc::clone(&view), Rc::clone(&rect));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let room = ui.available_rect_before_wrap();
|
||||
let current = shown_view.get().unwrap_or_else(|| CanvasView::new(room, Point::new(600.0, 450.0), 1.0));
|
||||
let shown = Canvas::new("Document").document(DOCUMENT).view(current).show_at(ui, room, |_, _| {});
|
||||
shown_rect.set(room);
|
||||
let id = shown.output.response.id;
|
||||
let mut open = true;
|
||||
Dialog::new("Keeps the canvas").opened(Bind::bound(&mut open)).show(ui, |ui, cx| {
|
||||
cx.keep_view_open(id);
|
||||
Text::new("Pick").show(ui);
|
||||
});
|
||||
let reply = ToolHost::new().run(ui, &shown.output, &mut *tool.borrow_mut());
|
||||
shown_view.set(Some(reply.view.unwrap_or(current)));
|
||||
});
|
||||
fixture.settle();
|
||||
(fixture, view, rect)
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_view_only_tool_drags_under_a_modal_that_keeps_the_canvas() {
|
||||
let hand = Rc::new(RefCell::new(HandTool::new(NavigationOptions::default())));
|
||||
let (mut fixture, view, rect) = kept_canvas(hand);
|
||||
let at = rect.get().center();
|
||||
let before = view.get().expect("the canvas ran").center;
|
||||
fixture.frame(vec![pointer::press(at)]).frame(vec![pointer::moved(at + BY)]).frame(vec![pointer::moved(at + BY * 2.0)]);
|
||||
fixture.frame(vec![pointer::release(at + BY * 2.0)]);
|
||||
assert_ne!(view.get().expect("the canvas ran").center, before, "a Hand drag pans under the modal");
|
||||
|
||||
let tool = Rc::new(RefCell::new(Recorder::default()));
|
||||
let (mut fixture, _, rect) = kept_canvas(Rc::clone(&tool));
|
||||
let at = rect.get().center();
|
||||
fixture.frame(vec![pointer::press(at)]).frame(vec![pointer::moved(at + BY)]).frame(vec![pointer::release(at + BY)]);
|
||||
assert_eq!(tool.borrow().count(Call::Press), 0, "a drawing tool's press stays blocked: {:?}", tool.borrow().calls);
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn matched_smart_lines_are_drawn_and_reported() {
|
||||
let shapes = |smart: bool, color: Option<DataColor>| {
|
||||
let log = Log::default();
|
||||
let mut targets = SnapTargets::new();
|
||||
targets.add(SnapTarget::new(Axis::Y, 100.0, SnapKind::LayerEdge));
|
||||
let mut options = SnapOptions::default();
|
||||
options.smart_guides = smart;
|
||||
let mut main = Probe::new("main", &log);
|
||||
main.snaps = true;
|
||||
let mut rig = Rig::with(main, &log, Some(Snap::new(Arc::new(targets), options)), Setup { smart_color: color, ..Setup::default() });
|
||||
rig.fixture.idle(2);
|
||||
let reported = rig.snapped.borrow().len();
|
||||
(rig.fixture.frame_shapes(), reported)
|
||||
};
|
||||
let (on, reported_on) = shapes(true, None);
|
||||
let (off, reported_off) = shapes(false, None);
|
||||
let (on, off) = (on.len(), off.len());
|
||||
assert!(reported_on > 0 && reported_off > 0, "the lines reach the response whatever the option: {reported_on}, {reported_off}");
|
||||
assert!(on > off, "smart kinds are painted only with Smart Guides on: {on} shapes vs {off}");
|
||||
|
||||
let color = Color32::from_rgb(12, 200, 34);
|
||||
let (coloured, _) = shapes(true, Some(DataColor(color)));
|
||||
assert!(coloured.iter().any(|shape| strokes_in(shape, color)), "a smart line is drawn in `smart_guide_color` when it is set");
|
||||
let (plain, _) = shapes(true, None);
|
||||
assert!(!plain.iter().any(|shape| strokes_in(shape, color)), "and not otherwise");
|
||||
}
|
||||
|
||||
/// Whether `shape` or a shape inside it is a line or path stroked in `color`.
|
||||
fn strokes_in(shape: &Shape, color: Color32) -> bool {
|
||||
match shape {
|
||||
Shape::Vec(shapes) => shapes.iter().any(|shape| strokes_in(shape, color)),
|
||||
Shape::LineSegment { stroke, .. } => stroke.color == color,
|
||||
Shape::Path(path) => path.stroke.color == egui::epaint::ColorMode::Solid(color),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_tool_that_takes_every_move_gets_each_move_of_a_pass_in_order() {
|
||||
for every in [true, false] {
|
||||
let log = Log::default();
|
||||
let mut main = Probe::new("main", &log);
|
||||
main.every_move = every;
|
||||
let rerun = Rc::new(Cell::new(false));
|
||||
let mut rig = Rig::with(main, &log, None, Setup { rerun: Rc::clone(&rerun), ..Setup::default() });
|
||||
let at = rig.centre();
|
||||
let path = [at + Vec2::new(20.0, 0.0), at + Vec2::new(40.0, 5.0), at + Vec2::new(60.0, 10.0)];
|
||||
rig.fixture.frame(vec![pointer::press(at)]);
|
||||
// The frame's pass runs twice: the moves reach the tool once.
|
||||
rerun.set(true);
|
||||
rig.fixture.frame(path.iter().map(|to| pointer::moved(*to)).collect());
|
||||
let main = rig.main.borrow();
|
||||
if every {
|
||||
let seen: Vec<Pos2> = main.drags.iter().map(|(pos, _)| *pos).collect();
|
||||
assert_eq!(seen, path, "each move of the pass reaches the tool, in order");
|
||||
assert!(main.drags.windows(2).all(|pair| pair[0].1 <= pair[1].1), "times rise: {:?}", main.drags);
|
||||
assert_eq!(main.drags.last().map(|(_, time)| *time), Some(main.pass_time), "the last move is at the pass time");
|
||||
} else {
|
||||
assert_eq!(main.drags.len(), 1, "a tool that does not ask gets one call: {:?}", main.drags);
|
||||
assert_eq!(main.drags[0].0, path[2], "at the last position");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_secondary_click_the_tool_did_not_take_asks_for_the_menu() {
|
||||
let log = Log::default();
|
||||
let mut rig = Rig::new(Probe::new("main", &log), &log, None);
|
||||
let at = rig.centre();
|
||||
rig.fixture.hold(Modifiers::SHIFT).frame(vec![pointer::secondary(at, true)]);
|
||||
rig.fixture.hold(Modifiers::NONE).frame(vec![pointer::secondary(at, false)]);
|
||||
let asked = rig.contexts.borrow().clone();
|
||||
assert_eq!(asked.len(), 1, "{asked:?}");
|
||||
assert_eq!(asked[0].at, at);
|
||||
assert!(asked[0].mods.shift, "the modifiers are those held at the press: {:?}", asked[0]);
|
||||
assert_eq!(asked[0].momentary, None);
|
||||
|
||||
// The Menu key asks at the view's centre.
|
||||
rig.contexts.borrow_mut().clear();
|
||||
rig.fixture.frame(vec![pointer::press(at)]).frame(vec![pointer::release(at)]);
|
||||
rig.fixture.key(Key::F10, Modifiers::SHIFT).settle();
|
||||
let asked = rig.contexts.borrow().clone();
|
||||
assert_eq!(asked.first().map(|request| request.at), Some(at), "{asked:?}");
|
||||
|
||||
// A press the tool took asks for nothing.
|
||||
let log = Log::default();
|
||||
let mut taker = Probe::new("main", &log);
|
||||
taker.secondary = true;
|
||||
let mut rig = Rig::new(taker, &log, None);
|
||||
let at = rig.centre();
|
||||
rig.fixture.frame(vec![pointer::secondary(at, true)]).frame(vec![pointer::secondary(at, false)]);
|
||||
assert!(rig.contexts.borrow().is_empty(), "{:?}", rig.contexts.borrow());
|
||||
|
||||
// A press on the scroll bars reports none.
|
||||
let (mut fixture, contexts, _, rect) = menu_canvas(false, true);
|
||||
let on_bar = Pos2::new(rect.get().center().x, rect.get().bottom() - 3.0);
|
||||
fixture.frame(vec![pointer::secondary(on_bar, true)]).frame(vec![pointer::secondary(on_bar, false)]);
|
||||
assert!(contexts.borrow().is_empty(), "{:?}", contexts.borrow());
|
||||
|
||||
// With Space held a secondary drag pans with the momentary Hand and reports none.
|
||||
let (mut fixture, contexts, view, rect) = menu_canvas(true, false);
|
||||
let at = rect.get().center();
|
||||
let before = view.get().expect("the canvas ran").center;
|
||||
fixture.frame(vec![pointer::moved(at), key_press(Key::Space, Modifiers::NONE)]);
|
||||
fixture.frame(vec![pointer::secondary(at, true)]).frame(vec![pointer::moved(at + BY)]).frame(vec![pointer::moved(at + BY * 2.0)]);
|
||||
fixture.frame(vec![pointer::secondary(at + BY * 2.0, false)]);
|
||||
assert_ne!(view.get().expect("the canvas ran").center, before, "the secondary drag pans");
|
||||
assert!(contexts.borrow().is_empty(), "{:?}", contexts.borrow());
|
||||
|
||||
// The selected Hand does not take the secondary button: its click asks for the menu.
|
||||
let (mut fixture, contexts, _, rect) = menu_canvas(false, false);
|
||||
let at = rect.get().center();
|
||||
fixture.frame(vec![pointer::secondary(at, true)]).frame(vec![pointer::secondary(at, false)]);
|
||||
assert_eq!(contexts.borrow().len(), 1, "{:?}", contexts.borrow());
|
||||
}
|
||||
|
||||
/// A canvas with the Hand selected, with the momentary set when `momentary` and scroll bars in its body when `bars`.
|
||||
/// Returns the fixture, the menu requests, the app's view and the canvas's rect.
|
||||
fn menu_canvas(
|
||||
momentary: bool,
|
||||
bars: bool,
|
||||
) -> (Fixture, Rc<RefCell<Vec<ContextRequest>>>, Rc<Cell<Option<CanvasView>>>, Rc<Cell<Rect>>) {
|
||||
let (contexts, view, rect) = (Rc::new(RefCell::new(Vec::new())), Rc::new(Cell::new(None::<CanvasView>)), Rc::new(Cell::new(Rect::NOTHING)));
|
||||
let (shown_contexts, shown_view, shown_rect) = (Rc::clone(&contexts), Rc::clone(&view), Rc::clone(&rect));
|
||||
let mut hand = HandTool::new(NavigationOptions::default());
|
||||
let mut set = Momentary::new(NavigationOptions::default());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let room = ui.available_rect_before_wrap();
|
||||
let current = shown_view.get().unwrap_or_else(|| CanvasView::new(room, Point::new(600.0, 450.0), 4.0));
|
||||
shown_rect.set(room);
|
||||
let shown = Canvas::new("Document").document(DOCUMENT).view(current).show_at(ui, room, |ui, body| {
|
||||
if bars {
|
||||
let mut bar_view = current;
|
||||
CanvasScrollbars::new("Scroll bars", Bind::bound(&mut bar_view), craft_behavior::kurbo::Rect::from_origin_size(Point::ZERO, DOCUMENT)).show_at(ui, body.rect);
|
||||
}
|
||||
});
|
||||
let mut host = ToolHost::new();
|
||||
if momentary {
|
||||
host = host.momentary(&mut set);
|
||||
}
|
||||
let reply = host.run(ui, &shown.output, &mut hand);
|
||||
shown_contexts.borrow_mut().extend(reply.context);
|
||||
shown_view.set(Some(reply.view.unwrap_or(current)));
|
||||
});
|
||||
fixture.settle();
|
||||
(fixture, contexts, view, rect)
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn a_drag_past_the_canvas_edge_scrolls_the_view_and_a_turned_view_scrolls_on_the_clipped_axis() {
|
||||
for (rotation, upright) in [(0.0, true), (90.0, false)] {
|
||||
let tool = Rc::new(RefCell::new(Recorder::default()));
|
||||
let (mut fixture, view) = scroll_canvas(Rc::clone(&tool), rotation);
|
||||
let canvas = fixture.by_role(Role::CANVAS)[0].rect;
|
||||
let start = canvas.center();
|
||||
let before = view.get().expect("the canvas ran").center;
|
||||
fixture.frame(vec![pointer::press(start)]);
|
||||
fixture.frame(vec![pointer::moved(Pos2::new(canvas.right() + 25.0, start.y))]).idle(3);
|
||||
let after = view.get().expect("the canvas ran").center;
|
||||
if upright {
|
||||
assert!(after.x > before.x && (after.y - before.y).abs() < 1e-6, "scrolls along x: {before:?} -> {after:?}");
|
||||
} else {
|
||||
assert!(after.y != before.y && (after.x - before.x).abs() < 1e-6, "a view turned 90 degrees scrolls along y: {before:?} -> {after:?}");
|
||||
}
|
||||
fixture.frame(vec![pointer::release(Pos2::new(canvas.right() + 25.0, start.y))]);
|
||||
assert_eq!(tool.borrow().count(Call::Press), 1, "{:?}", tool.borrow().calls);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,8 +12,11 @@
|
||||
use craft_behavior::geometry::CropBox;
|
||||
use craft_behavior::kurbo::{Point, Rect};
|
||||
use craft_behavior::{CancelReason, CanvasView};
|
||||
use craft_keymap::{Chord, Key as ChordKey, Mods};
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::canvas::{CanvasTool, CropOverlay, ToolAccess, ToolAction, ToolClaims, ToolContext, ToolKey, ToolPath, ToolPointer};
|
||||
use craft_ui::contract::{Bind, Show as _};
|
||||
use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
|
||||
use craft_ui::popover::Popover;
|
||||
use craft_ui::primitives::Draw;
|
||||
use craft_ui::testing::access::Declared;
|
||||
use craft_ui::testing::focus::{AccessActionKind, key_release};
|
||||
@@ -170,6 +173,74 @@ fn with_no_session_control_the_arrows_and_enter_reach_the_tool_with_nothing_focu
|
||||
assert!(matches!(seen[..], [ToolKey::Nudge { .. }, ToolKey::Submit]), "{seen:?}");
|
||||
}
|
||||
|
||||
/// The chords `Claimer` takes through `ToolClaims::keys`.
|
||||
fn enter_and_escape() -> &'static [Chord] {
|
||||
static KEYS: std::sync::OnceLock<[Chord; 2]> = std::sync::OnceLock::new();
|
||||
KEYS.get_or_init(|| [Chord::new(Mods::NONE, ChordKey::Enter), Chord::new(Mods::NONE, ChordKey::Escape)])
|
||||
}
|
||||
|
||||
/// A tool that claims Enter and Escape as single chords and takes every key it is offered.
|
||||
#[derive(Default)]
|
||||
struct Claimer {
|
||||
seen: Vec<ToolKey>,
|
||||
}
|
||||
|
||||
impl CanvasTool for Claimer {
|
||||
fn claims(&self) -> ToolClaims {
|
||||
ToolClaims::NONE.keys(enter_and_escape())
|
||||
}
|
||||
|
||||
fn press(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) -> ToolAction {
|
||||
ToolAction::Ignored
|
||||
}
|
||||
|
||||
fn drag(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {}
|
||||
|
||||
fn release(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {}
|
||||
|
||||
fn cancel(&mut self, _: CancelReason, _: &mut ToolContext<'_>) {}
|
||||
|
||||
fn key(&mut self, key: &ToolKey, _: &mut ToolContext<'_>) -> bool {
|
||||
self.seen.push(key.clone());
|
||||
true
|
||||
}
|
||||
|
||||
fn paint(&self, _: &Draw<'_>, _: &ToolContext<'_>) {}
|
||||
|
||||
fn command_form(&self) -> ToolPath {
|
||||
ToolPath::Command("the claimer's form")
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn an_open_layer_takes_enter_and_escape_before_a_tools_claim() {
|
||||
let open = Rc::new(Cell::new(false));
|
||||
let shown = Rc::clone(&open);
|
||||
let mut canvas = ToolFixture::with_body("Document", Claimer::default(), move |ui, _| {
|
||||
let opener = Button::new("Options").show(ui);
|
||||
let mut is_open = shown.get();
|
||||
Popover::new("Options panel", Bind::bound(&mut is_open)).opened_by(&opener).show(ui, |ui, _| {
|
||||
let _ = Button::new("Item").show(ui);
|
||||
});
|
||||
shown.set(is_open);
|
||||
});
|
||||
canvas.fixture().settle();
|
||||
open.set(true);
|
||||
canvas.fixture().idle(4);
|
||||
// The layer's keys come first: Enter goes to it, and Escape closes it.
|
||||
canvas.fixture().key(Key::Enter, Modifiers::NONE).key(Key::Escape, Modifiers::NONE).settle();
|
||||
assert!(canvas.tool().seen.is_empty(), "the open layer took both keys: {:?}", canvas.tool().seen);
|
||||
assert!(!open.get(), "Escape closed the layer");
|
||||
canvas.fixture().idle(10);
|
||||
// Escape returned focus to the opener, whose Enter it is; the tool's chords hold while the canvas has focus, and
|
||||
// the canvas is the stop before the opener.
|
||||
canvas.fixture().key(Key::Tab, Modifiers::SHIFT).settle();
|
||||
assert_eq!(canvas.fixture().focused_stop().map(|(id, _)| id), Some(canvas.canvas_id()), "Shift+Tab focuses the canvas");
|
||||
canvas.fixture().key(Key::Enter, Modifiers::NONE).key(Key::Escape, Modifiers::NONE).settle();
|
||||
let kept = canvas.tool().seen.iter().filter(|key| matches!(key, ToolKey::Kept(_))).count();
|
||||
assert_eq!(kept, 2, "with the layer closed both chords reach the tool as Kept: {:?}", canvas.tool().seen);
|
||||
}
|
||||
|
||||
/// A marker the arrows move one unit along x while `held`; it describes itself as `Marker` at its place.
|
||||
struct Marker {
|
||||
held: bool,
|
||||
|
||||
Reference in New Issue
Block a user