diff --git a/Cargo.lock b/Cargo.lock index 416765ba8..67fd57e64 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3050,6 +3050,7 @@ dependencies = [ "craft-ui-test-kit", "egui", "serde", + "serde_json", ] [[package]] diff --git a/crates/behavior/src/geometry/crop.rs b/crates/behavior/src/geometry/crop.rs index 3fedc8d8a..df9b01c8f 100644 --- a/crates/behavior/src/geometry/crop.rs +++ b/crates/behavior/src/geometry/crop.rs @@ -500,6 +500,14 @@ pub enum CropGuide { GoldenSpiral, } +/// The lines of the grid a default-mode turn shows over a `w` by `h` frame: `step` apart counted from the frame's +/// centre, none on the outline, only inside `visible`; empty for a frame under one point or non-finite input. +#[allow(dead_code)] // P3(tools-w15): tl.T43 +pub fn turn_grid(w: f64, h: f64, step: f64, visible: kurbo::Rect) -> Vec> { + let _ = (w, h, step, visible); + todo!("tl.T43") +} + impl CropGuide { /// Every guide, in the order `next` cycles through. pub const ALL: [CropGuide; 6] = [Self::Thirds, Self::Grid, Self::Diagonal, Self::Triangle, Self::GoldenRatio, Self::GoldenSpiral]; diff --git a/crates/behavior/src/geometry/mod.rs b/crates/behavior/src/geometry/mod.rs index dcc4650d3..68ced9620 100644 --- a/crates/behavior/src/geometry/mod.rs +++ b/crates/behavior/src/geometry/mod.rs @@ -15,7 +15,7 @@ pub mod quad; pub mod selection_op; pub mod snap; -pub use crop::{AspectHold, CropBox, CropGuide, GuideShow, crop_view, crop_view_about, hit_rect, screen_step}; +pub use crop::{AspectHold, CropBox, CropGuide, GuideShow, crop_view, crop_view_about, hit_rect, screen_step, turn_grid}; pub use draft::{DraftEvent, DraftKind, DraftPoint, DraftReach, OutlineDraft}; pub use lock::{Directions, LOCK_HYSTERESIS_DEGREES, lock_direction, polygon_step, round_to_direction, turn_to_45}; pub use marquee::{Constraint, MarqueeGesture, MarqueeRect, fixed_size_pixels, marquee_pixels, square_pixels}; diff --git a/crates/behavior/src/press.rs b/crates/behavior/src/press.rs index dc9adf03d..23a5fbb5a 100644 --- a/crates/behavior/src/press.rs +++ b/crates/behavior/src/press.rs @@ -106,6 +106,13 @@ impl PointerSample { pub const fn new(pressure: f32) -> Self { PointerSample { pressure, tilt: [0.0, 0.0], rotation: 0.0, eraser: false } } + + /// The sample with every field in range: pressure within 0 to 1, tilt and rotation finite radians, a stray value + /// replaced by its neutral one. + #[must_use] + pub fn sanitized(self) -> Self { + todo!("cw.C73") + } } /// A two-finger gesture. @@ -329,8 +336,13 @@ pub fn count_clicks(previous: Option<(Pos2, f64, u32, Mods)>, pos: Pos2, time: f #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub enum PointerEvent { - /// The pointer moved. - Moved(Pos2), + /// The pointer moved, with the pen's reading for the move when the runtime has one. + Moved { + /// Where the pointer is. + at: Pos2, + /// The pen's reading paired with this move, interpolated from the tablet's samples. + sample: Option, + }, /// A button went down. #[non_exhaustive] Pressed { @@ -522,7 +534,7 @@ impl PressMachine { } for event in input.events { match *event { - PointerEvent::Moved(at) => { + PointerEvent::Moved { at, .. } => { pos = at; if let Some(open) = &mut self.open && open.released_at.is_none() @@ -690,7 +702,7 @@ mod tests { let second = press(0.0, 1.1); assert_eq!(phases(&[&[press(0.0, 1.0)], &[up, second], &[up], &[]], Sense::CLICK), "D R! D R!"); // The second press's drag starts in the pass that owes its Down, and the button goes up there too. - let far = PointerEvent::Moved(pos2(40.0, 0.0)); + let far = PointerEvent::Moved { at: pos2(40.0, 0.0), sample: None }; let passes: [&[PointerEvent]; 5] = [&[press(0.0, 1.0)], &[up, second], &[far, up], &[], &[]]; assert_eq!(phases(&passes, Sense::CLICK | Sense::DRAG), "D R! D S R"); } diff --git a/crates/ui-canvas/Cargo.toml b/crates/ui-canvas/Cargo.toml index 463d8c56f..fe58c3059 100644 --- a/crates/ui-canvas/Cargo.toml +++ b/crates/ui-canvas/Cargo.toml @@ -28,6 +28,7 @@ craft-ui-macros = { workspace = true } egui = { workspace = true } craft-i18n = { workspace = true, features = ["collate"] } serde = { workspace = true } +serde_json = { workspace = true } [dev-dependencies] craft-ui-canvas = { path = ".", features = ["testing"] } diff --git a/crates/ui-canvas/src/canvas/crop/gesture.rs b/crates/ui-canvas/src/canvas/crop/gesture.rs index 1abd66a5d..beaea7f4c 100644 --- a/crates/ui-canvas/src/canvas/crop/gesture.rs +++ b/crates/ui-canvas/src/canvas/crop/gesture.rs @@ -81,10 +81,12 @@ impl Rules<'_> { let keep = (r.width() > 0.0 && r.height() > 0.0).then(|| r.width() / r.height()); let ratio = self.ratio.or(if mods.shift { keep } else { None }); let by = to - drag.from; + // P3(tools-w15): tl.T41 + let hold = ratio.map_or(craft_behavior::geometry::AspectHold::Free, craft_behavior::geometry::AspectHold::Ratio); let next = if self.image && self.auto_center { - at.resized_centred(*part, by, ratio, mods.alt)? + at.resized_centred(*part, by, hold, mods.alt)? } else { - at.resized(*part, by, ratio, mods.alt) + at.resized(*part, by, hold, mods.alt) }; (next, true, ratio.is_some()) } diff --git a/crates/ui-canvas/src/canvas/crop/mod.rs b/crates/ui-canvas/src/canvas/crop/mod.rs index d5456d341..424342bb6 100644 --- a/crates/ui-canvas/src/canvas/crop/mod.rs +++ b/crates/ui-canvas/src/canvas/crop/mod.rs @@ -27,7 +27,7 @@ use craft_keymap::{Chord, Key, Mods, Platform}; use egui::{Pos2, Rect, Response, Vec2}; use gesture::{Drag, Kind, Rules}; -pub use shield::{CropShield, ShieldColor}; +pub use shield::{CropShield, ShieldColor, paint_outside}; /// A part of the frame: `FRAME.at(part.index())` with the whole frame at 0, the corners at 1 to 4 and the edges at 5 /// to 8, so the keyboard order is the whole frame and then the corners and the edges clockwise. @@ -154,6 +154,9 @@ pub struct CropOverlay<'a> { /// middle of the canvas. #[prop(flag)] auto_center: bool, + /// Nothing is painted and a press anywhere on the canvas draws a new frame. + #[prop(flag)] + hidden: bool, /// The snap targets a dragged part snaps to. #[prop] snap: Option<&'a SnapTargets>, @@ -176,6 +179,7 @@ impl<'a> CropOverlay<'a> { bounds: None, image_mode: false, auto_center: false, + hidden: false, snap: None, report: Report::default(), } @@ -417,6 +421,11 @@ pub struct CropOverlayOutput { pub turning: Option, /// The size Enter would crop to while the frame is drawn or resized. pub sizing: Option<(f64, f64)>, + /// The pointer of a draw, a classic move or a resize that is not live-centred: the crop tool hands it to + /// `ToolContext::autoscroll_at`; `None` for a turn, an image-mode move and a Straighten line. + pub scrolls_at: Option, + /// True in the pass a Straighten press is released or cancelled, whatever its length. + pub straighten_ended: bool, } impl Outcome for CropOverlayOutput { @@ -643,6 +652,8 @@ impl Component for CropOverlay<'_> { nudged, turning, sizing, + scrolls_at: None, // P3(tools-w15): tl.T43 + straighten_ended: false, // P3(tools-w15): tl.T43 } } } diff --git a/crates/ui-canvas/src/canvas/crop/shield.rs b/crates/ui-canvas/src/canvas/crop/shield.rs index 1b25b1aa5..953f2a98c 100644 --- a/crates/ui-canvas/src/canvas/crop/shield.rs +++ b/crates/ui-canvas/src/canvas/crop/shield.rs @@ -1,6 +1,10 @@ //! The crop shield: the options that dim the area outside the frame. -use egui::Color32; +use crate::primitives::{Draw, PaintShape}; +use crate::style::DataColor; +use craft_behavior::geometry::outside_pieces; +use craft_behavior::kurbo::Point; +use egui::{Color32, Pos2}; /// Default shield opacity, in percent. const SHIELD_OPACITY: f32 = 75.0; @@ -58,7 +62,30 @@ impl Default for CropShield { } } +/// Paints `fill` over the canvas quad outside the convex `hole`, in screen points: one polygon per convex piece of +/// [`outside_pieces`]. The one shield painter for both crops. +pub fn paint_outside(draw: &Draw<'_>, canvas: [Pos2; 4], hole: &[Pos2], fill: DataColor) { + let point = |p: Pos2| Point::new(f64::from(p.x), f64::from(p.y)); + let hole: Vec = hole.iter().copied().map(point).collect(); + for piece in outside_pieces(canvas.map(point), &hole) { + let piece = piece.into_iter().map(|p| Pos2::new(p.x as f32, p.y as f32)).collect(); + draw.data_fill(&PaintShape::Polygon(piece), fill); + } +} + impl CropShield { + /// The Perspective Crop's shield: enabled, a custom grey, 18 % opacity, no auto adjust, cropped area shown. + pub const PERSPECTIVE: CropShield = CropShield { + show_cropped_area: true, + enabled: true, + color: ShieldColor::Custom, + custom_color: [89, 89, 89], + auto_center_preview: true, + opacity: 18.0, + auto_adjust: false, + classic_mode: false, + }; + /// Show Cropped Area as it acts: always on in Classic mode (the stored choice is kept for the default mode). pub fn shows_cropped_area(&self) -> bool { self.classic_mode || self.show_cropped_area diff --git a/crates/ui-canvas/src/canvas/full_window.rs b/crates/ui-canvas/src/canvas/full_window.rs index d24f7fba3..3c9413ece 100644 --- a/crates/ui-canvas/src/canvas/full_window.rs +++ b/crates/ui-canvas/src/canvas/full_window.rs @@ -3,7 +3,7 @@ use super::full_window_parts::SideFooter; use crate::canvas::ViewCommands; use crate::contract::{ - Bind, BindMut, BodyCx, Common, Component, Container, ContainerProps, Cx, EndRegion, FooterPlace, FooterRegion, HeaderRegion, Mount, Pad, + Bind, BindMut, BodyCx, Common, Component, Container, ContainerProps, Cx, EndRegion, FooterPlace, FooterRegion, HeaderRegion, Mount, Overlay, Pad, Props as _, Role, SaveKey, }; use crate::dialog::frame::{self, DialogOutput, FOOTER, FooterCx, FooterFn, FooterHooks}; @@ -12,12 +12,13 @@ use crate::runtime::commands::{self, CommandScope, CommandSet as _}; use crate::runtime::env::Label; use crate::runtime::focus::{EnterRule, FocusPolicy, Initial}; use crate::runtime::overlay::CloseReason; +use crate::runtime::windows::WindowSpec; use crate::sections::FooterButton; use crate::style::{ComponentStyle, StyleCx, SurfaceKind}; use craft_behavior::{Metrics, Sense}; use egui::Ui; -pub use hosted::{FullWindowWorkspace, HostedWorkspace, WorkspacePass}; +pub use hosted::{FullWindowWorkspace, HostedWorkspace, WorkspaceCx, WorkspacePass}; mod hosted; #[cfg(feature = "testing")] @@ -120,6 +121,15 @@ impl<'a> FullWindowDialog<'a> { .label(title) } + /// Shows the dialog in its own OS window described by `spec`, resizable, opening at the saved placement; where + /// viewports are unavailable it fills the main window. The dialog's focus policy moves into the fallback overlay. + #[must_use] + pub fn own_window(mut self, spec: WindowSpec) -> Self { + self.props.mount = Mount::viewport_with(Overlay::full_window(self.props.focus), spec); + self.props.focus = FocusPolicy::NONE; + self + } + /// Who gets Enter: the dialog's submit, or the body. #[must_use] pub fn enter(mut self, rule: EnterRule) -> Self { diff --git a/crates/ui-canvas/src/canvas/full_window/hosted.rs b/crates/ui-canvas/src/canvas/full_window/hosted.rs index c8ad45657..1c69bfcaf 100644 --- a/crates/ui-canvas/src/canvas/full_window/hosted.rs +++ b/crates/ui-canvas/src/canvas/full_window/hosted.rs @@ -2,10 +2,11 @@ use std::sync::Arc; -use egui::{Response, Ui}; +use egui::{Context, Response, Ui}; use crate::contract::Bind; -use crate::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id}; +use crate::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id}; +use crate::runtime::env::Label; /// A full-window workspace (Liquify, Filter Gallery, Select and Mask) that a [`HostedWorkspace`] shows on the app's /// [`DialogHost`](crate::dialog::DialogHost). The workspace keeps its session and view; the app's side of it (the @@ -27,7 +28,45 @@ pub trait FullWindowWorkspace: Send + 'static { /// Shows one pass of the workspace's [`FullWindowDialog`](crate::dialog::FullWindowDialog), whose open state /// it binds to `open` ([`opened`](crate::dialog::FullWindowDialog::opened)). - fn show(&mut self, ui: &mut Ui, source: &Self::Source, open: Bind<'_, bool>) -> WorkspacePass; + fn show(&mut self, ui: &mut Ui, cx: WorkspaceCx<'_, Self::Source>) -> WorkspacePass; + + /// The workspace's fields as JSON for the automation surface; `None` when it has none. + fn json_fields(&self) -> Option { + None + } + + /// Sets one field of the workspace; each key applies or is refused on its own. Refuses every key by default. + fn set_json_field(&mut self, ctx: &Context, source: &Self::Source, field: &str, value: serde_json::Value) -> Result<(), String> { + let _ = (ctx, source, value); + Err(FieldRefusal::NoFields.message(field)) + } + + /// Answers OK for the automation surface; `None` when the workspace has no answer to give. + fn confirm(&mut self, ctx: &Context, source: &Self::Source) -> Option { + let _ = (ctx, source); + None + } + + /// The app refused the OK the workspace held: `reason` is shown. Does nothing by default. + fn ok_failed(&mut self, reason: Label) { + let _ = reason; + } +} + +/// What the host hands a [`FullWindowWorkspace`] each pass. +#[non_exhaustive] +pub struct WorkspaceCx<'a, S: ?Sized> { + /// What the workspace reads from the app. + pub source: &'a S, + /// Counts the source changes under an open workspace; the workspace adds it to its pending key, so a document edit + /// previews again and a late preview of the old pixels is dropped. + pub revision: u64, + /// The workspace dialog's open state. + pub open: Bind<'a, bool>, + /// OK is held: the workspace waits for the app's answer before it closes. + pub hold_ok: bool, + /// The app's answer to OK is pending. + pub ok_waits: bool, } /// What one pass of a [`FullWindowWorkspace`] reports. @@ -76,6 +115,9 @@ pub struct HostedWorkspace { source: Arc, events: Vec, open: bool, + revision: u64, + hold_ok: bool, + ok_waits: bool, #[cfg(feature = "testing")] facts: crate::testing::StoryOutput, } @@ -89,6 +131,9 @@ impl HostedWorkspace { source, events: Vec::new(), open: true, + revision: 0, + hold_ok: false, + ok_waits: false, #[cfg(feature = "testing")] facts: crate::testing::StoryOutput::default(), } @@ -107,6 +152,26 @@ impl HostedWorkspace { /// The source the next pass reads. pub fn set_source(&mut self, source: Arc) { self.source = source; + self.revision += 1; + } + + /// OK waits for the app's answer ([`answer_ok`](Self::answer_ok)) instead of closing the workspace at once. + #[must_use] + pub fn held_ok(mut self) -> Self { + self.hold_ok = true; + self + } + + /// The OK the workspace is holding for the app to act on, once; `None` when none is held. + pub fn take_ok(&mut self) -> Option { + todo!("dl.K57") + } + + /// The app's answer to a held OK: `Ok` closes the workspace with it, `Err(reason)` keeps it open and shows + /// `reason`. + pub fn answer_ok(&mut self, answer: Result<(), Label>) { + let _ = answer; + todo!("dl.K57") } /// The events of the passes since the last call, in order. @@ -123,7 +188,14 @@ impl StackDialog for HostedWorkspace { } fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { - let pass = self.workspace.show(ui, &self.source, Bind::bound(&mut self.open)); + let cx = WorkspaceCx { + source: &*self.source, + revision: self.revision, + open: Bind::bound(&mut self.open), + hold_ok: self.hold_ok, + ok_waits: self.ok_waits, + }; + let pass = self.workspace.show(ui, cx); #[cfg(feature = "testing")] { self.facts = crate::contract::Outcome::story_facts(&pass.response); @@ -136,6 +208,18 @@ impl StackDialog for HostedWorkspace { Some(W::KEY) } + fn confirm(&mut self, ctx: &Context) -> Option { + self.workspace.confirm(ctx, &*self.source) + } + + fn json_fields(&self) -> Option { + self.workspace.json_fields() + } + + fn set_json_field(&mut self, ctx: &Context, field: &str, value: serde_json::Value) -> Result<(), String> { + self.workspace.set_json_field(ctx, &*self.source, field, value) + } + #[cfg(feature = "testing")] fn story_facts(&self) -> crate::testing::StoryOutput { self.facts.clone() diff --git a/crates/ui-canvas/src/canvas/full_window/stories.rs b/crates/ui-canvas/src/canvas/full_window/stories.rs index 57e002b2d..23247bca7 100644 --- a/crates/ui-canvas/src/canvas/full_window/stories.rs +++ b/crates/ui-canvas/src/canvas/full_window/stories.rs @@ -2,7 +2,7 @@ use std::sync::Arc; -use super::{FullWindowDialog, FullWindowWorkspace, HostedWorkspace, WorkspacePass}; +use super::{FullWindowDialog, FullWindowWorkspace, HostedWorkspace, WorkspaceCx, WorkspacePass}; use crate::canvas::{PixelRect, RasterSource}; use crate::contract::{Bind, Show as _, ShowContainer as _}; use crate::dialog::stories::hosted; @@ -92,7 +92,8 @@ impl FullWindowWorkspace for BrushWorkspace { const KEY: &'static str = "story.brushWorkspace"; - fn show(&mut self, ui: &mut Ui, source: &Self::Source, open: Bind<'_, bool>) -> WorkspacePass { + fn show(&mut self, ui: &mut Ui, cx: WorkspaceCx<'_, Self::Source>) -> WorkspacePass { + let WorkspaceCx { source, open, .. } = cx; // P3(dialogs-w11): dl.K57 let common = Env::of(ui).words::(); let before = self.brush; let (view, brush) = (&mut self.view, &mut self.brush); diff --git a/crates/ui-canvas/src/canvas/mod.rs b/crates/ui-canvas/src/canvas/mod.rs index c5d9a2fb2..b82384915 100644 --- a/crates/ui-canvas/src/canvas/mod.rs +++ b/crates/ui-canvas/src/canvas/mod.rs @@ -26,10 +26,10 @@ mod tool_groups; mod tool_host; pub use crate::canvas_data::{Guide, GuideColor, GuideDrag, GuideKey, GuideLine, NavigatorOptions, NavigatorSettings, ProxyColor}; -pub use crop::{CropOverlay, CropOverlayOutput, CropShield, CropStyle, ShieldColor}; +pub use crop::{CropOverlay, CropOverlayOutput, CropShield, CropStyle, ShieldColor, paint_outside}; pub use frame_step::{FRAME_STEP_MAX, frame_step}; pub(crate) use march::{MARCH_SECONDS, MARCH_TICK, march_shift}; -pub use readout::readout; +pub use readout::{ShowReadouts, hud, readout}; pub use space::{CanvasSpace, RulerText, canvas_space, pixel_aligned}; pub use words::CanvasWords; @@ -37,7 +37,7 @@ pub use words::CanvasWords; pub use tool::tool_probe; pub use tool::{CanvasTool, NoTool, ToolAccess, ToolAction, ToolAnchor, ToolClaims, ToolContext, ToolKey, ToolPointer, ViewEase}; pub use tool_groups::{PickStep, tool_pick}; -pub use tool_host::{ToolHost, ToolHostResponse, ToolInput, ToolReadout}; +pub use tool_host::{ContextRequest, StandInKey, ToolHost, ToolHostResponse, ToolInput, ToolReadout, ViewPan}; mod raster_source; pub use raster_source::{PixelRect, RasterSource}; @@ -59,7 +59,7 @@ mod snap; pub use opacity_keys::OpacityDigit; pub(crate) use rulers::LABEL_STEP_MIN; pub use rulers::{NUDGE, NUDGE_FAR}; -pub use snap::{Snap, canvas_snap, snap_suspended, snap_tolerance}; +pub use snap::{GestureSnap, Snap, canvas_snap, snap_suspended, snap_tolerance}; pub(crate) use space::context_menu; pub use space::{BackgroundPress, BodyKeys, CanvasRulers, context_click}; // End of l4d-space. @@ -181,6 +181,9 @@ pub struct Canvas<'a> { /// ([`ToolContext::snap`]). Without it nothing snaps. #[prop] snap: Option, + /// The pasteboard colour, set once here; the pasteboard and the crop shield read it from the space. + #[prop] + pasteboard: PasteboardColor, /// The view of this pass, after the canvas folded in its input. settled: Option, /// The Menu key or Shift+F10 reached the focused canvas this pass. @@ -218,6 +221,7 @@ impl<'a> Canvas<'a> { navigation: NavigationOptions::default(), show_rulers: false, keys_to_body: false, + pasteboard: PasteboardColor::Default, rulers: None, snap: None, settled: None, @@ -428,7 +432,15 @@ 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_background(background).with_canvas(id)) + Some( + space + .with_keys(keys) + .with_document(self.document_size()) + .with_rulers(self.rulers) + .with_pasteboard(self.pasteboard) + .with_background(background) + .with_canvas(id), + ) } /// The press on the background part as the canvas reports it, and the pan of a middle-button drag: a middle press diff --git a/crates/ui-canvas/src/canvas/momentary.rs b/crates/ui-canvas/src/canvas/momentary.rs index 6d807242c..130603891 100644 --- a/crates/ui-canvas/src/canvas/momentary.rs +++ b/crates/ui-canvas/src/canvas/momentary.rs @@ -73,12 +73,21 @@ pub struct Momentary { latched: Option, hand: HandTool, zoom: ZoomTool, + /// The selected tool is the Hand: Cmd and Alt at a press then give Zoom In and Zoom Out. + #[allow(dead_code)] // P3(canvas-widgets-w2): cw.C15 + hand_selected: bool, } impl Momentary { /// The momentary tools under `options`. The Zoom tool reads the document's size from the canvas's space. pub fn new(options: NavigationOptions) -> Self { - Momentary { held: None, latched: None, hand: HandTool::new(options), zoom: ZoomTool::new(options) } + Momentary { held: None, latched: None, hand: HandTool::new(options).lent(), zoom: ZoomTool::new(options), hand_selected: false } + } + + /// Tells the set whether the selected tool is the Hand: with the Hand selected and no Space held, Cmd and Alt at a + /// press give Zoom In and Zoom Out with the same latch. + pub fn hand_selected(&mut self, selected: bool) { + self.hand_selected = selected; } /// Follows a change of the navigation options. diff --git a/crates/ui-canvas/src/canvas/navigate/bar.rs b/crates/ui-canvas/src/canvas/navigate/bar.rs index 6532cd0a8..91af5e57c 100644 --- a/crates/ui-canvas/src/canvas/navigate/bar.rs +++ b/crates/ui-canvas/src/canvas/navigate/bar.rs @@ -23,6 +23,8 @@ pub struct NavigateBarOutput { pub response: Response, /// The view changes of this pass from the Zoom and Angle fields, for a binding that does not write through. pub view: EditEvents, + /// The zoom field's refused entry of this pass, for the app's alert; `None` when the field took its input. + pub invalid_zoom: Option, } impl Outcome for NavigateBarOutput { @@ -127,7 +129,7 @@ impl<'a> NavigateBar<'a> { view_buttons(ui, &words); }), }; - NavigateBarOutput { response: shown.output, view: events } + NavigateBarOutput { response: shown.output, view: events, invalid_zoom: None } // P3(canvas-widgets-w11): cw.C60 } } diff --git a/crates/ui-canvas/src/canvas/navigate/wheel.rs b/crates/ui-canvas/src/canvas/navigate/wheel.rs index 659fcd9a9..6f7b272a2 100644 --- a/crates/ui-canvas/src/canvas/navigate/wheel.rs +++ b/crates/ui-canvas/src/canvas/navigate/wheel.rs @@ -38,6 +38,12 @@ pub struct WheelInput { pub notch: f32, /// The OS, which decides where the Control key is among the modifiers. pub os: Platform, + /// The pinch factor of a two-finger touch; 1 for none. + pub touch_zoom: f32, + /// The trackpad's rotation, in radians. + pub rotation: f32, + /// The twist of a two-finger touch, in radians. + pub touch_rotation: f32, } impl WheelInput { @@ -46,7 +52,16 @@ impl WheelInput { /// line. pub fn of(wheel: &Wheel, line: f32, os: Platform) -> Self { let notch = if wheel.unit == WheelUnit::Line { line } else { WheelNotch::DEFAULT.points(0.0) }; - WheelInput { scroll: wheel.scroll, zoom: wheel.zoom, mods: wheel.mods, notch, os } + WheelInput { + scroll: wheel.scroll, + zoom: wheel.zoom, + mods: wheel.mods, + notch, + os, + touch_zoom: wheel.touch_zoom, + rotation: wheel.rotation, + touch_rotation: wheel.touch_rotation, + } } /// The scroll along the wheel's axis whichever one the device reported it on (some systems send a modified wheel @@ -87,6 +102,13 @@ impl WheelNavigation { self.classify(WheelInput::of(wheel, line, os), options) } + /// The degrees `input` adds to the view's rotation: the trackpad's with `trackpad_rotate`, the fingers' twist with + /// `touch_gestures`; `None` for none. + pub fn rotation(input: &WheelInput, options: &NavigationOptions) -> Option { + let _ = (input, options); + todo!("cw.C30") + } + /// Whether `mods` make the Alt zoom gesture on `os`: Alt, with the Control key allowed, which is `ctrl` on macOS /// (⌘ keeps the wheel out of it) and `cmd` elsewhere, where Shift with it keeps the wheel a scroll. fn alt_gesture(mods: Mods, os: Platform) -> bool { diff --git a/crates/ui-canvas/src/canvas/navigator/zoom_row.rs b/crates/ui-canvas/src/canvas/navigator/zoom_row.rs index a64e66a84..cdf34d349 100644 --- a/crates/ui-canvas/src/canvas/navigator/zoom_row.rs +++ b/crates/ui-canvas/src/canvas/navigator/zoom_row.rs @@ -21,6 +21,8 @@ pub struct NavigatorZoomRowOutput { /// The view changes of this pass, for a binding that does not write through: a typed percent or a slider drag as /// its gesture. pub view: EditEvents, + /// The zoom field's refused entry of this pass, for the app's alert; `None` when the field took its input. + pub invalid_zoom: Option, } impl Outcome for NavigatorZoomRowOutput { @@ -93,6 +95,6 @@ impl<'a> NavigatorZoomRow<'a> { } events = edits.into_iter().collect(); }); - NavigatorZoomRowOutput { response: shown.output, view: events } + NavigatorZoomRowOutput { response: shown.output, view: events, invalid_zoom: None } // P3(canvas-widgets-w11): cw.C60 } } diff --git a/crates/ui-canvas/src/canvas/navigator_panel.rs b/crates/ui-canvas/src/canvas/navigator_panel.rs index be1a820b7..5254dbec5 100644 --- a/crates/ui-canvas/src/canvas/navigator_panel.rs +++ b/crates/ui-canvas/src/canvas/navigator_panel.rs @@ -20,6 +20,8 @@ pub struct NavigatorPanelOutput { /// The view changes of this pass, from the preview box or the zoom row's field and slider, in order. A preview /// zoom under Animated Zoom is the change to its target; the canvas eases to it. pub view: EditEvents, + /// The zoom field's refused entry of this pass, for the app's alert; `None` when the field took its input. + pub invalid_zoom: Option, } impl Outcome for NavigatorPanelOutput { @@ -84,6 +86,6 @@ impl<'a> NavigatorPanel<'a> { let row = NavigatorZoomRow::new(view.reborrowed(), document).show(ui); change = preview.view.events.clone().into_iter().chain(row.view).collect(); }); - NavigatorPanelOutput { response: shown.output, view: change } + NavigatorPanelOutput { response: shown.output, view: change, invalid_zoom: None } // P3(canvas-widgets-w11): cw.C60 } } diff --git a/crates/ui-canvas/src/canvas/pasteboard/mod.rs b/crates/ui-canvas/src/canvas/pasteboard/mod.rs index 5a88185d9..f9f1849e3 100644 --- a/crates/ui-canvas/src/canvas/pasteboard/mod.rs +++ b/crates/ui-canvas/src/canvas/pasteboard/mod.rs @@ -170,6 +170,9 @@ pub struct Pasteboard<'a> { /// The border round each page; a drop shadow by default. #[prop] border: PageBorder, + /// Document rects the pasteboard does not cover, subtracted like the pages. + #[prop] + uncovered: &'a [DocRect], /// The size of each page's name, measured in `parts`; zero for a page without one. name_sizes: Vec, name_clicked: Option, @@ -184,6 +187,7 @@ impl<'a> Pasteboard<'a> { pages, color: PasteboardColor::Default, border: PageBorder::DropShadow, + uncovered: &[], name_sizes: Vec::new(), name_clicked: None, context_at: None, @@ -193,7 +197,8 @@ impl<'a> Pasteboard<'a> { /// The pasteboard as screen quads: the canvas minus the pages, each piece as its four corners (a turned view needs /// quads, not rects). For an app that draws the pasteboard itself. - pub fn quads(view: &CanvasView, pages: &[PageFrame]) -> Vec<[Pos2; 4]> { + pub fn quads(view: &CanvasView, pages: &[PageFrame], uncovered: &[DocRect]) -> Vec<[Pos2; 4]> { + let _ = uncovered; // P3(canvas-widgets-w9): cw.C48 let canvas = view.visible(); if !(canvas.x1 > canvas.x0 && canvas.y1 > canvas.y0 && canvas.area().is_finite()) { return Vec::new(); @@ -333,7 +338,7 @@ impl Component for Pasteboard<'_> { let (view, style) = (space.view, cx.style); let draw = ui.draw(); let polygon = |quad: &[Pos2; 4]| PaintShape::Polygon(quad.to_vec()); - for quad in Self::quads(&view, self.pages).iter().filter(|quad| bounds(quad).intersects(view.rect)) { + for quad in Self::quads(&view, self.pages, self.uncovered).iter().filter(|quad| bounds(quad).intersects(view.rect)) { match self.color.fill() { Some(color) => draw.data_fill(&polygon(quad), color), None => draw.fill(&polygon(quad), style.fill), diff --git a/crates/ui-canvas/src/canvas/raster/mod.rs b/crates/ui-canvas/src/canvas/raster/mod.rs index a85c3fe32..4337bad8b 100644 --- a/crates/ui-canvas/src/canvas/raster/mod.rs +++ b/crates/ui-canvas/src/canvas/raster/mod.rs @@ -261,6 +261,9 @@ 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. + #[prop(flag, name = "picture")] + under_controls: bool, read: PixelRect, shown: Option, mapping: Option, @@ -324,6 +327,7 @@ impl<'a> RasterDisplay<'a> { checkerboard: None, outlined: false, extent: Extent::Document, + under_controls: false, read: PixelRect::default(), shown: None, mapping: None, diff --git a/crates/ui-canvas/src/canvas/readout.rs b/crates/ui-canvas/src/canvas/readout.rs index 8e472103e..67b530965 100644 --- a/crates/ui-canvas/src/canvas/readout.rs +++ b/crates/ui-canvas/src/canvas/readout.rs @@ -2,13 +2,24 @@ use crate::contract::ghost; use crate::primitives::{Draw, DrawEnv, PaintRecord, Span, TextRun}; -use crate::runtime::env::{Env, Label}; +use crate::runtime::env::{Env, EnvValue, Label}; use crate::runtime::memory::StageAccess; use crate::style::{Corners, Ink, SurfaceKind}; use craft_i18n::Direction; use egui::{Context, Pos2, Rect, Vec2, vec2}; use std::cell::RefCell; +/// The one Show Transformation Values gate: while it holds `false` in the root env, [`readout`] and the tool host's +/// paint of a tool's readout rows paint nothing. [`hud`] is never gated. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ShowReadouts(pub bool); + +impl EnvValue for ShowReadouts { + fn root() -> Self { + ShowReadouts(true) + } +} + /// Paints rows of a label and a value beside the pointer at `at`, on the ghost layer above every popup, for this /// pass only: a gesture calls it each pass it runs. The readout takes no input. It sits toward the lower end side /// of the pointer (the lower right, mirrored under right-to-left), flips to the other side where the window has no @@ -19,6 +30,11 @@ pub fn readout(cx: &impl StageAccess, at: Pos2, rows: &[(Label, String)]) { paint_readout(cx.stage().ctx(), at, rows); } +/// [`readout`] that the Show Transformation Values gate ([`ShowReadouts`]) never silences: brush size readouts. +pub fn hud(cx: &impl StageAccess, at: Pos2, rows: &[(Label, String)]) { + paint_readout(cx.stage().ctx(), at, rows); +} + /// [`readout`] for a caller that has the context, such as the tool host. pub(super) fn paint_readout(ctx: &Context, at: Pos2, rows: &[(Label, String)]) { if rows.is_empty() { diff --git a/crates/ui-canvas/src/canvas/snap.rs b/crates/ui-canvas/src/canvas/snap.rs index 58b8cacba..2c170e537 100644 --- a/crates/ui-canvas/src/canvas/snap.rs +++ b/crates/ui-canvas/src/canvas/snap.rs @@ -1,36 +1,78 @@ //! `Snap`: a canvas's snapping of a coordinate the pointer sets. use crate::runtime::env::{AppValues, EnvValue, EnvView}; -use craft_behavior::geometry::SNAP_PX; +use craft_behavior::geometry::{SNAP_PX, SnapLine, SnapOptions, SnapTargets}; +use craft_behavior::kurbo::{Point, Vec2}; use craft_behavior::{Axis, CanvasView}; use craft_keymap::{Mods, Platform}; use std::sync::Arc; -/// A canvas's snapping of a coordinate the pointer sets (View > Snap To): the axis a guide at the coordinate would -/// run along (an x coordinate is across `Axis::Y`), the document coordinate under the pointer and the modifiers held, -/// to the coordinate to use. The app gives it to the canvas once ([`Canvas::snap`](super::Canvas::snap)); the canvas -/// publishes it to its body, where the rulers snap the zero point and the guides snap a guide -/// ([`canvas_snap`]), and hands it to the tool host through [`CanvasOutput`](super::CanvasOutput), which gives it to -/// the tool ([`ToolContext::snap`](super::ToolContext::snap)). Clones share one function; two snaps are equal when -/// they are clones of each other. +/// A canvas's snapping of a coordinate the pointer sets (View > Snap To), as data over the document's [`SnapTargets`]: +/// the axis a guide at the coordinate would run along (an x coordinate is across `Axis::Y`), the document coordinate +/// under the pointer and the modifiers held, to the coordinate to use. The app gives it to the canvas once +/// ([`Canvas::snap`](super::Canvas::snap)); the canvas publishes it to its body, where the rulers snap the zero point +/// and the guides snap a guide ([`canvas_snap`]), and hands it to the tool host through +/// [`CanvasOutput`](super::CanvasOutput), which gives it to the tool ([`ToolContext::snap`](super::ToolContext::snap)). +/// Two snaps are equal when they share their targets and have equal options, tolerance and OS. #[derive(Clone)] -pub struct Snap(Arc f64 + Send + Sync>); +pub struct Snap { + targets: Arc, + options: SnapOptions, + tolerance: Option, + os: Platform, +} + +/// The gesture's snap options in one argument: whether the gesture reads Control itself. +// P3(canvas-widgets-w3): cw.C16 `kinds: SnapKinds` is defined by no item (plan error, open). +#[derive(Clone, Copy, Debug, Default)] +pub struct GestureSnap { + /// Whether the gesture reads the Control key itself, so Control does not suspend snapping. + pub reads_control: bool, +} impl Snap { - /// The snapping that runs `snap`. - pub fn new(snap: impl Fn(Axis, f64, Mods) -> f64 + Send + Sync + 'static) -> Self { - Snap(Arc::new(snap)) + /// The snapping over `targets` with `options`; the tolerance is set by the canvas each pass. + pub fn new(targets: Arc, options: SnapOptions) -> Self { + Snap { targets, options, tolerance: None, os: Platform::current() } } /// `position` across a guide running `along`, snapped. pub fn apply(&self, along: Axis, position: f64, mods: Mods) -> f64 { - (self.0)(along, position, mods) + let Some(tolerance) = self.tolerance.filter(|_| self.options.on && !snap_suspended(mods, self.os, false)) else { + return position; + }; + self.targets.nearest(along, position, tolerance).map_or(position, |target| target.position) + } + + /// `point` snapped on both axes, with the lines to draw; the input and no lines when snapping is off. + pub fn point(&self, point: Point, mods: Mods, gesture: GestureSnap) -> (Point, Vec) { + let _ = (point, mods, gesture); + todo!("cw.C16") + } + + /// The offset that moves `rect` onto a snap target, with the lines to draw; zero when snapping is off. + pub fn rect(&self, rect: craft_behavior::kurbo::Rect, mods: Mods) -> (Vec2, Vec) { + let _ = (rect, mods); + todo!("cw.C16") + } + + /// The View > Snap To options this snap was built with. + pub fn options(&self) -> SnapOptions { + self.options + } + + /// This snap with its tolerance for `view` and the OS set. + #[allow(dead_code)] // P3(canvas-widgets-w3): cw.C16 + pub(super) fn at(mut self, view: &CanvasView, os: Platform) -> Self { + self.tolerance = Some(view.doc_len(SNAP_PX as f32)); + self.os = os; + self } } impl PartialEq for Snap { fn eq(&self, other: &Self) -> bool { - Arc::ptr_eq(&self.0, &other.0) + Arc::ptr_eq(&self.targets, &other.targets) && self.options == other.options && self.tolerance == other.tolerance && self.os == other.os } } diff --git a/crates/ui-canvas/src/canvas/space.rs b/crates/ui-canvas/src/canvas/space.rs index de025b70d..6a00bc5b1 100644 --- a/crates/ui-canvas/src/canvas/space.rs +++ b/crates/ui-canvas/src/canvas/space.rs @@ -5,6 +5,7 @@ //! control reads it with [`canvas_space`]; the canvas's tool reads it with `ToolContext::space`, handed over by //! `CanvasOutput::space`. +use super::PasteboardColor; use crate::contract::{Component, Cx, Focus as _, Pointer as _}; use crate::runtime::env::{AppValues, EnvValue, EnvView, UnitKind, Units}; use craft_behavior::canvas::zoom; @@ -33,6 +34,7 @@ pub struct CanvasSpace { background: BackgroundPress, /// The canvas's id, under which its controls claim keys on the focused canvas. canvas: Option, + pasteboard: PasteboardColor, } impl CanvasSpace { @@ -50,6 +52,7 @@ impl CanvasSpace { rulers: None, background: BackgroundPress::default(), canvas: None, + pasteboard: PasteboardColor::Default, } } @@ -110,6 +113,25 @@ impl CanvasSpace { self } + /// This space with the pasteboard colour the canvas was given. + #[must_use] + pub fn with_pasteboard(mut self, color: PasteboardColor) -> Self { + self.pasteboard = color; + self + } + + /// The pasteboard colour set once on the canvas: the pasteboard and the crop shield read it from the space. + pub fn pasteboard(&self) -> PasteboardColor { + self.pasteboard + } + + /// Appends `shapes` to the canvas's picture slot, so they paint under every canvas control of the body, in show + /// order with the displays that use [`RasterDisplay::picture`](super::RasterDisplay::picture). + pub fn paint_picture(&self, shapes: Vec) { + let _ = shapes; + todo!("cw.C70") + } + /// This space published by the canvas `id`. #[must_use] pub(crate) fn with_canvas(mut self, id: egui::Id) -> Self { diff --git a/crates/ui-canvas/src/canvas/tool.rs b/crates/ui-canvas/src/canvas/tool.rs index 47d310a9a..58355feb7 100644 --- a/crates/ui-canvas/src/canvas/tool.rs +++ b/crates/ui-canvas/src/canvas/tool.rs @@ -10,7 +10,8 @@ use crate::primitives::{ContentPainterCx, Draw}; use crate::runtime::env::{Direction, Env, Label, MotionPolicy, PointSize, UnitWords, Units, WordSet, Words}; use crate::runtime::motion::loop_phase; use crate::style::StyleCx; -use craft_behavior::kurbo::Point; +use craft_behavior::geometry::SnapLine; +use craft_behavior::kurbo::{self, Point}; use craft_behavior::{Axis, CancelReason, CanvasView, Cursor, CursorIcon, GestureId, PointerButton, PointerSample}; use craft_i18n::{Digits, Format, Region}; use craft_keymap::{Chord, Key, Mods, Platform}; @@ -215,6 +216,8 @@ pub(crate) struct ToolRequests { pub(crate) repaint: bool, pub(crate) view: Option, pub(crate) ease: Option, + pub(crate) snapped: Vec, + pub(crate) autoscroll_at: Option, } /// What a tool sees and may ask for during a call. @@ -234,6 +237,7 @@ pub struct ToolContext<'a> { /// Whether Caps Lock is on now (a brush shows its precise cursor): the platform's toggle state, read once per /// pass, not a count of key presses. pub caps_lock: bool, + precise_cursors: bool, space: Option, gesture: Option, down: &'a [Key], @@ -266,6 +270,7 @@ impl<'a> ToolContext<'a> { gesture: None, down: &[], caps_lock: false, + precise_cursors: false, painter: None, style: None, env: None, @@ -317,6 +322,18 @@ impl<'a> ToolContext<'a> { self } + /// Whether Preferences > Cursors > Other Cursors is Precise. + #[must_use] + pub fn precise_cursors(mut self, on: bool) -> Self { + self.precise_cursors = on; + self + } + + /// Whether the tool shows its precise cursor now: `precise_cursors` differs from Caps Lock. + pub fn precise(&self) -> bool { + self.precise_cursors != self.caps_lock + } + /// The press arena's slop. #[must_use] pub fn slop(mut self, slop: f32) -> Self { @@ -403,6 +420,30 @@ impl<'a> ToolContext<'a> { } } + /// 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") + } + + /// Adds the snap lines a canvas control the tool shows snapped this pass, handed to the host in the same pass. + pub fn add_snapped(&mut self, lines: impl IntoIterator) { + self.requests.snapped.extend(lines); + } + + /// 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") + } + + /// A canvas control the tool shows asks the app to scroll: the host reports `past_edge` for `pointer` through the + /// tool's drag rule. + pub fn autoscroll_at(&mut self, pointer: Pos2) { + self.requests.autoscroll_at = Some(pointer); + } + /// The OS the pass runs on: the env's; the build's for a context built without an env. fn os(&self) -> Platform { self.env.map_or_else(Platform::current, |env| env.os) @@ -479,6 +520,13 @@ impl<'a> ToolContext<'a> { self.requests.readout = Some(rows); } + /// 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. + pub fn hud(&mut self, rows: Vec<(Label, String)>) { + let _ = rows; + todo!("cw.C2") + } + /// Asks for another pass (an animation, a held key that repeats). pub fn request_repaint(&mut self) { self.requests.repaint = true; @@ -513,11 +561,20 @@ pub struct ToolClaims { /// Decrement on the tool's node and turns them into [`ToolKey::Nudge`], so a tool that claims the nudges /// describes what they move in [`CanvasTool::access`]. The arrows reach [`CanvasTool::key`] either way. pub nudges: bool, + /// Single chords the tool takes while the rest of the keyboard stays the app's, delivered as [`ToolKey::Kept`]. + pub keys: &'static [Chord], } impl ToolClaims { /// No keys: every key stays the app's. - pub const NONE: ToolClaims = ToolClaims { keyboard: false, deletes: false, nudges: false }; + pub const NONE: ToolClaims = ToolClaims { keyboard: false, deletes: false, nudges: false, keys: &[] }; + + /// The same claims with the single chords `keys`. + #[must_use] + pub const fn keys(mut self, keys: &'static [Chord]) -> Self { + self.keys = keys; + self + } /// The same claims with the canvas's plain keys. #[must_use] @@ -611,6 +668,18 @@ pub trait CanvasTool { false } + /// Whether the tool changes only the view: its primary gestures pass under a modal that keeps the canvas. + /// Default: `false`. + fn view_only(&self) -> bool { + false + } + + /// Whether the host calls `drag` once per pointer move of a pass (the freehand family) instead of once at the + /// latest position. Default: `false`. + fn takes_every_move(&self) -> bool { + false + } + /// What the tool is to assistive technology this pass: its drawing as one object with its anchors (a rectangle /// being dragged: `Rectangle 120 x 80 px`), or `None` for a tool with nothing to describe. The host emits it /// after [`paint`](Self::paint), with the same context. Default: `None`. diff --git a/crates/ui-canvas/src/canvas/tool_host.rs b/crates/ui-canvas/src/canvas/tool_host.rs index fd4935c46..0cd06f616 100644 --- a/crates/ui-canvas/src/canvas/tool_host.rs +++ b/crates/ui-canvas/src/canvas/tool_host.rs @@ -55,7 +55,7 @@ //! ``` use super::frame_step; -use super::momentary::{Momentary, MomentaryCommands}; +use super::momentary::{Momentary, MomentaryCommands, MomentaryTool}; use super::navigate::Autoscroll; use super::readout::paint_readout; use super::tool::{CanvasTool, March, ToolAccess, ToolAction, ToolClaims, ToolContext, ToolKey, ToolPointer, ToolRequests}; @@ -70,7 +70,8 @@ use crate::runtime::env::{Env, Label}; use crate::runtime::memory::{global, with_session}; use crate::runtime::pointer::{self, PointerFrame}; use crate::runtime::{cursor, frame, keys, lock_keys, measure}; -use crate::style::StyleCx; +use crate::style::{DataColor, StyleCx}; +use craft_behavior::geometry::SnapLine; use craft_behavior::kurbo; use craft_behavior::{ AccessAction, AccessRequest, CancelReason, CanvasView, Cursor, CursorPriority, GestureId, GesturePhase, Intent, PartKey, PartRef, PointerButton, @@ -193,6 +194,52 @@ pub struct ToolHostResponse { /// off), else the canvas's own ([`CanvasOutput::view`]): the one view the app copies into its own. A view that /// eases is its target; the canvas shows the way there. pub view: Option, + /// The snap lines of this pass from `snap_rect` and `add_snapped`. + pub snapped: Vec, + /// Where the app opens its canvas menu: a secondary press on the background the running tool did not take, or the + /// Menu key or Shift+F10. + pub context: Option, + /// The document distance the view centre moved this pass from a `pan_view`, after the Overscroll clamp. + pub pan: Option, +} + +/// Where and how the app opens its canvas menu, from [`ToolHostResponse::context`]. +#[derive(Clone, Copy, Debug, PartialEq)] +#[non_exhaustive] +pub struct ContextRequest { + /// The pointer on screen, or the view centre for a key. + pub at: Pos2, + /// The modifiers held when the secondary button went down, or those held at the key. + pub mods: Mods, + /// The momentary tool in effect at the press (a Space-held Hand). + pub momentary: Option, +} + +/// A pan of the view, from [`ToolHostResponse::pan`]. +#[derive(Clone, Copy, Debug, PartialEq)] +#[non_exhaustive] +pub struct ViewPan { + /// The document distance the view centre moved. + pub delta: kurbo::Vec2, + /// The press's scroll-all-windows choice. + pub scroll_all: bool, +} + +impl ViewPan { + /// A pan of `delta` document units with the press's `scroll_all` choice. + pub const fn new(delta: kurbo::Vec2, scroll_all: bool) -> Self { + ViewPan { delta, scroll_all } + } +} + +/// A key whose hold at a press makes the host run a stand-in tool, from [`ToolHost::stand_in`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum StandInKey { + /// The platform command key. + Command, + /// The Alt key. + Alt, } #[derive(Clone, Copy, Debug)] @@ -234,6 +281,14 @@ fn state_id(canvas: Id) -> Id { 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, + #[allow(dead_code)] // P3(canvas-widgets-w2): cw.C4 + precise_cursors: bool, } impl<'m> ToolHost<'m> { @@ -261,10 +316,35 @@ impl<'m> ToolHost<'m> { self } + /// The tool a press runs when `key` is held at the press and the selected tool does not take it, latched for the + /// gesture. Order: `Momentary` first, then Command, then Alt. + #[must_use] + pub fn stand_in(mut self, key: StandInKey, tool: &'m mut (dyn CanvasTool + 'm)) -> Self { + match key { + StandInKey::Command => self.command_stand_in = Some(tool), + StandInKey::Alt => self.alt_stand_in = Some(tool), + } + self + } + + /// The user's Smart Guide colour; `None` is the guides' own `data.magenta`. + #[must_use] + pub fn smart_guide_color(mut self, color: Option) -> Self { + self.smart_guide_color = color; + self + } + + /// Preferences > Cursors > Other Cursors (Precise); reaches [`ToolContext::precise`]. + #[must_use] + pub fn precise_cursors(mut self, on: bool) -> Self { + self.precise_cursors = on; + self + } + /// 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; + let ToolHost { disabled, momentary, .. } = self; // P3(canvas-widgets-w2): cw.C1, cw.C3, cw.C4 let ctx = ui.ctx().clone(); let env = Env::of(ui); let key = state_id(canvas.response.id); diff --git a/crates/ui-canvas/src/canvas/tools.rs b/crates/ui-canvas/src/canvas/tools.rs index 2f02c3010..b8797bbf1 100644 --- a/crates/ui-canvas/src/canvas/tools.rs +++ b/crates/ui-canvas/src/canvas/tools.rs @@ -11,6 +11,7 @@ use super::rotate::ViewTurn; use super::zoom_motion::{HoldZoom, ZoomDrag}; use super::{CanvasTool, ToolAction, ToolContext, ToolKey, ToolPath, ToolPointer}; use crate::primitives::Draw; +use craft_behavior::PointerButton; use craft_behavior::canvas::zoom; use craft_behavior::geometry::crop::normalized_angle; use craft_behavior::kurbo::{Rect, Size, Vec2}; @@ -239,12 +240,24 @@ pub struct HandTool { /// The pointer at the previous drag pass: a drag step is the flick's input. last: Pos2, flick: FlickPan, + /// Lent by the momentary set: a secondary press pans too. + lent: bool, + /// The press's scroll-all-windows choice, reported with the pan. + #[allow(dead_code)] // P3(canvas-widgets-w2): cw.C14 + scroll_all: bool, } impl HandTool { /// A Hand tool under `options`. pub fn new(options: NavigationOptions) -> Self { - Self { options, start: None, last: Pos2::ZERO, flick: FlickPan::default() } + Self { options, start: None, last: Pos2::ZERO, flick: FlickPan::default(), lent: false, scroll_all: false } + } + + /// This tool as the momentary set lends it: a secondary press pans as well. + #[must_use] + pub(super) fn lent(mut self) -> Self { + self.lent = true; + self } /// Ends a glide: the app's clamp of the view the tool set (Overscroll off) moved it, so the view hit a scroll @@ -268,6 +281,14 @@ impl HandTool { } impl CanvasTool for HandTool { + fn view_only(&self) -> bool { + true + } + + fn takes(&self, button: PointerButton, _mods: Mods) -> bool { + button == PointerButton::Primary || (self.lent && button == PointerButton::Secondary) + } + fn each_pass(&mut self, cx: &mut ToolContext<'_>) { if self.start.is_some() || !self.flick.gliding() { return; @@ -418,6 +439,10 @@ fn click_step(view: &CanvasView, screen: Pos2, out: bool, size: Size, options: & } impl CanvasTool for ZoomTool { + fn view_only(&self) -> bool { + true + } + fn each_pass(&mut self, cx: &mut ToolContext<'_>) { // The hold advances without pointer movement, so a press held perfectly still keeps zooming. if self.press.is_some() { @@ -517,6 +542,10 @@ pub struct RotateViewTool { } impl CanvasTool for RotateViewTool { + fn view_only(&self) -> bool { + true + } + fn press(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) -> ToolAction { self.drag = cx.space().map(|space| (ViewTurn::begin(&space.view, pointer.pos), space.view)); ToolAction::Claimed diff --git a/crates/ui-canvas/src/canvas_controls/brush/mod.rs b/crates/ui-canvas/src/canvas_controls/brush/mod.rs index 8b639700d..5b8775f4e 100644 --- a/crates/ui-canvas/src/canvas_controls/brush/mod.rs +++ b/crates/ui-canvas/src/canvas_controls/brush/mod.rs @@ -22,11 +22,15 @@ mod cursor; mod falloff; mod resize; +mod source_marker; #[cfg(feature = "testing")] mod stories; mod tip; +mod trail; pub use cursor::{BrushCursor, BrushCursorOptions, PaintingCursor, TipCell, TipCellStyle}; pub use falloff::{FalloffPreview, FalloffPreviewStyle, TipFalloff}; pub use resize::{BrushDimensions, BrushLevel, BrushResize, BrushResizeOptions, RESIZE_TRAVEL, ResizeStep}; +pub use source_marker::SourceMarker; pub use tip::{BrushTip, BrushTipOutline, TipPose, TipRings}; +pub use trail::{CoverageMask, StrokeTrail, TrailTone}; diff --git a/crates/ui-canvas/src/canvas_controls/brush/source_marker.rs b/crates/ui-canvas/src/canvas_controls/brush/source_marker.rs new file mode 100644 index 000000000..ae1ddd3fa --- /dev/null +++ b/crates/ui-canvas/src/canvas_controls/brush/source_marker.rs @@ -0,0 +1,92 @@ +//! `SourceMarker`: the clone source's crosshair. + +use crate::canvas::canvas_space; +use crate::contract::{Access, Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role}; +use crate::primitives::{PaintShape, StrokeWidth}; +use crate::runtime::env::Label; +use crate::style::{ComponentStyle, StyleColor, StyleCx}; +use craft_behavior::kurbo::Point; +use craft_behavior::{Input, Metrics}; +use egui::{Pos2, Response, Vec2}; + +/// The style of the source marker: the arms in a thin colour over a halo. +#[derive(Clone, Debug, PartialEq, ComponentStyle)] +#[non_exhaustive] +pub struct SourceMarkerStyle { + #[style(metrics)] + metrics: Metrics, + /// The arms. + line: StyleColor, + /// The halo under the arms, so they read on any image. + halo: StyleColor, + /// The length of one arm from the crosshair's centre. + arm: f32, +} + +/// The clone source's crosshair at document point `at`: two arms through the view, a thin line over a thick halo. +/// Display only. +#[derive(crate::contract::Component)] +#[component(canvas_control, content_painter)] +pub struct SourceMarker { + #[common] + common: Common, + at: Point, +} + +impl SourceMarker { + /// A marker named `label` at the document point `at`. + pub fn new(label: impl Into