Contract stubs: craft-ui-canvas, craft-ui-shell (plus stage-4 carry)

This commit is contained in:
aiongg
2026-11-14 01:59:24 +00:00
parent 3c509c6227
commit 38ce55467c
55 changed files with 1250 additions and 91 deletions
Generated
+1
View File
@@ -3050,6 +3050,7 @@ dependencies = [
"craft-ui-test-kit",
"egui",
"serde",
"serde_json",
]
[[package]]
+8
View File
@@ -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<Vec<Point>> {
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];
+1 -1
View File
@@ -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};
+16 -4
View File
@@ -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<PointerSample>,
},
/// A button went down.
#[non_exhaustive]
Pressed {
@@ -522,7 +534,7 @@ impl<T: Copy> PressMachine<T> {
}
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");
}
+1
View File
@@ -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"] }
+4 -2
View File
@@ -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())
}
+12 -1
View File
@@ -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<f64>,
/// 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<Pos2>,
/// 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
}
}
}
+28 -1
View File
@@ -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<Point> = 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
+12 -2
View File
@@ -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 {
@@ -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<Self::Event, Self::Result>;
fn show(&mut self, ui: &mut Ui, cx: WorkspaceCx<'_, Self::Source>) -> WorkspacePass<Self::Event, Self::Result>;
/// The workspace's fields as JSON for the automation surface; `None` when it has none.
fn json_fields(&self) -> Option<serde_json::Value> {
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<Self::Result> {
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<W: FullWindowWorkspace> {
source: Arc<W::Source>,
events: Vec<W::Event>,
open: bool,
revision: u64,
hold_ok: bool,
ok_waits: bool,
#[cfg(feature = "testing")]
facts: crate::testing::StoryOutput,
}
@@ -89,6 +131,9 @@ impl<W: FullWindowWorkspace> HostedWorkspace<W> {
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<W: FullWindowWorkspace> HostedWorkspace<W> {
/// The source the next pass reads.
pub fn set_source(&mut self, source: Arc<W::Source>) {
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<W::Result> {
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<W: FullWindowWorkspace> StackDialog for HostedWorkspace<W> {
}
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<W::Result>> {
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<W: FullWindowWorkspace> StackDialog for HostedWorkspace<W> {
Some(W::KEY)
}
fn confirm(&mut self, ctx: &Context) -> Option<W::Result> {
self.workspace.confirm(ctx, &*self.source)
}
fn json_fields(&self) -> Option<serde_json::Value> {
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()
@@ -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<BrushChanged, f64> {
fn show(&mut self, ui: &mut Ui, cx: WorkspaceCx<'_, Self::Source>) -> WorkspacePass<BrushChanged, f64> {
let WorkspaceCx { source, open, .. } = cx; // P3(dialogs-w11): dl.K57
let common = Env::of(ui).words::<CommonWords>();
let before = self.brush;
let (view, brush) = (&mut self.view, &mut self.brush);
+17 -5
View File
@@ -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<Snap>,
/// 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<Settled>,
/// 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
+10 -1
View File
@@ -73,12 +73,21 @@ pub struct Momentary {
latched: Option<MomentaryTool>,
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.
+3 -1
View File
@@ -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<CanvasView>,
/// 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<crate::text::InvalidZoom>,
}
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
}
}
+23 -1
View File
@@ -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<f64> {
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 {
@@ -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<CanvasView>,
/// 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<crate::text::InvalidZoom>,
}
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
}
}
@@ -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<CanvasView>,
/// 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<crate::text::InvalidZoom>,
}
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
}
}
@@ -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<Vec2>,
name_clicked: Option<usize>,
@@ -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),
@@ -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<Shown>,
mapping: Option<Mapping>,
@@ -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,
+17 -1
View File
@@ -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() {
+56 -14
View File
@@ -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<dyn Fn(Axis, f64, Mods) -> f64 + Send + Sync>);
pub struct Snap {
targets: Arc<SnapTargets>,
options: SnapOptions,
tolerance: Option<f64>,
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<SnapTargets>, 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<SnapLine>) {
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<SnapLine>) {
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
}
}
+22
View File
@@ -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<egui::Id>,
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<egui::Shape>) {
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 {
+71 -2
View File
@@ -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<CanvasView>,
pub(crate) ease: Option<ViewEase>,
pub(crate) snapped: Vec<SnapLine>,
pub(crate) autoscroll_at: Option<Pos2>,
}
/// 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<CanvasSpace>,
gesture: Option<GestureId>,
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<Item = SnapLine>) {
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`.
+83 -3
View File
@@ -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<CanvasView>,
/// The snap lines of this pass from `snap_rect` and `add_snapped`.
pub snapped: Vec<SnapLine>,
/// 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<ContextRequest>,
/// The document distance the view centre moved this pass from a `pan_view`, after the Overscroll clamp.
pub pan: Option<ViewPan>,
}
/// 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<MomentaryTool>,
}
/// 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<DataColor>,
#[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<DataColor>) -> 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);
+30 -1
View File
@@ -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
@@ -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};
@@ -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<Label>, at: Point) -> Self {
SourceMarker { common: Common::new(), at }.label(label)
}
}
impl Component for SourceMarker {
const ROLE: Role = Role::GRAPHICS_OBJECT;
const ALT_ROLES: &'static [Role] = &[Role::None];
const INPUT: Input = Input::Display;
const PARTS: bool = false;
const STOPS: bool = false;
const OVERLAYS: bool = false;
type Style = SourceMarkerStyle;
type Output = Response;
fn style(cx: &StyleCx<'_>, _: SourceMarkerStyleKey) -> SourceMarkerStyle {
let overlay = &cx.tokens.color.overlay;
SourceMarkerStyle {
metrics: Metrics::new(),
line: cx.color(overlay.handle_fill),
halo: cx.color(overlay.halo),
arm: cx.tokens.size.icon.sm / 2.0,
}
}
fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 {
Vec2::ZERO
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
if !(self.at.x.is_finite() && self.at.y.is_finite()) {
return;
}
let Some(space) = canvas_space(&cx.env) else { return };
let centre = space.view.to_screen(self.at);
let arm = cx.style.arm;
let draw = ui.draw();
for ends in [
[Pos2::new(centre.x - arm, centre.y), Pos2::new(centre.x + arm, centre.y)],
[Pos2::new(centre.x, centre.y - arm), Pos2::new(centre.x, centre.y + arm)],
] {
let path = PaintShape::Path(ends.to_vec());
draw.stroke(&path, StrokeWidth::Thick, cx.style.halo);
draw.stroke(&path, StrokeWidth::Thin, cx.style.line);
}
}
fn access(&self, access: &mut Access, _: &Cx<'_, Self>) {
access.role(Role::None);
}
fn finish(self, cx: Cx<'_, Self>) -> Response {
cx.response.clone()
}
}
@@ -0,0 +1,144 @@
//! `StrokeTrail`: the footprint of the stroke being painted, over a coverage raster with partial uploads.
use crate::contract::{Access, Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role};
use crate::runtime::env::Label;
use crate::style::{ComponentStyle, StyleColor, StyleCx};
use craft_behavior::kurbo::{Point, Rect};
use craft_behavior::{Input, Metrics};
use egui::Response;
/// A coverage raster over a document rect: one byte per texel, `scale` document units wide, stamped by the tool as the
/// stroke grows and uploaded by [`StrokeTrail`] by its changed rows.
#[derive(Debug)]
#[allow(dead_code)] // P3(tools-w17): tl.T52
pub struct CoverageMask {
bounds: Rect,
max_side: u32,
}
impl CoverageMask {
/// A mask over `bounds` with no side longer than `max_side` texels.
pub fn new(bounds: Rect, max_side: u32) -> Self {
let _ = (bounds, max_side);
todo!("tl.T52")
}
/// Stamps the capsule from `from` to `to` (document units) of radius `radius`, keeping the larger coverage.
pub fn stamp_capsule(&mut self, from: Point, to: Point, radius: f64) {
let _ = (from, to, radius);
todo!("tl.T52")
}
/// Writes `max(coverage(point), base)` into the texels of `rect`; `coverage` is asked at document points.
pub fn restamp(&mut self, rect: Rect, coverage: impl Fn(Point) -> f32) {
let _ = (rect, coverage);
todo!("tl.T52")
}
/// Starts a stroke: the coverage so far becomes the base `restamp` keeps.
pub fn begin_stroke(&mut self) {
todo!("tl.T52")
}
/// The coverage at the document point `at`, 0 outside the mask.
pub fn coverage_at(&self, at: Point) -> u8 {
let _ = at;
todo!("tl.T52")
}
/// Document units per texel.
pub fn scale(&self) -> f64 {
todo!("tl.T52")
}
/// The mask's size in texels, width then height.
pub fn size(&self) -> (u32, u32) {
todo!("tl.T52")
}
}
/// What the trail shows its footprint as.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum TrailTone {
/// The marquee's colour.
#[default]
Light,
/// The halo's colour.
Shade,
/// The bad status colour.
Danger,
}
/// The style of the stroke trail: the texture carries the colour, so only the metrics.
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
#[non_exhaustive]
pub struct StrokeTrailStyle {
#[style(metrics)]
metrics: Metrics,
/// The colour of a [`TrailTone::Light`] footprint.
light: StyleColor,
/// The colour of a [`TrailTone::Shade`] footprint.
shade: StyleColor,
/// The colour of a [`TrailTone::Danger`] footprint.
danger: StyleColor,
}
/// The footprint of the stroke being painted, drawn from a [`CoverageMask`] as one textured quad over the mask's
/// document rect. Display only.
#[derive(crate::contract::Component, crate::contract::Props)]
#[component(canvas_control, content_painter)]
pub struct StrokeTrail<'a> {
#[common]
common: Common,
#[allow(dead_code)] // P3(tools-w17): tl.T52
mask: &'a mut CoverageMask,
/// What the footprint shows as.
#[prop]
#[allow(dead_code)] // P3(tools-w17): tl.T52
tone: TrailTone,
}
impl<'a> StrokeTrail<'a> {
/// A trail named `label` over `mask`.
pub fn new(label: impl Into<Label>, mask: &'a mut CoverageMask) -> Self {
StrokeTrail { common: Common::new(), mask, tone: TrailTone::Light }.label(label)
}
}
impl Component for StrokeTrail<'_> {
const ROLE: Role = Role::GROUP;
const INPUT: Input = Input::Display;
const PARTS: bool = false;
const STOPS: bool = false;
const OVERLAYS: bool = false;
type Style = StrokeTrailStyle;
type Output = Response;
fn style(cx: &StyleCx<'_>, _: StrokeTrailStyleKey) -> StrokeTrailStyle {
let color = &cx.tokens.color;
StrokeTrailStyle {
metrics: Metrics::new(),
light: cx.color(color.overlay.marquee),
shade: cx.color(color.overlay.halo),
danger: cx.color(color.status.bad.solid),
}
}
fn measure(&mut self, _: &MeasureCx<'_, Self>) -> egui::Vec2 {
egui::Vec2::ZERO
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let _ = (ui, cx);
todo!("tl.T52")
}
fn access(&self, access: &mut Access, _: &Cx<'_, Self>) {
access.role(Role::None);
}
fn finish(self, cx: Cx<'_, Self>) -> Response {
cx.response.clone()
}
}
@@ -2,6 +2,7 @@
//! arena, so a press on a guide stays with the guides and one elsewhere reaches the tool.
mod place;
pub mod reading;
#[cfg(feature = "testing")]
mod stories;
@@ -102,7 +103,7 @@ struct Report {
select: Option<Option<GuideKey>>,
clicked: Option<(GuideKey, Mods, Point)>,
double_clicked: Option<GuideKey>,
context: Option<GuideKey>,
context: Option<(GuideKey, Pos2)>,
}
/// The key of the guide a ruler drag is creating, kept for the length of the drag.
@@ -142,6 +143,10 @@ pub struct Guides<'a> {
/// draw.
#[prop]
interactive: bool,
/// With `interactive` off, a press on an unlocked guide with the platform command key held takes the guide.
#[prop]
#[allow(dead_code)] // P3(canvas-widgets-w2): cw.C22
moves_with_command: bool,
/// Where guides may live, in document units; a guide released outside is removed. Without bounds, the canvas.
#[prop]
bounds: Option<DocRect>,
@@ -165,6 +170,7 @@ impl<'a> Guides<'a> {
guides,
selected: None,
interactive: false,
moves_with_command: false,
bounds: None,
step: NUDGE,
big_step: NUDGE_FAR,
@@ -309,8 +315,8 @@ impl<'a> Guides<'a> {
}
}
for guide in guides.iter().filter(|guide| !guide.locked) {
if context_menu(cx, guide.key.part(GUIDE)).is_some() {
self.report.context = Some(guide.key);
if let Some(at) = context_menu(cx, guide.key.part(GUIDE)) {
self.report.context = Some((guide.key, at));
}
}
}
@@ -389,8 +395,8 @@ pub struct GuidesOutput {
pub clicked: Option<(GuideKey, Mods, Point)>,
/// A guide pressed twice, for the guide dialog.
pub double_clicked: Option<GuideKey>,
/// A guide clicked with the secondary button, for the app's guide menu.
pub context: Option<GuideKey>,
/// A guide clicked with the secondary button, for the app's guide menu, and where it was asked for the menu.
pub context: Option<(GuideKey, Pos2)>,
}
impl Outcome for GuidesOutput {
@@ -0,0 +1,20 @@
//! `GuideReading`: the guide a drag is moving or creating, read from the running gesture.
use craft_behavior::Axis;
use egui::{Context, Id};
/// The position and orientation of the guide a drag is moving or creating.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GuideReading {
/// The axis the guide runs along.
pub along: Axis,
/// The guide's position across that axis, in document units.
pub position: f64,
}
/// The guide a drag is moving or creating on the canvas `canvas`, read from the framework's running gesture of the
/// guide parts, so a panel drawn before or after the canvas reads the same value; `None` when no guide drag runs.
pub fn running(ctx: &Context, canvas: Id) -> Option<GuideReading> {
let _ = (ctx, canvas);
todo!("cw.C74")
}
@@ -27,19 +27,23 @@ pub struct LineGuideStyle {
/// The Shift-click line from `from` (the end of the last stroke) to `to` (the pointer), both in document units. A
/// non-finite end draws nothing. The brush tip at the pointer is the cursor's, not this line's.
#[derive(crate::contract::Component)]
#[derive(crate::contract::Component, crate::contract::Props)]
#[component(canvas_control)]
pub struct StraightLinePreview {
#[common]
common: Common,
from: Point,
to: Point,
/// A filled disc in the line colour at `from`, twice the thick stroke wide: the brush end of the smoothing string.
#[prop(flag)]
#[allow(dead_code)] // P3(tools-w17): cw.C36
dot: bool,
}
impl StraightLinePreview {
/// A line named `label` from `from` to `to` (document units).
pub fn new(label: impl Into<Label>, from: Point, to: Point) -> Self {
StraightLinePreview { common: Common::new(), from, to }.label(label)
StraightLinePreview { common: Common::new(), from, to, dot: false }.label(label)
}
}
+3 -1
View File
@@ -6,7 +6,7 @@ mod words;
mod guides;
mod smart_guides;
pub use guides::{GuideCommands, GuideStyle, Guides, GuidesOutput};
pub use guides::{GuideCommands, GuideStyle, Guides, GuidesOutput, reading};
pub use smart_guides::{Measure, SmartGuides, SmartGuidesStyle, SmartLine};
pub use words::CanvasControlWords;
@@ -17,6 +17,7 @@ mod line_preview;
mod marquee;
mod outline;
mod pixel_grid;
mod task_bar;
pub use bands::{range_bands, rect_around};
pub use grid::{CanvasGrid, GridAxis, GridLine, GridLines, GridStyle, MAX_LINES};
@@ -24,6 +25,7 @@ pub use line_preview::{LineGuideStyle, StraightLinePreview};
pub use marquee::{Marquee, MarqueeLook, MarqueeShape, MarqueeStyle, Run};
pub use outline::{HoverMask, HoverOutline, HoverShape, OutlineStyle, SelectionOutline, SelectionOutlineLook, path_runs};
pub use pixel_grid::{GridSegment, PixelGrid, PixelGridStyle};
pub use task_bar::{TaskBar, TaskBarCx, TaskBarOutput, TaskBarPlace};
// End of canvas-controls-b.
// Brush overlays.
@@ -6,11 +6,12 @@ mod stories;
use crate::canvas::{CanvasRulers, canvas_space};
use crate::contract::{Common, Component, Cx, MeasureCx, PaintUi, Role};
use crate::primitives::{Dashes, PaintShape, Rule, StrokeWidth, TextRun};
use crate::primitives::{ContentPainterCx, Dashes, PaintShape, Rule, StrokeWidth, TextRun};
use crate::runtime::env::Units;
use crate::style::{ComponentStyle, DataColor, RuleLook, RuleWidth, StyleColor, StyleCx, TypeRole, UiTokens};
use craft_behavior::geometry::SnapLine;
use craft_behavior::kurbo::{Point, Rect as DocRect};
use craft_behavior::{Metrics, Sense};
use craft_behavior::{CanvasView, Metrics, Sense};
use craft_theme::{Rgba, contrast_ratio};
use egui::emath::GuiRounding as _;
use egui::{Color32, CornerRadius, Pos2, Response, Vec2};
@@ -33,6 +34,12 @@ impl SmartLine {
Self { a, b, extension: false }
}
/// The line of `line` the host draws for a snap: a line with no span runs across `visible`.
pub fn of(line: &SnapLine, visible: DocRect) -> SmartLine {
let _ = (line, visible);
todo!("cw.C18")
}
/// The same line as a dashed extension.
#[must_use]
pub const fn dashed(mut self) -> Self {
@@ -130,6 +137,28 @@ impl<'a> SmartGuides<'a> {
}
}
/// The line loop of [`SmartGuides`]'s paint: a rule per line, an extension dashed. The tool host paints the snapped
/// lines through it outside a canvas body, where `SmartGuides` paints nothing.
pub(crate) fn paint_lines(
painter: &ContentPainterCx<'_>,
view: &CanvasView,
lines: &[SmartLine],
style: &SmartGuidesStyle,
color: Option<DataColor>,
) {
let fill = color.map_or(style.smart.egui(), |color| color.0);
let ppp = painter.pixels_per_point();
let line = RuleLook { color: fill, width: RuleWidth::Points(style.width) };
for smart in lines {
let (a, b) = (view.to_screen(smart.a), view.to_screen(smart.b));
if smart.extension {
painter.dashed(&[a, b], Dashes::even(style.dash), StrokeWidth::Thin, fill);
} else {
painter.painter.extend(Rule::shapes(&line, a, b, ppp));
}
}
}
fn contrast(fill: Color32, ink: StyleColor) -> f64 {
let rgba = |color: Color32| Rgba(color.to_array());
contrast_ratio(rgba(ink.egui()), rgba(fill))
@@ -181,14 +210,7 @@ impl Component for SmartGuides<'_> {
let corners = view.quad(bounds).to_vec();
ui.draw().stroke(&PaintShape::Polygon(corners), StrokeWidth::Thin, style.bounds);
}
for smart in self.lines {
let (a, b) = (view.to_screen(smart.a), view.to_screen(smart.b));
if smart.extension {
painter.dashed(&[a, b], Dashes::even(style.dash), StrokeWidth::Thin, fill);
} else {
painter.painter.extend(Rule::shapes(&line, a, b, ppp));
}
}
paint_lines(&painter, view, self.lines, style, self.color);
let ink = if contrast(fill, style.ink_dark) >= contrast(fill, style.ink_light) { style.ink_dark } else { style.ink_light };
let draw = ui.draw();
let (rulers, numbers) = (space.rulers(), cx.env.units());
@@ -0,0 +1,72 @@
//! `TaskBar`: the contextual task bar over a canvas, hung below its anchor until the user moves it.
use crate::contract::{Bind, Inner};
use crate::runtime::env::Label;
use craft_behavior::kurbo::Point;
use egui::{Rect, Response, Ui};
use std::marker::PhantomData;
/// Where the task bar sits: pinned or following its anchor, and where the user moved it. The one owner of the bar's
/// place; the serde shape is PhotoCraft's, so saved preferences load unchanged, and a non-finite `at` counts as unset.
#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct TaskBarPlace {
/// The bar keeps its place instead of following the anchor.
#[serde(default)]
pub pinned: bool,
/// The bar's top left corner relative to the area's, once moved; `None` while it follows the anchor.
#[serde(default)]
pub at: Option<[f32; 2]>,
}
/// The contextual task bar: a movable modeless layer hung below the screen bounds of `anchor` while its place is
/// unset, with a body of members and a More menu (Hide, Reset, Pin). One place, pin and Hide setting for Crop and
/// Frame.
#[must_use = "show the task bar with `show`"]
#[derive(crate::contract::Pattern, crate::contract::Props)]
pub struct TaskBar<'a> {
#[allow(dead_code)] // P3(tools-w16): tl.T49
label: Label,
#[allow(dead_code)] // P3(tools-w16): tl.T49
anchor: &'a [Point],
#[allow(dead_code)] // P3(tools-w16): tl.T49
place: Bind<'a, TaskBarPlace>,
}
/// What the task bar reports.
#[derive(Debug)]
#[non_exhaustive]
pub struct TaskBarOutput {
/// The bar's response.
pub response: Response,
/// Hide bar was picked from the More menu.
pub hide: bool,
/// The bar's rect on screen.
pub rect: Rect,
}
/// The context the task bar's body gets.
pub struct TaskBarCx<'a> {
marker: PhantomData<&'a mut ()>,
}
impl TaskBarCx<'_> {
/// Places the More menu button here, before the members that follow it (the Crop bar puts Cancel and Done after
/// it); without the call the button comes after the body.
pub fn more_menu(&mut self, ui: &mut Ui) {
let _ = ui;
todo!("tl.T49")
}
}
impl<'a> TaskBar<'a> {
/// A bar named `label` hung below the screen bounds of `anchor` (document points) until `place` moves it.
pub fn new(label: impl Into<Label>, anchor: &'a [Point], place: Bind<'a, TaskBarPlace>) -> Self {
TaskBar { label: label.into(), anchor, place }
}
/// Shows the bar inside `area`; `body` fills its members.
pub fn show<R>(self, ui: &mut Ui, area: Rect, body: impl FnOnce(&mut Ui, &mut TaskBarCx<'_>) -> R) -> Inner<TaskBarOutput, R> {
let _ = (ui, area, body);
todo!("tl.T49")
}
}
@@ -21,5 +21,11 @@ craft_ui::words! {
hardness: "brushResize.hardness" = "Hardness:";
opacity: "brushResize.opacity" = "Opacity:";
density: "brushResize.density" = "Density:";
task_bar_move: "taskBar.move" = "Move bar";
task_bar_more: "taskBar.more" = "More options";
task_bar_hide: "taskBar.hide" = "Hide bar";
task_bar_reset: "taskBar.reset" = "Reset bar position";
task_bar_pin: "taskBar.pin" = "Pin bar position";
}
}
+1 -1
View File
@@ -31,7 +31,7 @@ pub mod canvas_controls;
/// Dialog shells and prompts, with the full-window dialog family that shows a canvas.
pub mod dialog {
pub use crate::canvas::full_window::{FullWindowDialog, FullWindowDialogStyle, FullWindowWorkspace, HostedWorkspace, WorkspacePass};
pub use crate::canvas::full_window::{FullWindowDialog, FullWindowDialogStyle, FullWindowWorkspace, HostedWorkspace, WorkspaceCx, WorkspacePass};
pub use crate::canvas::full_window_parts::{
FullWindowCanvas, FullWindowCanvasOutput, FullWindowSide, FullWindowSideOutput, FullWindowSideStyle, FullWindowStatus,
FullWindowStatusOutput, FullWindowTitle, FullWindowTitleOutput, FullWindowView, FullWindowZoomBar, FullWindowZoomBarOutput, RasterOverlay,
+1 -1
View File
@@ -221,7 +221,7 @@ fn a_corner_drag_resizes_along_the_frame_axes_in_a_turned_view() {
let view = rig.view();
let corner = view.to_screen(b.corners()[2]);
let to = corner + Vec2::new(14.0, -9.0);
let want = b.resized(BoxPart::Corner(2), view.to_doc(to) - view.to_doc(corner), None, false);
let want = b.resized(BoxPart::Corner(2), view.to_doc(to) - view.to_doc(corner), craft_behavior::geometry::AspectHold::Free, false); // P3(tools-w15): tl.T41
rig.drag(corner, to, Modifiers::NONE);
assert!(near(&rig.crop(), &want), "{:?} vs {want:?}", rig.crop());
assert_eq!(rig.seen.borrow().picked, Some(BoxPart::Corner(2)));
@@ -13,9 +13,13 @@ use craft_behavior::{Cursor, CursorPriority, PartRef, PressState};
#[derive(Clone, Default)]
struct BandDouble(bool);
/// Whether the primary press of this pass went down on the container's own surface (`Sense::SURFACE`).
/// Whether the primary press of this pass went down on the container's own surface (`Sense::SURFACE`), and whether it
/// is the second of a double click.
#[derive(Clone, Default)]
struct SurfacePress(bool);
struct SurfacePress {
pressed: bool,
double: bool,
}
impl BodyCx<'_> {
/// Whether the second press of a double click went down on the container's move band in this pass. The body step
@@ -38,7 +42,13 @@ impl BodyCx<'_> {
/// container decides what it means (a dock group focuses its panel, as Photoshop does); it is no click and moves
/// no focus by itself.
pub fn surface_pressed(&self) -> bool {
self.memory.recall::<SurfacePress>(sub(self.id, "surface_press")).0
self.memory.recall::<SurfacePress>(sub(self.id, "surface_press")).pressed
}
/// Whether the press of [`surface_pressed`](Self::surface_pressed) is the second press of a double click: no child
/// or part takes it and its click count is two or more. One own-surface signal for every container.
pub fn surface_double_pressed(&self) -> bool {
self.memory.recall::<SurfacePress>(sub(self.id, "surface_press")).double
}
/// Requests `cursor` at `priority` for this pass, in the cursor service the parts' and components' requests go
@@ -70,7 +80,9 @@ impl BodyHooks<'_> {
},
)
};
cx.core.memory.shown::<SurfacePress>(sub(sub(cx.core.id, "body"), "surface_press")).0 = pressed;
let shown = cx.core.memory.shown::<SurfacePress>(sub(sub(cx.core.id, "body"), "surface_press"));
shown.pressed = pressed;
shown.double = false; // P3(canvas-widgets-w9): cw.C46
}
/// Records for the container's header hooks whether the second press of a double click went down on the move
@@ -477,8 +477,11 @@ impl BodyHooks<'_> {
} else {
// A pointer move of this pass is relative to where the window was when the system sent it, which is where
// the window reports itself now; a position from an earlier pass was measured against an older place.
let moved =
pointer::pass_pointer(&ctx).events.iter().rev().find_map(|event| if let PointerEvent::Moved(at) = event { Some(*at) } else { None });
let moved = pointer::pass_pointer(&ctx)
.events
.iter()
.rev()
.find_map(|event| if let PointerEvent::Moved { at, .. } = event { Some(*at) } else { None });
moved.map(|at| facts.inner.min + (at.to_vec2() - moving.grab) - inset)
};
let Some(to) = to.filter(|to| *to != moving.at.min) else { return };
+1 -1
View File
@@ -272,7 +272,7 @@ pub(crate) fn pointer_read(ctx: &Context) -> PointerRead {
}
Event::PointerMoved(pos) => {
stirred = true;
events.push(PointerEvent::Moved(*pos));
events.push(PointerEvent::Moved { at: *pos, sample: None }); // P3(canvas-widgets-w4): cw.C73
}
Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, .. } => {
events.push(PointerEvent::pressed(*pos, input.time, 1));
+17
View File
@@ -2,6 +2,7 @@
use crate::runtime::egui::{input, plugin};
use crate::runtime::env::{SystemReader, system};
use crate::runtime::pen::PenSource;
use crate::runtime::{commands, frame, windows};
use crate::style::{DuplicateStyle, StyleReplacements};
use craft_host::target::ShellInfo;
@@ -9,6 +10,7 @@ use craft_window::policy::Decision;
use craft_window::restore::Store;
use craft_window::system::WindowSystem;
use egui::Context;
use std::sync::{Arc, Mutex};
/// What `install` takes.
@@ -35,6 +37,8 @@ pub struct InstallSpec {
pub wheel: WheelModifiers,
/// The app id every OS window carries (dock icon, Wayland compositor rules); empty carries none.
pub app_id: String,
/// The tablet readings the pointer feed pairs with each pointer move; none reports no pen.
pub pen: Option<PenSource>,
}
/// The modifiers the mouse wheel zooms and scrolls sideways with.
@@ -65,6 +69,7 @@ impl InstallSpec {
system: SystemReader::unwatched(),
wheel: WheelModifiers::default(),
app_id: String::new(),
pen: None,
}
}
@@ -98,6 +103,18 @@ impl InstallSpec {
self
}
/// Sets the app id every OS window carries (dock icon, Wayland compositor rules).
pub fn app_id(mut self, id: impl Into<String>) -> Self {
self.app_id = id.into();
self
}
/// Sets the tablet source the pointer feed reads.
pub fn pen(mut self, source: PenSource) -> Self {
self.pen = Some(source);
self
}
/// Sets the end hook's ghost-layer painter.
pub fn frame_layers(mut self, painter: Option<fn(&Context)>) -> Self {
self.frame_layers = painter;
+1
View File
@@ -23,6 +23,7 @@ pub mod memory;
pub mod motion;
pub mod overlay;
pub(crate) mod pass_state;
pub mod pen;
pub mod pending;
pub mod pointer;
pub(crate) mod reads;
+53
View File
@@ -0,0 +1,53 @@
//! `PenSource`: the tablet's readings, which the runtime's one pointer feed pairs with each pointer move.
use craft_behavior::PointerSample;
use std::sync::{Arc, Mutex};
/// What the tablet hooks have written and the pass has not yet read.
#[derive(Default)]
#[allow(dead_code)] // P3(canvas-widgets-w4): cw.C73
struct Readings {
queued: Vec<PointerSample>,
current: Option<PointerSample>,
barrel: bool,
}
/// A shared handle the app's platform tablet hooks write into and the runtime reads once per pass. Clones share one
/// queue.
#[derive(Clone, Default)]
pub struct PenSource {
readings: Arc<Mutex<Readings>>,
}
impl PenSource {
/// Queues one tablet reading in order; `None` says the pen left the tablet.
pub fn set(&self, sample: Option<PointerSample>) {
let _ = sample;
todo!("cw.C73")
}
/// Sets whether the barrel button is down.
pub fn set_barrel(&self, down: bool) {
let _ = down;
todo!("cw.C73")
}
/// Takes the readings queued since the last pass, in order.
#[allow(dead_code)] // P3(canvas-widgets-w4): cw.C73
pub(crate) fn drain(&self) -> Vec<PointerSample> {
let _ = &self.readings;
todo!("cw.C73")
}
/// The latest reading, if the pen is on the tablet.
#[allow(dead_code)] // P3(canvas-widgets-w4): cw.C73
pub(crate) fn current(&self) -> Option<PointerSample> {
todo!("cw.C73")
}
/// Whether the barrel button is down.
#[allow(dead_code)] // P3(canvas-widgets-w4): cw.C73
pub(crate) fn barrel(&self) -> bool {
todo!("cw.C73")
}
}
+5
View File
@@ -195,6 +195,11 @@ pub struct StandardPrompt {
type Content = (Label, Label, Vec<(PromptChoice, Reply)>);
impl StandardPrompt {
/// The tag attached with the `tag` builder, when it is a `T`: tells which family's prompt is open.
pub fn tag_as<T: Any>(&self) -> Option<&T> {
self.tag.as_deref()?.downcast_ref()
}
/// A prompt asking `kind`, with no tag and no "Don't show again" box.
pub fn new(kind: PromptKind) -> Self {
Self {
+1 -1
View File
@@ -167,7 +167,7 @@ fn create<A: ShellApp + 'static>(
move |cc| {
let ctx = cc.egui_ctx.clone();
let system = crate::runtime::env::SystemReader::start(move || ctx.request_repaint());
let mut install = InstallSpec::new(spec.shell_info, spec.window_system).placement(spec.placement).system(system);
let mut install = InstallSpec::new(spec.shell_info, spec.window_system).placement(spec.placement).system(system).app_id(spec.app_id.clone());
if let Some(decision) = spec.frame {
install = install.frame(decision);
}
+7
View File
@@ -278,6 +278,11 @@ pub struct AppShell<'a, S> {
/// The host's flag for the document tabs, read back through `ShellCx::tabs_visible`.
#[prop]
document_tabs: bool,
/// The window's title: the shell sends `WindowAction::SetTitle` when it differs from the title the viewport
/// reports. Not in an embedded shell.
#[prop(into)]
#[allow(dead_code)] // P3(panels-w10): pn.C10
window_title: Option<String>,
/// The name of the body region; the translated "Document" without it.
#[prop(into)]
body_label: Option<Label>,
@@ -300,6 +305,7 @@ impl<'a, S> AppShell<'a, S> {
allow_reveal: true,
edge_reveal: true,
document_tabs: true,
window_title: None,
body_label: None,
title: None,
slots: Vec::new(),
@@ -414,6 +420,7 @@ impl<'a, S> AppShell<'a, S> {
allow_reveal,
edge_reveal,
document_tabs,
window_title: _, // P3(panels-w10): pn.C10
body_label,
title,
slots,
+3 -1
View File
@@ -53,6 +53,8 @@ pub struct CanvasPanelOutput {
pub tabs: Option<Rect>,
/// The document area.
pub document: Rect,
/// The second press of a double click on the document pane's own surface, where no document control took it.
pub empty_double: bool,
}
impl Outcome for CanvasPanelOutput {
@@ -124,7 +126,7 @@ impl<'a> CanvasPanel<'a> {
tabs_rect = Some(out.response.rect);
}
let out = ShellRegion::pane(ShellPane::new("document")).id_salt("document").label(words.document.clone()).show(ui, |ui, cx| document(ui, cx));
CanvasPanelOutput { document: out.response.rect, response: out.output.response, rail: rail_rect, tabs: tabs_rect }
CanvasPanelOutput { document: out.response.rect, response: out.output.response, rail: rail_rect, tabs: tabs_rect, empty_double: false } // P3(canvas-widgets-w9): cw.C46
}
}
+28 -1
View File
@@ -45,6 +45,19 @@ pub struct DocumentWindowOutput {
pub cascade: f32,
/// The window gained OS focus in this pass.
pub focus_gained: bool,
/// Whether the window took the size a zoom edit asked for in this pass (`Fits`: the host centres the document) or
/// the work area capped it (`Capped`: the zoomed spot stays); `None` when nothing was asked or sent.
pub wrapped: Option<Wrapped>,
}
/// How a window answered the size a zoom edit asked for ([`DocumentWindow::wrap_in`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Wrapped {
/// The window took the wanted size.
Fits,
/// The monitor's work area capped the size.
Capped,
}
impl Outcome for DocumentWindowOutput {
@@ -89,6 +102,13 @@ pub struct DocumentWindow<'a> {
}
impl<'a> DocumentWindow<'a> {
/// Files the zoom edit's size request from the window's body: the window sizes itself so its `canvas` rect becomes
/// `wanted`, in the pass `finish` reads it, keeping its centre and staying inside the monitor's work area.
pub fn wrap_in(cx: &mut BodyCx<'_>, canvas: Rect, wanted: Vec2) {
let _ = (cx, canvas, wanted);
todo!("cw.C53")
}
/// A window titled `title`, resizable, with the installed decision's frame.
pub fn new(title: impl Into<Label>) -> Self {
let fallback = Overlay::floating().resizable(true).fit(OverlayFit::Resizable);
@@ -197,7 +217,14 @@ impl Component for DocumentWindow<'_> {
if focus_gained && let Some(activate) = self.activate.as_mut() {
activate();
}
DocumentWindowOutput { response: cx.response.clone(), close_requested: self.closed, focused, cascade: cx.style.cascade, focus_gained }
DocumentWindowOutput {
response: cx.response.clone(),
close_requested: self.closed,
focused,
cascade: cx.style.cascade,
focus_gained,
wrapped: None,
} // P3(canvas-widgets-w9): cw.C53
}
}
+6 -2
View File
@@ -19,12 +19,16 @@ pub use regions::{Slot, SlotSize};
// App shell, canvas panel, screen modes and reveal.
mod app_shell;
mod canvas_shell;
mod opening;
mod reveal;
mod screen_mode;
mod screen_mode_button;
pub use app_shell::{AppShell, AppShellOutput, ShellDialogsCx, ShellRegion, ShellRegionOutput, WindowDialogs};
pub use canvas_shell::{CanvasPanel, CanvasPanelOutput, slots};
pub use opening::{OpeningCard, OpeningCardOutput};
pub use screen_mode::{ScreenMode, ScreenModeCommands};
pub use screen_mode_button::{ScreenModeButton, ScreenModeButtonOutput};
pub use words::ShellWords;
// Start screen and app windows.
@@ -33,7 +37,7 @@ mod start;
mod viewport_window;
pub use recent::{RecentFile, RecentSort, RecentView, Template, ThumbKey, sort_recent};
pub use start::{StartAction, StartOutput, StartPinnedCommands, StartRecentCommands, StartScreen};
pub use start::{StartAction, StartLink, StartLinkTarget, StartOutput, StartPinnedCommands, StartRecentCommands, StartScreen};
pub use viewport_window::{ViewportWindow, ViewportWindowOutput};
// Caption buttons: the four families' button, its slot layout and the icon-theme glyphs.
@@ -47,7 +51,7 @@ pub use craft_window::policy::{CaptionFamily, Captions, Frame, MacInset};
// A document's window: a container in its own OS viewport.
mod document_window;
pub use document_window::{DocumentWindow, DocumentWindowOutput, DocumentWindowStyle};
pub use document_window::{DocumentWindow, DocumentWindowOutput, DocumentWindowStyle, Wrapped};
// The title bar: the bar, its title and its output.
pub use title_bar::{Title, TitleBar, TitleBarOutput, TitleBarStyle};
+64
View File
@@ -0,0 +1,64 @@
//! `OpeningCard`: the card shown in the document area while a file opens.
use crate::contract::Pattern;
use crate::runtime::env::Label;
use egui::{Response, Ui};
/// A centred card: "Opening {name}…" elided on one line with the full text on hover, the muted message, a progress bar
/// (indeterminate without a fraction), the percentage at the start and Cancel at the end of the last row. Job UI
/// only: the fraction and the cancel answer come from the app's engine job.
#[must_use = "show the card with `show`"]
#[derive(Pattern)]
pub struct OpeningCard {
#[allow(dead_code)] // P3(top-w5): tp.T31
name: Label,
#[allow(dead_code)] // P3(top-w5): tp.T31
message: Option<Label>,
#[allow(dead_code)] // P3(top-w5): tp.T31
fraction: Option<f32>,
#[allow(dead_code)] // P3(top-w5): tp.T31
cancel: Option<Label>,
}
/// What an [`OpeningCard`] reports.
#[derive(Debug)]
pub struct OpeningCardOutput {
/// The card's response.
pub response: Response,
/// Cancel was picked in this pass.
pub cancelled: bool,
}
impl OpeningCard {
/// A card for the file `name`.
pub fn new(name: impl Into<Label>) -> Self {
OpeningCard { name: name.into(), message: None, fraction: None, cancel: None }
}
/// The muted message under the title.
#[must_use]
pub fn message(mut self, message: impl Into<Label>) -> Self {
self.message = Some(message.into());
self
}
/// How far the job is, 0 to 1; `None` shows an indeterminate bar.
#[must_use]
pub fn fraction(mut self, fraction: Option<f32>) -> Self {
self.fraction = fraction;
self
}
/// The Cancel button's text; without it the card has no Cancel.
#[must_use]
pub fn cancel(mut self, cancel: impl Into<Label>) -> Self {
self.cancel = Some(cancel.into());
self
}
/// Shows the card centred in `ui`.
pub fn show(self, ui: &mut Ui) -> OpeningCardOutput {
let _ = ui;
todo!("tp.T31")
}
}
@@ -0,0 +1,34 @@
//! `ScreenModeButton`: the status bar's screen mode button, a flyout of the three modes.
use super::screen_mode::ScreenMode;
use egui::{Response, Ui};
/// A flyout button over the three screen modes, with `mode` marked: a click, Enter or Space cycles; a hold, a drag away
/// or a right click lists the three modes without cycling. The face is the Cycle command's icon and tooltip; disabled
/// while Cycle is disabled.
#[must_use = "show the button with `show`"]
#[derive(crate::contract::Pattern)]
pub struct ScreenModeButton {
#[allow(dead_code)] // P3(panels-w10): pn.C16
mode: ScreenMode,
}
/// What a [`ScreenModeButton`] reports.
#[derive(Debug)]
pub struct ScreenModeButtonOutput {
/// The button's response.
pub response: Response,
}
impl ScreenModeButton {
/// A button showing `mode` as the current one.
pub fn new(mode: ScreenMode) -> Self {
ScreenModeButton { mode }
}
/// Shows the button in `ui`.
pub fn show(self, ui: &mut Ui) -> ScreenModeButtonOutput {
let _ = ui;
todo!("pn.C16")
}
}
+76 -4
View File
@@ -17,7 +17,8 @@ use crate::list::{List, ListRow, ThumbAspect};
use crate::menu::{Menu, MenuItem};
use crate::notices::{Notice, NoticeLayout};
use crate::pickers::Select;
use crate::primitives::{CachedTexture, ContentPainterCx, IconSpec, Revision, TextureState, TextureStore};
use crate::primitives::{CachedTexture, ContentPainterCx, IconSpec, Revision, TextureState, TextureStore, ThumbSource, Thumbnails};
use crate::runtime::commands::CommandRef;
use crate::runtime::commands::{CommandSet as _, Commands as _};
use crate::runtime::env::{AgeStyle, Env, Label};
use crate::sections::Section;
@@ -155,14 +156,85 @@ pub struct StartScreen<'a> {
#[prop]
now: Option<i64>,
/// The store that holds the thumbnails and previews, which the app fills.
#[prop]
thumbnails: Option<TextureStore<ThumbKey>>,
/// The thumbnails and the source of each key's revision: cards, rows and templates ask `Thumbnails::state`.
#[allow(dead_code)] // P3(top-w5): tp.T29
shown: Option<(&'a Thumbnails<ThumbKey>, &'a dyn ThumbSource<ThumbKey>)>,
/// The links beside the page: New and Open at the rail's top, then these.
#[prop]
links: &'a [StartLink],
/// With no recent files, the Recent body is a drop card with this hint, and a double click on the page's own room
/// reports `StartAction::Open`.
#[prop(into)]
#[allow(dead_code)] // P3(canvas-widgets-w9): cw.C45
drop_hint: Option<Label>,
}
/// A link on the start screen's rail.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct StartLink {
/// The link's text.
pub label: Label,
/// The link's icon, a catalogue name (`home`, `globe`).
pub icon: Option<IconId>,
/// What the link does.
pub target: StartLinkTarget,
}
/// What a [`StartLink`] does.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum StartLinkTarget {
/// Opens the URL itself.
Url(String),
/// Fires the command.
Command(CommandRef),
}
impl StartLink {
/// A link that opens `url`, shown as its tooltip.
pub fn url(label: impl Into<Label>, icon: Option<IconId>, url: impl Into<String>) -> Self {
StartLink { label: label.into(), icon, target: StartLinkTarget::Url(url.into()) }
}
/// A link that fires `command`.
pub fn command(label: impl Into<Label>, icon: Option<IconId>, command: impl Into<CommandRef>) -> Self {
StartLink { label: label.into(), icon, target: StartLinkTarget::Command(command.into()) }
}
}
impl<'a> StartScreen<'a> {
/// A start screen of `recent` files, shown in `view` and ordered by `sort`; names sort in the env's language.
pub fn new(view: Bind<'a, RecentView>, sort: Bind<'a, RecentSort>, recent: &'a [RecentFile]) -> Self {
StartScreen { view, sort, recent, pinned: None, templates: &[], max_recent: RECENT_SHOWN, now: None, thumbnails: None }
StartScreen {
view,
sort,
recent,
pinned: None,
templates: &[],
max_recent: RECENT_SHOWN,
now: None,
thumbnails: None,
shown: None,
links: &[],
drop_hint: None,
}
}
/// Cards, rows and templates ask `thumbnails.state(..)` for what they show; `source` gives each key's revision.
#[must_use]
pub fn thumbnails(mut self, thumbnails: &'a Thumbnails<ThumbKey>, source: &'a dyn ThumbSource<ThumbKey>) -> Self {
self.shown = Some((thumbnails, source));
self
}
/// The store of thumbnails the page reads today.
#[must_use]
pub(crate) fn texture_store(mut self, store: TextureStore<ThumbKey>) -> Self {
// P3(top-w5): tp.T29
self.thumbnails = Some(store);
self
}
}
@@ -290,7 +362,7 @@ fn read_events<K: Clone, E>(events: Vec<CollectionEvent<K, E>>, lead: &mut Optio
impl StartScreen<'_> {
/// Shows the page across the available room and reports what the user did.
pub fn show(self, ui: &mut Ui) -> StartOutput {
let StartScreen { view, sort, recent, pinned, templates, max_recent, now, thumbnails } = self;
let StartScreen { view, sort, recent, pinned, templates, max_recent, now, thumbnails, .. } = self; // P3(top-w5): tp.T29
let env = Env::of(ui);
let collator = env.collator();
let words = env.words::<ShellWords>();
+1 -1
View File
@@ -97,7 +97,7 @@ fn screen(ui: &mut Ui, data: &mut StoryData, choice: Choice, files: &[RecentFile
.pinned(pinned)
.templates(templates)
.now(NOW)
.thumbnails(store)
.texture_store(store) // P3(top-w5): tp.T29
.show(ui)
.into();
*data.value("choice", Choice::default()) = choice;
+11 -4
View File
@@ -8,7 +8,7 @@ use super::style::TitleBarStyle;
use super::title::{Title, centre_line};
use crate::contract::{
Access, BodyCx, BodyLayout, Common, Component, Container, ContainerProps, Cx, DragBand, EndRegion, Gap, HeaderRegion, NoValue, Outcome, Pad,
PaintUi, Role, ShowContainer as _, Sizing, WordSetCx as _,
PaintUi, PartsCx, Role, ShowContainer as _, Sizing, WordSetCx as _,
};
use crate::layout::{Placed, arrange};
use crate::primitives::{RectSide, RuleKind};
@@ -19,9 +19,9 @@ use crate::runtime::windows::{self, WindowAction, WindowHost};
use crate::shell::app_shell::RegionBody;
use crate::shell::{Caption, CaptionButton, CaptionIcons, Frame, ShellWords, SlotSize};
use crate::style::{StyleCx, SurfaceKind};
use craft_behavior::Sense;
use craft_behavior::{PartKey, Sense};
use craft_host::target::{DoubleClick, WindowState};
use egui::{Response, Ui};
use egui::{Rect, Response, Ui};
/// What a title bar reports: the caption clicked and whether the window was asked to close.
#[derive(Debug)]
@@ -213,7 +213,7 @@ impl Default for TitleBar<'_> {
impl Component for TitleBar<'_> {
const ROLE: Role = Role::GROUP;
const PARTS: bool = false;
const PARTS: bool = true;
const STOPS: bool = false;
const OVERLAYS: bool = false;
type Style = TitleBarStyle;
@@ -227,6 +227,13 @@ impl Component for TitleBar<'_> {
Sense::empty()
}
/// One inert part over the bar's rect. A press anywhere on the bar keeps a focused draft (the zoom field)
/// unapplied.
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
// P3(canvas-widgets-w11): cw.C65 adds `.holds_drafts()` (cw.C58) once it has a body.
cx.part(PartKey::new("title_bar"), rect).sense(Sense::empty());
}
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
let words = cx.words::<ShellWords>();
if cx.resolved.label.is_empty() {
+6
View File
@@ -30,6 +30,12 @@ craft_ui::words! {
templates: "startScreen.templates" = "Templates";
recent_menu: "startScreen.recentMenu" = "Recent file";
pinned_menu: "startScreen.pinnedMenu" = "Pinned folder";
/// The accessible name of the start screen's rail of links.
start_links: "startScreen.links" = "Links";
/// The title line of the opening card.
opening: template "openingCard.title" = "Opening {name}…";
/// The accessible name of a recent row's revealed remove part.
remove_recent: template "startScreen.removeRecent" = "Remove {name} from Recent";
/// The minimize button.
minimize: "captionButton.minimize" = "Minimize";