From 8bf05d8e46e013c51aed9f9ae0879a4808b2f4bb Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 21 Nov 2026 11:15:49 +0700 Subject: [PATCH 001/523] Contract stubs: craft-i18n, craft-host, craft-theme, craft-keymap, craft-behavior, craft-platform, craft-window --- crates/behavior/src/canvas/mod.rs | 2 +- crates/behavior/src/canvas/zoom.rs | 114 ++++++++++++++++-- crates/behavior/src/codec.rs | 9 ++ crates/behavior/src/dock/workspace.rs | 8 ++ crates/behavior/src/edit_history.rs | 20 ++- crates/behavior/src/hold_repeat.rs | 35 ++++++ crates/behavior/src/lib.rs | 8 +- crates/behavior/src/overlay.rs | 18 +++ crates/behavior/src/press.rs | 12 ++ crates/behavior/src/quantity.rs | 12 +- crates/behavior/src/wheel.rs | 10 ++ crates/behavior/tests/canvas_view.rs | 14 +-- crates/host/src/files.rs | 39 ++++++ crates/host/src/lib.rs | 2 +- crates/i18n/src/catalog.rs | 2 +- crates/i18n/src/lib.rs | 23 ++++ crates/i18n/src/message.rs | 10 ++ crates/keymap/src/chord.rs | 45 +++++-- crates/keymap/src/chord/foreign.rs | 9 ++ crates/keymap/src/import.rs | 39 +++++- crates/keymap/src/import/kys.rs | 6 +- crates/keymap/src/keymap.rs | 41 ++++++- crates/keymap/src/lib.rs | 2 +- crates/keymap/src/matcher.rs | 21 +++- crates/keymap/tests/import.rs | 2 +- crates/platform/src/open.rs | 16 +++ crates/theme/src/builtins.rs | 6 +- .../themes/vectorcraft-modern-medium.json | 71 +++++++++++ crates/theme/themes/vectorcraft-modern.json | 71 +++++++++++ crates/window/src/native_menu.rs | 16 +++ crates/window/src/system.rs | 72 +++++++++++ 31 files changed, 702 insertions(+), 53 deletions(-) create mode 100644 crates/behavior/src/hold_repeat.rs create mode 100644 crates/i18n/src/message.rs create mode 100644 crates/theme/themes/vectorcraft-modern-medium.json create mode 100644 crates/theme/themes/vectorcraft-modern.json diff --git a/crates/behavior/src/canvas/mod.rs b/crates/behavior/src/canvas/mod.rs index 9ff5c9fb3b..f53b7201d7 100644 --- a/crates/behavior/src/canvas/mod.rs +++ b/crates/behavior/src/canvas/mod.rs @@ -10,7 +10,7 @@ pub mod zoom; pub use history::{ViewHistory, ViewPlace}; pub use units::{RulerUnits, Ticks}; pub use view::{CanvasView, resize_cursor}; -pub use zoom::ZoomLadder; +pub use zoom::{ZoomFloor, ZoomLadder, ZoomScheme}; /// A canvas body's mapping from canvas coordinates to its layer: `screen = canvas * scale + offset`. #[derive(Clone, Copy, Debug, PartialEq)] diff --git a/crates/behavior/src/canvas/zoom.rs b/crates/behavior/src/canvas/zoom.rs index d4d7533303..0a9a2507e7 100644 --- a/crates/behavior/src/canvas/zoom.rs +++ b/crates/behavior/src/canvas/zoom.rs @@ -107,13 +107,109 @@ impl ZoomLadder { } } +/// The least zoom: the document's shorter side that many device pixels, or a fixed zoom in scheme units. +#[derive(Clone, Copy, Debug, PartialEq)] +#[non_exhaustive] +pub enum ZoomFloor { + /// The document's shorter side is this many device pixels. + ShorterSide(f64), + /// A fixed zoom in scheme units. + Fixed(f64), +} + +/// A zoom range and its Zoom In and Out rungs in scheme units (1 = its 100 %); `hundred` is the device zoom of +/// 100 %. +#[derive(Clone, Copy, Debug, PartialEq)] +#[non_exhaustive] +pub struct ZoomScheme { + /// The Zoom In and Out rungs, lowest first. + pub rungs: &'static [f64], + /// The greatest zoom. + pub max: f64, + /// The least zoom. + pub floor: ZoomFloor, + /// The device zoom of 100 %. + pub hundred: f64, +} + +impl ZoomScheme { + /// Photoshop's: [`ZoomLadder::STEPS`], up to 12800 %, the shorter side 2 px at the least. + pub const PHOTOSHOP: ZoomScheme = + ZoomScheme { rungs: &ZoomLadder::STEPS, max: ZoomLadder::MAX, floor: ZoomFloor::ShorterSide(2.0), hundred: 1.0 }; + + /// Illustrator's: 26 stops from 3.13 % to 64000 %. + pub const ILLUSTRATOR: ZoomScheme = ZoomScheme { + rungs: &[ + 0.0313, 0.0417, 0.0625, 0.0833, 0.125, 0.1667, 0.25, 0.3333, 0.5, 0.6667, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 8.0, 12.0, 16.0, 24.0, 32.0, + 48.0, 64.0, 128.0, 256.0, 640.0, + ], + max: 640.0, + floor: ZoomFloor::Fixed(0.0313), + hundred: 1.0, + }; + + /// The scheme with `device` as the device zoom of 100 %. + pub const fn with_hundred(self, device: f64) -> Self { + ZoomScheme { hundred: device, ..self } + } + + /// The least device zoom for a document of `size`. + pub fn min(&self, size: Size) -> f64 { + let _ = size; + todo!("cv.F1") + } + + /// The greatest device zoom. + pub fn max_device(&self) -> f64 { + todo!("cv.F1") + } + + /// `device` within the range for a document of `size`; a zoom that is not a finite number becomes 100 %. + pub fn clamp(&self, device: f64, size: Size) -> f64 { + let _ = (device, size); + todo!("cv.F1") + } + + /// Zoom In (`dir` > 0) or Zoom Out (`dir` < 0) from `device`: the next rung past it, within the document's + /// range. + pub fn step(&self, device: f64, dir: i32, size: Size) -> f64 { + let _ = (device, dir, size); + todo!("cv.F1") + } + + /// [`step`](Self::step) within an explicit range of device zoom. + pub fn step_in_range(&self, device: f64, dir: i32, range: RangeInclusive) -> f64 { + let _ = (device, dir, range); + todo!("cv.F1") + } + + /// A zoom field's range in percent: the document's range widened to include `device` itself. + pub fn percent_range(&self, device: f64, size: Size) -> RangeInclusive { + let _ = (device, size); + todo!("cv.F1") + } + + /// `device` zoom as percent of the scheme's 100 %. + pub fn percent(&self, device: f64) -> f64 { + let _ = device; + todo!("cv.F1") + } + + /// The device zoom of `percent` of the scheme's 100 %. + pub fn device(&self, percent: f64) -> f64 { + let _ = percent; + todo!("cv.F1") + } +} + /// `view.zoom` as device zoom (1 = 100 %) at `pixels_per_point`. pub fn device(view: &CanvasView, pixels_per_point: f32) -> f64 { view.zoom * f64::from(pixels_per_point) } /// `view` at `device` zoom (1 = 100 %), clamped to the zoom range of a document of `size`, with its centre kept. -pub fn with_device(view: &CanvasView, device: f64, size: Size, pixels_per_point: f32) -> CanvasView { +pub fn with_device(view: &CanvasView, device: f64, size: Size, pixels_per_point: f32, scheme: &ZoomScheme) -> CanvasView { + let _ = scheme; // P3(canvas-w1): cv.F3 let mut next = *view; next.zoom = CanvasView::points_per_unit(ZoomLadder::clamp(device, size), pixels_per_point); next @@ -132,13 +228,14 @@ fn shown_extent(view: &CanvasView, size: Size) -> (f64, f64, f64, f64) { /// each side, never past 100 % (one document pixel per device pixel, so a 150 % display does not open /// documents magnified). `size` is in document units; the view's [`aspect`](CanvasView::aspect) and rotation /// are taken into account. -pub fn fit(view: &mut CanvasView, size: Size, pixels_per_point: f32, margin: f64) { - fit_up_to(view, size, pixels_per_point, 1.0, margin); +pub fn fit(view: &mut CanvasView, size: Size, pixels_per_point: f32, margin: f64, scheme: &ZoomScheme) { + fit_up_to(view, size, pixels_per_point, 1.0, margin, scheme); } /// [`fit`] with the device zoom allowed up to `max_device` (1 = 100 %) instead of 100 %: a small document is /// magnified to fill the canvas, as Photoshop's Fit on Screen does. -pub fn fit_up_to(view: &mut CanvasView, size: Size, pixels_per_point: f32, max_device: f64, margin: f64) { +pub fn fit_up_to(view: &mut CanvasView, size: Size, pixels_per_point: f32, max_device: f64, margin: f64, scheme: &ZoomScheme) { + let _ = scheme; // P3(canvas-w1): cv.F3 fit_rect_up_to(view, Rect::from_origin_size(Point::ORIGIN, size), size, pixels_per_point, max_device, Vec2::new(margin, margin)); } @@ -146,7 +243,8 @@ pub fn fit_up_to(view: &mut CanvasView, size: Size, pixels_per_point: f32, max_d /// units, and zoom so all of it shows inside `view.rect` less `margin.x` points at the left and right and `margin.y` /// at the top and bottom, up to the zoom ceiling. /// The zoom stays inside the range of a document of `size`; an empty `rect` zooms to that ceiling about its centre. -pub fn fit_rect(view: &mut CanvasView, rect: Rect, size: Size, pixels_per_point: f32, margin: Vec2) { +pub fn fit_rect(view: &mut CanvasView, rect: Rect, size: Size, pixels_per_point: f32, margin: Vec2, scheme: &ZoomScheme) { + let _ = scheme; // P3(canvas-w1): cv.F3 fit_rect_up_to(view, rect, size, pixels_per_point, ZoomLadder::MAX, margin); } @@ -170,7 +268,8 @@ pub fn wrapped_canvas(view: &CanvasView, document: Size, canvas: ScreenRect) -> /// Fill Screen: centre the document and zoom until it covers `view.rect`; one axis may extend /// past the canvas. -pub fn fill(view: &mut CanvasView, size: Size, pixels_per_point: f32) { +pub fn fill(view: &mut CanvasView, size: Size, pixels_per_point: f32, scheme: &ZoomScheme) { + let _ = scheme; // P3(canvas-w1): cv.F3 let (shown_w, shown_h, sin, cos) = shown_extent(view, size); let (rw, rh) = (f64::from(view.rect.width()), f64::from(view.rect.height())); // The canvas rectangle's extent along the document's axes, which the document must cover. @@ -216,7 +315,8 @@ pub fn wheel_anchor(view: &CanvasView, screen: Pos2, size: Size) -> Pos2 { /// View › Zoom In (`dir` > 0) or Zoom Out (`dir` < 0): the next ladder rung /// ([`ZoomLadder::step`]), the view's centre unchanged. Returns whether the zoom changed (it does /// not at a limit). -pub fn step(view: &mut CanvasView, dir: i32, size: Size, pixels_per_point: f32) -> bool { +pub fn step(view: &mut CanvasView, dir: i32, size: Size, pixels_per_point: f32, scheme: &ZoomScheme) -> bool { + let _ = scheme; // P3(canvas-w1): cv.F3 let current = device(view, pixels_per_point); let next = ZoomLadder::step(current, dir, size); let changed = next.is_finite() && (next / current - 1.0).abs() > 1e-9; diff --git a/crates/behavior/src/codec.rs b/crates/behavior/src/codec.rs index 529f8bbf57..8ea3d5251e 100644 --- a/crates/behavior/src/codec.rs +++ b/crates/behavior/src/codec.rs @@ -62,6 +62,11 @@ pub trait Codec { true } + /// Whether a paste the codec reads whole replaces the field's text, wherever the caret is. + fn whole_paste(&self, _pasted: &str) -> bool { + false + } + /// The text the field shows after committing `v`, which was parsed from `text`. fn normalise(&self, _text: &str, v: &Self::Value) -> String { self.format(v) @@ -103,6 +108,10 @@ impl Codec for &C { (**self).filter(c) } + fn whole_paste(&self, pasted: &str) -> bool { + (**self).whole_paste(pasted) + } + fn normalise(&self, text: &str, v: &Self::Value) -> String { (**self).normalise(text, v) } diff --git a/crates/behavior/src/dock/workspace.rs b/crates/behavior/src/dock/workspace.rs index d261427ce8..0c9de875ce 100644 --- a/crates/behavior/src/dock/workspace.rs +++ b/crates/behavior/src/dock/workspace.rs @@ -89,6 +89,14 @@ impl

Workspace

{ } impl Workspace

{ + /// Renames a panel in `layout`, `hidden` and `floated` (keys and anchors), keeping its place; all or nothing, + /// and the revision stays. `MissingPanel` when `from` is in none of them, `DuplicatePanel` when `to` is + /// already there. + pub fn rename(&mut self, from: &P, to: P) -> Result<(), DockError> { + let _ = (from, to); + todo!("ch.K27") + } + /// Check the version, the layout, that every hidden panel is hidden once and absent /// from the layout, and that the floated records are bounded and one per panel. pub fn validate(&self) -> Result<(), DockError> { diff --git a/crates/behavior/src/edit_history.rs b/crates/behavior/src/edit_history.rs index 0dd299939a..c35dfb2dc9 100644 --- a/crates/behavior/src/edit_history.rs +++ b/crates/behavior/src/edit_history.rs @@ -21,6 +21,9 @@ pub enum Step { struct Entry { value: T, name: Arc, + /// The step's weight under the history's budget ([`EditHistory::with_budget`]). + #[allow(dead_code)] // P3(color-w7): co.K40 + weight: usize, } /// The gesture under way: its name, taken from its `Begin`. @@ -39,12 +42,23 @@ pub struct EditHistory { /// The value as of the latest step. settled: T, open: Option, + /// The most summed weight the undo steps keep, and how a value weighs. + #[allow(dead_code)] // P3(color-w7): co.K40 + budget: Option<(usize, fn(&T) -> usize)>, } impl EditHistory { /// A history that starts at `now`. pub fn new(now: &T) -> Self { - EditHistory { undo: Vec::new(), redo: Vec::new(), settled: now.clone(), open: None } + EditHistory { undo: Vec::new(), redo: Vec::new(), settled: now.clone(), open: None, budget: None } + } + + /// The undo steps' summed weight stays at or under `max`: after each push the oldest go first, the newest always + /// stays; each weight is measured once at push. Without a budget nothing changes. + #[must_use] + pub fn with_budget(self, max: usize, weight: fn(&T) -> usize) -> Self { + let _ = (max, weight); + todo!("co.K40") } /// Takes in one event. Events of a gesture other than the open one are ignored. @@ -81,7 +95,7 @@ impl EditHistory { if self.undo.len() >= LIMIT { self.undo.remove(0); } - self.undo.push(Entry { value: std::mem::replace(&mut self.settled, after.clone()), name }); + self.undo.push(Entry { value: std::mem::replace(&mut self.settled, after.clone()), name, weight: 0 }); // P3(color-w7): co.K40 self.redo.clear(); } @@ -93,7 +107,7 @@ impl EditHistory { Step::Redo => (&mut self.redo, &mut self.undo), }; let Some(entry) = from.pop() else { return false }; - to.push(Entry { value: std::mem::replace(now, entry.value.clone()), name: entry.name }); + to.push(Entry { value: std::mem::replace(now, entry.value.clone()), name: entry.name, weight: entry.weight }); self.settled = entry.value; true } diff --git a/crates/behavior/src/hold_repeat.rs b/crates/behavior/src/hold_repeat.rs new file mode 100644 index 0000000000..6436f62253 --- /dev/null +++ b/crates/behavior/src/hold_repeat.rs @@ -0,0 +1,35 @@ +//! Steps due while a press is held, as a spinner button repeats. + +/// Seconds a press is held before the steps repeat. +pub const DELAY: f64 = 0.4; + +/// Seconds between repeated steps. +pub const INTERVAL: f64 = 0.05; + +/// Steps due while a press is held, from the pass's elapsed time (zero on later passes of a frame, so a rerun steps +/// nothing). A different concept from `HoldZoom`, which zooms continuously at a rate. +#[derive(Clone, Copy, Debug, Default)] +pub struct HoldRepeat { + #[allow(dead_code)] // P3(widgets-w2): wg.W35 + held_for: f64, + #[allow(dead_code)] // P3(widgets-w2): wg.W35 + fired: u32, +} + +impl HoldRepeat { + /// Starts a press: the one step due now. + pub fn press(&mut self) -> u32 { + todo!("wg.W35") + } + + /// The steps due after `elapsed` more seconds of the press. + pub fn hold(&mut self, elapsed: f64) -> u32 { + let _ = elapsed; + todo!("wg.W35") + } + + /// Ends the press. + pub fn release(&mut self) { + todo!("wg.W35") + } +} diff --git a/crates/behavior/src/lib.rs b/crates/behavior/src/lib.rs index 7ad5665c77..145790506d 100644 --- a/crates/behavior/src/lib.rs +++ b/crates/behavior/src/lib.rs @@ -25,6 +25,7 @@ pub mod flow; pub mod focus; pub mod grid; pub mod hit; +pub mod hold_repeat; pub mod input; pub mod intent; pub mod item_layout; @@ -64,7 +65,7 @@ pub use anchor::Anchor9; pub use arrangement::Arrangement; pub use canvas::CanvasTransform; -pub use canvas::{CanvasView, RulerUnits, Ticks, ViewHistory, ViewPlace, ZoomLadder, resize_cursor}; +pub use canvas::{CanvasView, RulerUnits, Ticks, ViewHistory, ViewPlace, ZoomFloor, ZoomLadder, ZoomScheme, resize_cursor}; /// The f64 geometry crate the canvas view and its callers share. pub use kurbo; @@ -96,9 +97,10 @@ pub use part::{PartKey, PartRef}; pub use pixel_size::PixelSize; +pub use hold_repeat::HoldRepeat; pub use press::{ - Buttons, MultiTouch, PassInput, PointerButton, PointerEvent, PointerKind, PointerSample, PressCancel, PressMachine, PressPhase, PressStart, - PressState, PressStep, count_clicks, + Buttons, MultiTap, MultiTouch, PassInput, PointerButton, PointerEvent, PointerKind, PointerSample, PressCancel, PressMachine, PressPhase, + PressStart, PressState, PressStep, count_clicks, }; pub use quantity::Reader; pub use role_rule::{GridFacts, RoleRule, is_checkable, is_selectable, role_violations}; diff --git a/crates/behavior/src/overlay.rs b/crates/behavior/src/overlay.rs index 84b75ee028..621de8fddd 100644 --- a/crates/behavior/src/overlay.rs +++ b/crates/behavior/src/overlay.rs @@ -97,6 +97,10 @@ pub struct PlaceRequest { /// Beside the anchor, the overlay lines up with the anchor's other end when it runs past the bounds from the /// aligned end and fits from the other, instead of sliding: a submenu of a low row opens upward. pub flips_across: bool, + /// After side, alignment and the bounds clamp, the overlay shifts by this and clamps again. + pub offset: Vec2, + /// When the shifted overlay would cover this rect, the unshifted one wins. + pub clear: Option, } impl PlaceRequest { @@ -113,6 +117,8 @@ impl PlaceRequest { bounds, kept: None, flips_across: false, + offset: Vec2::ZERO, + clear: None, } } @@ -158,6 +164,18 @@ impl PlaceRequest { self } + /// Shifts the overlay by `by` after it is placed and clamped. + pub const fn offset(mut self, by: Vec2) -> Self { + self.offset = by; + self + } + + /// Keeps the unshifted place when the shifted overlay would cover `rect`. + pub const fn clear(mut self, rect: Option) -> Self { + self.clear = rect; + self + } + /// Lines up with the anchor's other end, beside it, when that fits and the aligned end does not. pub const fn flips_across(mut self, on: bool) -> Self { self.flips_across = on; diff --git a/crates/behavior/src/press.rs b/crates/behavior/src/press.rs index ba4a4d7f30..9642a4c566 100644 --- a/crates/behavior/src/press.rs +++ b/crates/behavior/src/press.rs @@ -157,6 +157,18 @@ pub enum PressCancel { Removed, /// The host ended what the press acted on (`primitives::cancel_press_of`). Host, + /// A second finger landed while a press was open. + Gesture, +} + +/// Two or more fingers came down and all lifted within the tap time without moving past the slop. +#[derive(Clone, Copy, Debug, PartialEq)] +#[non_exhaustive] +pub struct MultiTap { + /// How many fingers tapped. + pub fingers: u8, + /// The centre of the fingers. + pub at: Pos2, } /// One part's press state in one pass. diff --git a/crates/behavior/src/quantity.rs b/crates/behavior/src/quantity.rs index b424c342cb..f4b5800272 100644 --- a/crates/behavior/src/quantity.rs +++ b/crates/behavior/src/quantity.rs @@ -41,11 +41,14 @@ pub struct Reader { decimal: char, group: Option, units: Vec, + /// The factor of a number with no unit ([`Reader::bare`]). + #[allow(dead_code)] // P3(widgets-w7): wg.W37 + bare: f64, } impl Default for Reader { fn default() -> Self { - Reader { decimal: '.', group: None, units: Vec::new() } + Reader { decimal: '.', group: None, units: Vec::new(), bare: 1.0 } } } @@ -55,6 +58,13 @@ impl Reader { Self::default() } + /// A number with no unit counts as `factor` of the reader's base unit. + #[must_use] + pub fn bare(self, factor: f64) -> Self { + let _ = factor; + todo!("wg.W37") + } + /// The decimal separator. #[must_use] pub fn decimal(mut self, decimal: char) -> Self { diff --git a/crates/behavior/src/wheel.rs b/crates/behavior/src/wheel.rs index 625f684bbd..4c7af4925e 100644 --- a/crates/behavior/src/wheel.rs +++ b/crates/behavior/src/wheel.rs @@ -86,6 +86,8 @@ pub struct Wheel { pub rotation: f32, /// Rotation of a two-finger touch, in radians. pub touch_rotation: f32, + /// Two fingers' movement this pass, in points. + pub touch_pan: Vec2, } impl Wheel { @@ -104,6 +106,7 @@ impl Wheel { touch_zoom: 1.0, rotation: 0.0, touch_rotation: 0.0, + touch_pan: Vec2::ZERO, } } @@ -131,6 +134,13 @@ impl Wheel { self } + /// The same gesture with the two-finger touch movement `pan`, in points. + #[must_use] + pub fn touch_pan(self, pan: Vec2) -> Self { + let _ = pan; + todo!("cv.F15") + } + /// The same gesture from `source`. pub const fn source(mut self, source: WheelSource) -> Self { self.source = source; diff --git a/crates/behavior/tests/canvas_view.rs b/crates/behavior/tests/canvas_view.rs index 2da0b59c99..e5e161a2da 100644 --- a/crates/behavior/tests/canvas_view.rs +++ b/crates/behavior/tests/canvas_view.rs @@ -1,7 +1,7 @@ //! The canvas view's mapping between document and screen. use craft_behavior::CanvasView; -use craft_behavior::canvas::zoom; +use craft_behavior::canvas::{ZoomScheme, zoom}; use emath::{Rect as ScreenRect, pos2, vec2}; use kurbo::{Point, Rect, Size}; @@ -55,21 +55,21 @@ fn fit_and_fill_measure_the_stretched_document() { // Fit keeps 20 points of margin per side: 1000 points across for a 1000 px wide document, 2000 shown at aspect 2. let (mut square, mut wide) = (stage(1.0, rect(1040.0, 800.0)), stage(2.0, rect(1040.0, 800.0))); - zoom::fit(&mut square, size, 1.0, 20.0); - zoom::fit(&mut wide, size, 1.0, 20.0); + zoom::fit(&mut square, size, 1.0, 20.0, &ZoomScheme::PHOTOSHOP); // P3(canvas-w1): cv.F3 + zoom::fit(&mut wide, size, 1.0, 20.0, &ZoomScheme::PHOTOSHOP); // P3(canvas-w1): cv.F3 assert!(near(square.zoom, 1.0), "{}", square.zoom); assert!(near(wide.zoom, 0.5), "{}", wide.zoom); assert!(near(wide.center.x, 500.0) && near(wide.center.y, 250.0), "{:?}", wide.center); // On a square rect the height limits fill at both aspects; the 1000 by 400 rect below is where the stretched width decides. let (mut square, mut wide) = (stage(1.0, rect(1000.0, 1000.0)), stage(2.0, rect(1000.0, 1000.0))); - zoom::fill(&mut square, size, 1.0); - zoom::fill(&mut wide, size, 1.0); + zoom::fill(&mut square, size, 1.0, &ZoomScheme::PHOTOSHOP); // P3(canvas-w1): cv.F3 + zoom::fill(&mut wide, size, 1.0, &ZoomScheme::PHOTOSHOP); // P3(canvas-w1): cv.F3 assert!(near(square.zoom, 2.0) && near(wide.zoom, 2.0), "{} {}", square.zoom, wide.zoom); // A wide rect: the unstretched document is limited by its width, the stretched one by its height. let (mut square, mut wide) = (stage(1.0, rect(1000.0, 400.0)), stage(2.0, rect(1000.0, 400.0))); - zoom::fill(&mut square, size, 1.0); - zoom::fill(&mut wide, size, 1.0); + zoom::fill(&mut square, size, 1.0, &ZoomScheme::PHOTOSHOP); // P3(canvas-w1): cv.F3 + zoom::fill(&mut wide, size, 1.0, &ZoomScheme::PHOTOSHOP); // P3(canvas-w1): cv.F3 assert!(near(square.zoom, 1.0), "{}", square.zoom); assert!(near(wide.zoom, 0.8), "{}", wide.zoom); assert!(near(wide.center.x, 500.0) && near(wide.center.y, 250.0), "{:?}", wide.center); diff --git a/crates/host/src/files.rs b/crates/host/src/files.rs index 4dce84d993..a438915acf 100644 --- a/crates/host/src/files.rs +++ b/crates/host/src/files.rs @@ -153,6 +153,14 @@ pub enum Picked { /// One or more paths. For [`PickKind::Save`] the extension policy has been applied, and the /// service has already asked about replacing an existing file the OS panel did not check. Paths(Vec), + /// Every [`PickKind::Save`] answer. `file_type` is the index into the request's `filters` of the + /// type picked in the panel, when the panel reports one. + Saved { + /// The path chosen. + path: PathBuf, + /// The index of the picked type in the request's `filters`. + file_type: Option, + }, /// Files read by the browser (wasm): name and contents. Contents(Vec<(String, Vec)>), /// No picker could be shown (no desktop portal or `zenity` on Linux, no window to attach to); @@ -166,6 +174,7 @@ impl Picked { pub fn first_path(&self) -> Option { match self { Picked::Paths(paths) => paths.first().cloned(), + Picked::Saved { path, .. } => Some(path.clone()), Picked::Contents(files) => files.first().map(|(name, _)| PathBuf::from(name)), Picked::Cancelled | Picked::Unavailable(_) => None, } @@ -175,12 +184,22 @@ impl Picked { pub fn paths(&self) -> Vec { match self { Picked::Paths(paths) => paths.clone(), + Picked::Saved { path, .. } => vec![path.clone()], Picked::Contents(files) => files.iter().map(|(name, _)| PathBuf::from(name)).collect(), Picked::Cancelled | Picked::Unavailable(_) => Vec::new(), } } } +/// A pick that is on screen or waiting. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PendingPick { + /// The request. + pub request: PickRequest, + /// Whether the panel is attached to the app window (macOS Save), so the window must not close. + pub sheet: bool, +} + /// One answered pick. #[derive(Clone, Debug, PartialEq, Eq)] pub struct PickAnswer { @@ -243,6 +262,9 @@ pub trait Files: Send + Sync { fn forget(&self, id: PickId); /// Whether a picker is on screen or waiting. fn pick_pending(&self) -> bool; + /// The oldest pick not yet answered (the one on screen), including one waiting on the service's + /// Replace question; `None` when none. + fn pending_pick(&self) -> Option; /// Reads the whole file at `path`. fn read(&self, path: &Path) -> Result, FileError>; /// Writes atomically where the platform allows (temp file and rename). @@ -282,6 +304,10 @@ impl Files for NoPickFiles { false } + fn pending_pick(&self) -> Option { + None + } + #[cfg(not(target_arch = "wasm32"))] fn read(&self, path: &Path) -> Result, FileError> { std::fs::read(path).map_err(|e| with_path(e, path)) @@ -332,6 +358,9 @@ struct ScriptState { held: bool, /// A Save is answered with the suggested name in the suggested folder. save_suggested: bool, + /// Picks report `sheet: true` in [`PendingPick`]. + #[allow(dead_code)] // P3(files-w1): fl.F4 + sheets: bool, /// Picks the test has not answered yet, oldest first. open: Vec<(PickId, PickRequest)>, answered: Vec, @@ -367,6 +396,12 @@ impl ScriptedFiles { self } + /// Scripted picks report `sheet: on`. + pub fn sheets(self, on: bool) -> Self { + let _ = on; + todo!("fl.F4") + } + /// Puts a file in memory, for [`Files::read`]. pub fn with_file(self, path: impl Into, bytes: impl Into>) -> Self { self.state().files.insert(path.into(), bytes.into()); @@ -453,6 +488,10 @@ impl Files for ScriptedFiles { !self.state().open.is_empty() } + fn pending_pick(&self) -> Option { + todo!("fl.F2") + } + fn read(&self, path: &Path) -> Result, FileError> { self.file(path).ok_or_else(|| FileError::NotFound(path.to_owned())) } diff --git a/crates/host/src/lib.rs b/crates/host/src/lib.rs index f3b5a8d537..df4b2aa335 100644 --- a/crates/host/src/lib.rs +++ b/crates/host/src/lib.rs @@ -12,7 +12,7 @@ use std::sync::Arc; use craft_i18n::{I18n, Lang}; -pub use files::{FileError, FileFilter, Files, NoPickFiles, PickAnswer, PickId, PickKind, PickRequest, Picked, ScriptedFiles}; +pub use files::{FileError, FileFilter, Files, NoPickFiles, PendingPick, PickAnswer, PickId, PickKind, PickRequest, Picked, ScriptedFiles}; #[cfg(not(target_arch = "wasm32"))] pub use services::ThreadJobs; pub use services::{AppInfo, Commands, InlineJobs, Jobs, ManualJobs, MemorySections, NoCommands, Section, SectionStore, Wake}; diff --git a/crates/i18n/src/catalog.rs b/crates/i18n/src/catalog.rs index 0cb51e36c3..3d27adadb6 100644 --- a/crates/i18n/src/catalog.rs +++ b/crates/i18n/src/catalog.rs @@ -12,7 +12,7 @@ pub(crate) struct Entry { } /// The contexts with a meaning here. Any other context starting with `@` is skipped. -const RESERVED: &[&str] = &["@plural", "@id", "@msg"]; +const RESERVED: &[&str] = &["@plural", "@id", "@msg", "@msgplural"]; /// The rows of a catalog whose locale has `forms` plural forms, and one problem (`line N: …`) per /// row skipped. Of a row defined twice, the first is kept, as in craft-i18n's checker. diff --git a/crates/i18n/src/lib.rs b/crates/i18n/src/lib.rs index 4729b11389..dec3ada636 100644 --- a/crates/i18n/src/lib.rs +++ b/crates/i18n/src/lib.rs @@ -19,6 +19,7 @@ mod date; mod fold; mod format; pub mod matcher; +mod message; mod number; mod region; mod scripts; @@ -34,6 +35,7 @@ use negotiation::posix_env_tags; use negotiation::{bare, candidates, is_region, marked, plural_rules}; pub use bidi::{isolate, ltr, strip_isolates}; +pub use message::MessageMatch; /// The CLDR number, plural and date data for every CLDR locale, from `data/generate.sh`. mod data { @@ -299,6 +301,27 @@ impl I18n { self.find(lang, &[("@id", id), ("", label)]).unwrap_or(label) } + /// Translates a filled-in English message. An exact `@msg` row wins; otherwise the first matching + /// template, by the order of the contract's template ranking, with the plural form from `{n}`. + pub fn message(&self, lang: Lang, s: &str) -> String { + let _ = (lang, s); + todo!("sh.K15") + } + + /// As [`I18n::message`], with an app hook that sees each captured value (`key`, `value`) before + /// the default rule. + pub fn message_with(&self, lang: Lang, s: &str, values: &dyn Fn(&MessageMatch<'_>, &str, &str) -> Option) -> String { + let _ = (lang, s, values); + todo!("sh.K16") + } + + /// Translates a message around a kept span (placeholder U+FFFC). The message is shown in English + /// when the placeholder does not appear exactly once. + pub fn message_keeping(&self, lang: Lang, before: &str, kept: &str, after: &str) -> String { + let _ = (lang, before, kept, after); + todo!("sh.K18") + } + /// A count's wording in `lang`, `{n}` filled in as [`I18n::format`] writes numbers: grouped and /// in the region's digits, as a left-to-right isolate ([`ltr`]) when the wording has a /// right-to-left letter. `one` and `other` are the English forms; they are also the key of the diff --git a/crates/i18n/src/message.rs b/crates/i18n/src/message.rs new file mode 100644 index 0000000000..a72ca9a143 --- /dev/null +++ b/crates/i18n/src/message.rs @@ -0,0 +1,10 @@ +//! Matching a filled-in English message against `@msg` and `@msgplural` templates. + +/// What a [`crate::I18n::message_with`] hook sees of the matched template. +#[derive(Clone, Copy, Debug)] +pub struct MessageMatch<'a> { + /// The English template that matched. + pub english: &'a str, + /// The captured values, as (key, value) pairs. + pub captures: &'a [(&'a str, &'a str)], +} diff --git a/crates/keymap/src/chord.rs b/crates/keymap/src/chord.rs index 86c410798c..69c28132aa 100644 --- a/crates/keymap/src/chord.rs +++ b/crates/keymap/src/chord.rs @@ -730,24 +730,51 @@ impl<'de> Deserialize<'de> for Chord { } } -/// What starts a command: a chord, pressed once or twice in a row. +/// How a chord starts a command. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum Press { + /// One press of the chord. + #[default] + Single, + /// Two presses of the chord in a row. + Double, + /// The chord held down. + Hold, +} + +/// What starts a command: a chord, pressed once, twice in a row, or held. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct Trigger { /// The chord to press. pub chord: Chord, - /// The chord pressed twice. - pub double: bool, + /// How the chord is pressed. + pub press: Press, } impl Trigger { /// A trigger that fires on one press of `chord`. pub const fn single(chord: Chord) -> Trigger { - Trigger { chord, double: false } + Trigger { chord, press: Press::Single } } /// A trigger that fires on two presses of `chord` in a row. pub const fn double(chord: Chord) -> Trigger { - Trigger { chord, double: true } + Trigger { chord, press: Press::Double } + } + + /// A trigger that fires while `chord` is held. + pub const fn hold(chord: Chord) -> Trigger { + Trigger { chord, press: Press::Hold } + } + + /// Whether this is a double press. + pub const fn is_double(&self) -> bool { + matches!(self.press, Press::Double) + } + + /// Whether this is a hold. + pub const fn is_hold(&self) -> bool { + matches!(self.press, Press::Hold) } /// Reads a chord as [`Chord::parse`] does, or the same chord twice separated by whitespace @@ -777,19 +804,19 @@ impl Trigger { /// The trigger with its chord's modifiers as `platform` sees them ([`Mods::effective`]). pub const fn effective(self, platform: Platform) -> Trigger { - Trigger { chord: self.chord.effective(platform), double: self.double } + Trigger { chord: self.chord.effective(platform), press: self.press } } /// [`Chord::display`], twice with a space between for a double press. pub fn display(&self, platform: Platform) -> String { let one = self.chord.display(platform); - if self.double { format!("{one} {one}") } else { one } + if self.is_double() { format!("{one} {one}") } else { one } // P3(shortcuts-w3): kb.C13b } /// [`Chord::display_for`], twice with a space between for a double press. pub fn display_for(&self, platform: Platform, layout: &Layout) -> String { let one = self.chord.display_for(platform, layout); - if self.double { format!("{one} {one}") } else { one } + if self.is_double() { format!("{one} {one}") } else { one } // P3(shortcuts-w3): kb.C13b } } @@ -801,7 +828,7 @@ impl From for Trigger { impl fmt::Display for Trigger { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - if self.double { write!(f, "{0} {0}", self.chord) } else { write!(f, "{}", self.chord) } + if self.is_double() { write!(f, "{0} {0}", self.chord) } else { write!(f, "{}", self.chord) } // P3(shortcuts-w3): kb.C13b } } diff --git a/crates/keymap/src/chord/foreign.rs b/crates/keymap/src/chord/foreign.rs index 0961170b62..512054c136 100644 --- a/crates/keymap/src/chord/foreign.rs +++ b/crates/keymap/src/chord/foreign.rs @@ -58,6 +58,14 @@ pub enum ForeignError { UnknownKey(String), /// A modifier with no counterpart here, such as the Windows key. UnsupportedModifier(String), + /// A key whose key code (`key`) or modifier code (`mods`) the reader leaves undecided; the decided + /// half is `None`. + Undecided { + /// The key code, when decided. + key: Option, + /// The modifier code, when decided. + mods: Option, + }, } impl std::fmt::Display for ForeignError { @@ -67,6 +75,7 @@ impl std::fmt::Display for ForeignError { ForeignError::TooLong => write!(f, "shortcut longer than {MAX_CHORD_TEXT} bytes"), ForeignError::UnknownKey(k) => write!(f, "unknown key `{k}`"), ForeignError::UnsupportedModifier(m) => write!(f, "unsupported modifier `{m}`"), + ForeignError::Undecided { .. } => f.write_str("undecided key code"), } } } diff --git a/crates/keymap/src/import.rs b/crates/keymap/src/import.rs index 66bb172d08..b05bd400aa 100644 --- a/crates/keymap/src/import.rs +++ b/crates/keymap/src/import.rs @@ -163,6 +163,13 @@ impl ForeignKey { }; ForeignKey { context: context.map(str::to_string), text: text.to_string(), trigger, notes } } + + /// A key whose key or modifier code the reader leaves undecided: `trigger` is + /// `Err(ForeignError::Undecided { key, mods })`, `text` is kept for reports. + pub fn code(context: Option<&str>, text: &str, key: Option, mods: Option) -> ForeignKey { + let _ = (context, text, key, mods); + todo!("kb.C19a") + } } /// What keys in a source context become. @@ -210,8 +217,13 @@ pub struct ImportOptions { /// Source contexts by name, compared case-insensitively. Keys in other contexts are reported /// as [`UnmatchedReason::Context`]. pub contexts: Vec<(String, ContextRule)>, - /// Earlier answers of the user, by [`ForeignEntry::remember_key`]. They are tried first. - pub remembered: BTreeMap, + /// Earlier answers of the user, by [`ForeignEntry::remember_key`]. `Some(command)` is tried first; + /// `None` is the user's "No equivalent": the entry is matched to nothing and goes to the report's + /// skipped list. + pub remembered: BTreeMap>, + /// Remembered and answered codes, by `key:N` / `mods:N`: `Some(text)` is the chord text the code + /// stands for, `None` is "No equivalent" (the keys with that code are skipped). + pub codes: BTreeMap>, /// What the import starts from. pub start: Start, /// What an entry without keys does to its command. @@ -507,6 +519,25 @@ pub struct ImportReport { /// Entries, keys, path segments, bindings and text fields cut at the caps, unmatched entries /// past [`MAX_SUGGESTIONS`] that got no suggestion, and [`ForeignSet::truncated`]. pub truncated: usize, + /// Undecided key and modifier codes the plan decoded or was answered, with the first entries that + /// use each. + #[serde(default)] + pub codes: Vec, +} + +/// An undecided key or modifier code of the source and what the plan made of it: decoded when at +/// least 2 matched commands' defaults vote for one text and 4 in 5 agree, or answered by +/// [`ImportOptions::codes`]. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[non_exhaustive] +pub struct DecodedCode { + /// The code, as `key:N` or `mods:N`. + pub code: String, + /// The chord text the code stands for; `None` when answered "No equivalent". + pub text: Option, + /// The first 3 entry names that use the code. + pub entries: Vec, } /// The matching form of a label or menu name: lower case, no `…`, `...` or `&`, a colon read as @@ -1109,8 +1140,8 @@ impl Index { /// on the names as written, then on toggle commands with the entry's label and theirs /// without a leading Show/Hide. A panel-menu entry's last segment alone matches only when /// its first segment, the panel, is a segment of some catalog path. - fn find(&self, entry: &ForeignEntry, tool: bool, remembered: &BTreeMap) -> Found { - if let Some(c) = remembered.get(&entry.remember_key()) + fn find(&self, entry: &ForeignEntry, tool: bool, remembered: &BTreeMap>) -> Found { + if let Some(c) = remembered.get(&entry.remember_key()).and_then(Option::as_ref) // P3(shortcuts-w3): kb.C28 && let Some(&i) = self.keys.get(&c.key()) && self.tool.get(i) == Some(&tool) { diff --git a/crates/keymap/src/import/kys.rs b/crates/keymap/src/import/kys.rs index 7884a2e71a..ee1606254d 100644 --- a/crates/keymap/src/import/kys.rs +++ b/crates/keymap/src/import/kys.rs @@ -177,7 +177,8 @@ pub fn read(text: &str) -> Result { let mut key = ForeignKey::read(None, key, flavor); // Photoshop's tool shortcuts are single keys: one with modifiers is reported as // unreadable and binds nothing, and the tool keeps the key it has. - if row.tool && key.trigger.as_ref().is_ok_and(|t| !t.chord.mods.is_none() || t.double) { + // P3(shortcuts-w3): kb.C13b + if row.tool && key.trigger.as_ref().is_ok_and(|t| !t.chord.mods.is_none() || t.is_double()) { key.trigger = Err(ForeignError::UnsupportedModifier(key.text.clone())); } entry = entry.with_key(key); @@ -226,7 +227,8 @@ pub fn write(name: &str, keymap: &Keymap) -> String { for tools in [false, true] { for b in keymap.catalog().iter().filter(|b| matches!(b.kind, CommandKind::Tool { .. }) == tools) { let keys: Vec = - keymap.bindings(&b.command).iter().filter(|k| k.scope.is_none() && !k.trigger.double).map(|k| photoshop_key(&k.trigger)).collect(); + // P3(shortcuts-w3): kb.C13b + keymap.bindings(&b.command).iter().filter(|k| k.scope.is_none() && !k.trigger.is_double()).map(|k| photoshop_key(&k.trigger)).collect(); let Some(first) = keys.first() else { continue }; let label = escape(&b.label.replace('…', "...")); let id = escape(&b.command.key()); diff --git a/crates/keymap/src/keymap.rs b/crates/keymap/src/keymap.rs index 47ef3320c5..1e64075fe2 100644 --- a/crates/keymap/src/keymap.rs +++ b/crates/keymap/src/keymap.rs @@ -7,7 +7,7 @@ use std::fmt; use serde::{Deserialize, Serialize}; -use crate::chord::{Chord, Key, Mods, ParseError, Platform, Trigger}; +use crate::chord::{Chord, Key, Mods, ParseError, Platform, Press, Trigger}; use crate::command::{CommandRef, MAX_KEY}; use crate::scope::{Active, Scope, ScopeKind, Scopes}; @@ -102,6 +102,8 @@ pub enum AssignError { UnknownScope(Scope), /// The change needs a new [`Overrides`] entry and it already holds [`MAX_COMMANDS`]. Full, + /// A hold is a chord that types a character, alone or with Shift: never Space, Backtick, Cmd, Ctrl or Alt. + NotHoldable(Trigger), } impl fmt::Display for AssignError { @@ -113,6 +115,7 @@ impl fmt::Display for AssignError { AssignError::Taken(h) => write!(f, "in use by {} other command(s)", h.len()), AssignError::UnknownScope(s) => write!(f, "unknown scope {s}"), AssignError::Full => write!(f, "more than {MAX_COMMANDS} changed commands"), + AssignError::NotHoldable(t) => write!(f, "{t} cannot be held"), } } } @@ -261,6 +264,9 @@ pub struct Keymap { overrides: Overrides, /// Tools of different groups may share a chord ([`Keymap::with_shared_tool_keys`]). pub(crate) shared_tool_keys: bool, + /// Whether hold bindings count ([`Keymap::set_holds`]). + #[allow(dead_code)] // P3(shortcuts-w3): kb.C13c + holds: bool, } impl Keymap { @@ -285,6 +291,7 @@ impl Keymap { reserved: Vec::new(), overrides: Overrides::new(), shared_tool_keys: false, + holds: false, }; for b in catalog { let key = b.command.key(); @@ -383,6 +390,24 @@ impl Keymap { scope.is_app() || self.scopes.knows(scope) || self.catalog_scopes.contains(scope) } + /// Whether hold bindings count: off (the default) leaves them out of bindings, lookups, conflicts and + /// summaries, though they stay in the overrides. + pub fn set_holds(&mut self, on: bool) { + let _ = on; + todo!("kb.C13c") + } + + /// Whether hold bindings count ([`Keymap::set_holds`]). + pub fn holds(&self) -> bool { + todo!("kb.C13c") + } + + /// The command a hold of `chord` runs where it applies, ranked as the other lookups rank. + pub fn hold_of(&self, chord: &Chord, active: &Active<'_>) -> Option { + let _ = (chord, active); + todo!("kb.C13e") + } + /// The command `chord` (pressed twice when `double`) runs with `active` focus. pub fn lookup(&self, chord: &Chord, double: bool, active: &Active) -> Lookup { self.lookup_nested(chord, double, active, &[]) @@ -391,7 +416,12 @@ impl Keymap { /// [`lookup`](Self::lookup) with the panels around the focused one in `outer` ([`Scopes::rank_nested`]). pub fn lookup_nested(&self, chord: &Chord, double: bool, active: &Active, outer: &[&str]) -> Lookup { let command = |i: usize| self.catalog[i].command.clone(); - match self.winners(Trigger { chord: chord.effective(self.platform), double }, active, outer) { + // P3(shortcuts-w3): kb.C13b + match self.winners( + Trigger { chord: chord.effective(self.platform), press: if double { Press::Double } else { Press::Single } }, + active, + outer, + ) { Winners::None => Lookup::None, Winners::Run(i) => Lookup::Run(command(i)), Winners::Cycle(cycle) => Lookup::Cycle(cycle.into_iter().map(command).collect()), @@ -449,7 +479,7 @@ impl Keymap { /// [`shown_chord`](Self::shown_chord) of the command at catalog position `i`, from the bindings. fn shown_of(&self, i: usize) -> Option { let home = &self.catalog[i].scope; - let single = || self.current[i].iter().filter(|(trigger, _)| !trigger.double); + let single = || self.current[i].iter().filter(|(trigger, _)| !trigger.is_double()); // P3(shortcuts-w3): kb.C13b let runs = |(trigger, scope): &&Bound| { let name = [scope.as_str()]; let active = match self.scopes.kind(scope) { @@ -457,7 +487,8 @@ impl Keymap { ScopeKind::Panel => Active::panel(name[0]), ScopeKind::Context => Active { panel: None, contexts: &name, typing: false }, }; - match self.winners(Trigger { chord: trigger.chord.effective(self.platform), double: false }, &active, &[]) { + // P3(shortcuts-w3): kb.C13b + match self.winners(Trigger { chord: trigger.chord.effective(self.platform), press: Press::Single }, &active, &[]) { Winners::None => false, Winners::Run(j) => j == i, Winners::Cycle(cycle) => cycle.contains(&i), @@ -481,7 +512,7 @@ impl Keymap { Lookup::Cycle(cycle) => return cycle.into_iter().next(), Lookup::None => {} } - let want = Trigger { chord: chord.effective(self.platform), double: false }; + let want = Trigger { chord: chord.effective(self.platform), press: Press::Single }; // P3(shortcuts-w3): kb.C13b self.by_trigger.get(&want)?.iter().find(|&&(i, k)| self.at(i, k).is_some()).map(|&(i, _)| self.catalog[i].command.clone()) } diff --git a/crates/keymap/src/lib.rs b/crates/keymap/src/lib.rs index c74faf64f1..7e59b55e0d 100644 --- a/crates/keymap/src/lib.rs +++ b/crates/keymap/src/lib.rs @@ -154,7 +154,7 @@ pub use chord::{Chord, Key, MAX_CHORD_TEXT, Mods, ParseError, Platform, Trigger} pub use command::{CommandRef, MAX_KEY}; pub use commands::KeymapCommands; pub use editor::{DOUBLE_PRESS, EditSession, MAX_UNDO, MAX_UNDO_BYTES, Recorded, Recorder}; -pub use import::{ContextRule, ForeignEntry, ForeignKey, ForeignSet, ImportOptions, ImportPlan, ImportReport, NoneDefined, Start, plan}; +pub use import::{ContextRule, DecodedCode, ForeignEntry, ForeignKey, ForeignSet, ImportOptions, ImportPlan, ImportReport, NoneDefined, Start, plan}; pub use keymap::{ AssignError, Assigned, Binding, BindingError, CommandDef, CommandKind, Conflict, ConflictKind, DropReason, Holder, Keymap, Lookup, MAX_BINDING_TEXT, MAX_BINDINGS, MAX_COMMANDS, MAX_CONFLICTS, ModalRule, Overrides, Policy, Problem, TypingRule, text_editing_chords, diff --git a/crates/keymap/src/matcher.rs b/crates/keymap/src/matcher.rs index bb303132c9..10cd54cc3c 100644 --- a/crates/keymap/src/matcher.rs +++ b/crates/keymap/src/matcher.rs @@ -2,7 +2,7 @@ //! Alt variant. It reads no toolkit's events; craft-ui's key stage runs it. use crate::DOUBLE_PRESS; -use crate::chord::{Chord, Key, Mods, Trigger}; +use crate::chord::{Chord, Key, Mods, Press as PressKind, Trigger}; use crate::command::CommandRef; use crate::keymap::{Keymap, Lookup}; use crate::layout::{KeyInput, Layout}; @@ -130,9 +130,13 @@ impl Chords { /// The first chord with a binding, pressed twice when `double`. fn find(&self, keymap: &Keymap, double: bool, active: &Active<'_>, outer: &[&str]) -> Option { let first = self.first(); - self.0 - .iter() - .find_map(|&chord| Hit::from_lookup(keymap.lookup_nested(&chord, double, active, outer), Trigger { chord, double }, chord == first)) + self.0.iter().find_map(|&chord| { + Hit::from_lookup( + keymap.lookup_nested(&chord, double, active, outer), + Trigger { chord, press: if double { PressKind::Double } else { PressKind::Single } }, + chord == first, + ) + }) // P3(shortcuts-w3): kb.C13b } /// The single press's binding, else its Alt variant. @@ -150,7 +154,14 @@ impl Chords { let plain = Chord::new(Mods { alt: false, ..chord.mods }, chord.key); match keymap.lookup_nested(&plain, false, &Active { typing: false, ..*active }, outer) { Lookup::Run(command) if keymap.bindable(&command).is_some_and(|b| b.has_alt_variant) => { - Some(Hit { command, cycle: Vec::new(), trigger: Trigger { chord, double: false }, exact: chord == first, alt_variant: true }) + // P3(shortcuts-w3): kb.C13b + Some(Hit { + command, + cycle: Vec::new(), + trigger: Trigger { chord, press: PressKind::Single }, + exact: chord == first, + alt_variant: true, + }) } _ => None, } diff --git a/crates/keymap/tests/import.rs b/crates/keymap/tests/import.rs index 6aaa67047e..59d02881ba 100644 --- a/crates/keymap/tests/import.rs +++ b/crates/keymap/tests/import.rs @@ -111,7 +111,7 @@ fn windows_set() -> ForeignSet { fn windows_options() -> ImportOptions { let mut remembered = BTreeMap::new(); - remembered.insert(ForeignEntry::new(Some("Scripts"), ["Frobnicate"]).remember_key(), CommandRef::new("scripts.run")); + remembered.insert(ForeignEntry::new(Some("Scripts"), ["Frobnicate"]).remember_key(), Some(CommandRef::new("scripts.run"))); // P3(shortcuts-w3): kb.C28 ImportOptions { contexts: vec![("default".into(), ContextRule::Home), ("TEXT".into(), ContextRule::HomeWithoutHomeEntry)], remembered, diff --git a/crates/platform/src/open.rs b/crates/platform/src/open.rs index 6cebea4691..8a6a8f6d9c 100644 --- a/crates/platform/src/open.rs +++ b/crates/platform/src/open.rs @@ -323,6 +323,22 @@ pub fn open_external(target: &str) -> Result<(), String> { command.spawn().map(|_| ()).map_err(|e| e.to_string()) } +/// Opens `target` in the application at `app` (Edit Original's chosen application), never through a shell: on +/// macOS `open -a app target`, waiting at most 2 s for Launch Services to refuse; elsewhere `app` runs with +/// `target` as its only argument, without waiting. A path holding `"` is refused on Windows. +#[cfg(not(target_arch = "wasm32"))] +pub fn open_with(app: &Path, target: &Path) -> Result<(), String> { + let _ = (app, target); + todo!("sh.B2a") +} + +/// Whether `path` names an application the platform can launch: an `.app` folder on macOS, an `.exe` file on +/// Windows, an executable file elsewhere; `false` on wasm. +pub fn is_application(path: &Path) -> bool { + let _ = path; + todo!("sh.B2b") +} + /// The command that opens `target`; see [`open_external`]. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn open_command(target: &str) -> Command { diff --git a/crates/theme/src/builtins.rs b/crates/theme/src/builtins.rs index 1a3f90d4b9..9c5edd0c2a 100644 --- a/crates/theme/src/builtins.rs +++ b/crates/theme/src/builtins.rs @@ -1,4 +1,4 @@ -//! The built-in themes: ten `craft-design-theme` files in `crates/theme/themes/`, embedded in +//! The built-in themes: twelve `craft-design-theme` files in `crates/theme/themes/`, embedded in //! the binary and parsed once. use std::sync::LazyLock; @@ -8,7 +8,7 @@ use super::format; use crate::SUITE_DEFAULT; /// Each built-in's file name (without `.json`) and its text. -pub(super) const SOURCES: [(&str, &str); 10] = [ +pub(super) const SOURCES: [(&str, &str); 12] = [ ("artcraft", include_str!("../themes/artcraft.json")), ("pro", include_str!("../themes/pro.json")), ("pro-light-gray", include_str!("../themes/pro-light-gray.json")), @@ -19,6 +19,8 @@ pub(super) const SOURCES: [(&str, &str); 10] = [ ("breeze", include_str!("../themes/breeze.json")), ("classic", include_str!("../themes/classic.json")), ("soft", include_str!("../themes/soft.json")), + ("vectorcraft-modern", include_str!("../themes/vectorcraft-modern.json")), + ("vectorcraft-modern-medium", include_str!("../themes/vectorcraft-modern-medium.json")), ]; // An invalid embedded file is a build defect that the built-in tests catch. diff --git a/crates/theme/themes/vectorcraft-modern-medium.json b/crates/theme/themes/vectorcraft-modern-medium.json new file mode 100644 index 0000000000..5e17bc5fa6 --- /dev/null +++ b/crates/theme/themes/vectorcraft-modern-medium.json @@ -0,0 +1,71 @@ +{ + "schema": "craft-design-theme", + "schema_version": 1, + "id": "craft.vectorcraft-modern-medium", + "name": "VectorCraft Modern Medium", + "version": 1, + "variants": "both", + "contrast_intent": "standard", + "seeds": { + "accent": "#378ef0", + "neutral": "#323232", + "status": { + "bad": "#ec5b62", + "good": "#85dc6a", + "info": "#378ef0", + "warn": "#e8b046" + } + }, + "shape": null, + "light": { + "accent.soft": "#d6d6d6", + "accent.solid": "#378ef0", + "accent.text": "#1062c4", + "caption.close_hover": "#c42b1c", + "caption.close_text": "#ffffff", + "line.border": "#d6d6d6", + "line.control_edge": "#bababa", + "line.divider": "#d6d6d6", + "line.knob_edge": "#282828", + "seeds": { + "neutral": "#f0f0f0", + "status": { + "good": "#4e712e" + } + }, + "state.hover": "#e2e2e2", + "state.pressed": "#cecece", + "state.selected": "#cccccc", + "surface.background": "#e2e2e2", + "surface.canvas": "#d6d6d6", + "surface.panel": "#d3d8e0", + "surface.sunken": "#ffffff", + "text.faint": "#787878", + "text.muted": "#404040", + "text.normal": "#141414", + "text.on_accent": "#ffffff" + }, + "dark": { + "accent.soft": "#4e4e4e", + "accent.solid": "#378ef0", + "caption.close_hover": "#c42b1c", + "caption.close_text": "#ffffff", + "line.border": "#1e1e1e", + "line.control_edge": "#4a4a4a", + "line.divider": "#1e1e1e", + "line.knob_edge": "#282828", + "state.hover": "#424242", + "state.pressed": "#4e4e4e", + "state.selected": "#525252", + "status.bad.fg": "#ec5b62", + "status.warn.fg": "#e8b046", + "surface.background": "#1e1e1e", + "surface.canvas": "#282828", + "surface.panel": "#272c36", + "surface.sunken": "#242424", + "text.faint": "#808080", + "text.muted": "#b2b2b2", + "text.normal": "#dedede", + "text.on_accent": "#ffffff" + } +} diff --git a/crates/theme/themes/vectorcraft-modern.json b/crates/theme/themes/vectorcraft-modern.json new file mode 100644 index 0000000000..0e44299f3a --- /dev/null +++ b/crates/theme/themes/vectorcraft-modern.json @@ -0,0 +1,71 @@ +{ + "schema": "craft-design-theme", + "schema_version": 1, + "id": "craft.vectorcraft-modern", + "name": "VectorCraft Modern", + "version": 1, + "variants": "both", + "contrast_intent": "standard", + "seeds": { + "accent": "#378ef0", + "neutral": "#323232", + "status": { + "bad": "#ec5b62", + "good": "#85dc6a", + "info": "#378ef0", + "warn": "#e8b046" + } + }, + "shape": null, + "light": { + "accent.soft": "#d6d6d6", + "accent.solid": "#378ef0", + "accent.text": "#1062c4", + "caption.close_hover": "#c42b1c", + "caption.close_text": "#ffffff", + "line.border": "#d6d6d6", + "line.control_edge": "#bababa", + "line.divider": "#d6d6d6", + "line.knob_edge": "#282828", + "seeds": { + "neutral": "#f0f0f0", + "status": { + "good": "#4e712e" + } + }, + "state.hover": "#e2e2e2", + "state.pressed": "#cecece", + "state.selected": "#cccccc", + "surface.background": "#e2e2e2", + "surface.canvas": "#d6d6d6", + "surface.panel": "#f3f5f8", + "surface.sunken": "#ffffff", + "text.faint": "#787878", + "text.muted": "#404040", + "text.normal": "#141414", + "text.on_accent": "#ffffff" + }, + "dark": { + "accent.soft": "#4e4e4e", + "accent.solid": "#378ef0", + "caption.close_hover": "#c42b1c", + "caption.close_text": "#ffffff", + "line.border": "#1e1e1e", + "line.control_edge": "#4a4a4a", + "line.divider": "#1e1e1e", + "line.knob_edge": "#282828", + "state.hover": "#424242", + "state.pressed": "#4e4e4e", + "state.selected": "#525252", + "status.bad.fg": "#ec5b62", + "status.warn.fg": "#e8b046", + "surface.background": "#1e1e1e", + "surface.canvas": "#282828", + "surface.panel": "#181b22", + "surface.sunken": "#242424", + "text.faint": "#808080", + "text.muted": "#b2b2b2", + "text.normal": "#dedede", + "text.on_accent": "#ffffff" + } +} diff --git a/crates/window/src/native_menu.rs b/crates/window/src/native_menu.rs index 867f033f22..66f1706702 100644 --- a/crates/window/src/native_menu.rs +++ b/crates/window/src/native_menu.rs @@ -249,6 +249,17 @@ impl Options { } } +/// Whether a menu is open. Safe from any thread; false where there is no application menu bar. +pub fn menu_tracking() -> bool { + todo!("mn.M12") +} + +/// Whether a menu began tracking since the last call, which clears it. Safe from any thread; false where there is +/// no application menu bar. +pub fn take_menu_began() -> bool { + todo!("mn.M12") +} + /// The installed menu bar. pub struct NativeBar(imp::Installed); @@ -278,6 +289,11 @@ impl NativeBar { self.0.tracking() } + /// Whether a menu began tracking since the last call ([`take_menu_began`]). + pub fn take_began(&self) -> bool { + todo!("mn.M13") + } + /// Close the open menu, if there is one. pub fn cancel_tracking(&self) { self.0.cancel_tracking(); diff --git a/crates/window/src/system.rs b/crates/window/src/system.rs index 850ad418ab..d9724bb1fc 100644 --- a/crates/window/src/system.rs +++ b/crates/window/src/system.rs @@ -5,6 +5,37 @@ use craft_behavior::Monitor; use std::sync::Mutex; +/// The mouse buttons the OS reports down, with no egui types. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct HeldButtons(#[allow(dead_code)] u8); // P3(shell-w1): sh.K5 + +impl HeldButtons { + /// No button. + pub const NONE: HeldButtons = HeldButtons(0); + /// The primary button. + pub const PRIMARY: HeldButtons = HeldButtons(1); + /// The secondary button. + pub const SECONDARY: HeldButtons = HeldButtons(2); + /// The middle button. + pub const MIDDLE: HeldButtons = HeldButtons(4); + /// The first extra button. + pub const EXTRA1: HeldButtons = HeldButtons(8); + /// The second extra button. + pub const EXTRA2: HeldButtons = HeldButtons(16); + + /// Whether every button of `b` is down. + pub fn contains(self, b: HeldButtons) -> bool { + let _ = b; + todo!("sh.K5") + } + + /// Adds the buttons of `b`. + pub fn insert(&mut self, b: HeldButtons) { + let _ = b; + todo!("sh.K5") + } +} + /// OS services the multi-window driver reads. Every method runs in the UI's `set_input`, outside every egui lock. pub trait WindowSystem: Send + Sync { /// The system pointer in desktop points, or `None` where the platform does not tell (Wayland, the web). @@ -14,6 +45,12 @@ pub trait WindowSystem: Send + Sync { /// moves a window for a drag and sends the app no pointer events. fn primary_held(&self) -> Option; + /// Every mouse button down now, or `None` where the platform does not tell. + fn buttons_held(&self) -> Option; + + /// Asks the input method to drop its marked text. Returns whether it did. + fn discard_marked_text(&self) -> bool; + /// Whether the platform's command modifier (Cmd on macOS, Ctrl elsewhere) is down now, or `None` where the platform /// does not tell. Read while the OS moves a window for a drag and sends the app no key events. fn command_held(&self) -> Option; @@ -34,6 +71,14 @@ impl WindowSystem for NoWindows { None } + fn buttons_held(&self) -> Option { + None + } + + fn discard_marked_text(&self) -> bool { + false + } + fn primary_held(&self) -> Option { None } @@ -76,6 +121,14 @@ impl WindowSystem for SystemWindows { } } + fn buttons_held(&self) -> Option { + todo!("sh.K6") + } + + fn discard_marked_text(&self) -> bool { + todo!("ty.X3") + } + fn primary_held(&self) -> Option { #[cfg(all(feature = "appkit", target_os = "macos"))] { @@ -140,6 +193,17 @@ impl FakeSystem { self.with(|state| state.primary = held); } + /// Sets the buttons the test system reports down; `None` where the platform does not tell. + pub fn set_buttons_held(&self, held: Option) { + let _ = held; + todo!("sh.K7") + } + + /// The count of asked discards of marked text. + pub fn discards(&self) -> usize { + todo!("ty.X4") + } + /// Sets whether the command modifier is down; `None` where the platform does not tell. pub fn set_command_held(&self, held: Option) { self.with(|state| state.command = held); @@ -167,6 +231,14 @@ impl WindowSystem for FakeSystem { self.with(|state| state.pointer) } + fn buttons_held(&self) -> Option { + todo!("sh.K6") + } + + fn discard_marked_text(&self) -> bool { + todo!("ty.X3") + } + fn primary_held(&self) -> Option { self.with(|state| state.primary) } From 7cc766ad845f5009ee13ac7baffde3f8f45c8e60 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 21 Nov 2026 12:30:25 +0700 Subject: [PATCH 002/523] Contract stubs: craft-ui-contract, craft-ui-widgets --- .../ui-contract/src/contract/body/presses.rs | 9 ++ .../src/contract/collection/props.rs | 6 +- crates/ui-contract/src/contract/container.rs | 9 ++ crates/ui-contract/src/contract/cx/context.rs | 8 +- crates/ui-contract/src/contract/cx/item.rs | 7 ++ crates/ui-contract/src/contract/cx/pointer.rs | 13 ++- crates/ui-contract/src/contract/items/drag.rs | 19 ++++- crates/ui-contract/src/contract/label.rs | 2 +- .../ui-contract/src/contract/label/props.rs | 22 +++++ crates/ui-contract/src/contract/mod.rs | 2 +- .../ui-contract/src/contract/overlay/place.rs | 20 ++++- crates/ui-contract/src/contract/reorder.rs | 12 +++ crates/ui-contract/src/contract/run.rs | 6 +- .../ui-contract/src/contract/steps/finish.rs | 6 +- crates/ui-contract/src/contract/values.rs | 6 ++ crates/ui-contract/src/layout/body.rs | 20 ++++- crates/ui-contract/src/primitives/draw.rs | 3 +- crates/ui-contract/src/primitives/face.rs | 54 ++++++++++++ crates/ui-contract/src/primitives/icon.rs | 5 +- crates/ui-contract/src/primitives/mod.rs | 4 +- crates/ui-contract/src/primitives/svg_set.rs | 10 ++- crates/ui-contract/src/primitives/text.rs | 11 ++- .../ui-contract/src/primitives/text_input.rs | 4 + .../src/primitives/textures/thumbnails.rs | 3 +- .../ui-contract/src/runtime/commands/board.rs | 49 ++++++----- .../ui-contract/src/runtime/commands/mod.rs | 60 +++++++++++++- crates/ui-contract/src/runtime/edit.rs | 35 ++++++++ crates/ui-contract/src/runtime/egui/access.rs | 4 +- .../src/runtime/egui/access/tree.rs | 19 ++++- crates/ui-contract/src/runtime/egui/input.rs | 20 +++-- crates/ui-contract/src/runtime/env.rs | 2 + crates/ui-contract/src/runtime/env/root.rs | 7 ++ crates/ui-contract/src/runtime/env/scrub.rs | 22 +++++ crates/ui-contract/src/runtime/env/shell.rs | 7 +- crates/ui-contract/src/runtime/env/units.rs | 51 +++++++++++- crates/ui-contract/src/runtime/frame.rs | 15 +++- crates/ui-contract/src/runtime/ime.rs | 7 ++ crates/ui-contract/src/runtime/keys.rs | 15 ++++ crates/ui-contract/src/runtime/keys/claims.rs | 14 ++++ crates/ui-contract/src/runtime/keys/input.rs | 11 ++- crates/ui-contract/src/runtime/keys/route.rs | 2 +- crates/ui-contract/src/runtime/memory.rs | 24 ++++++ crates/ui-contract/src/runtime/pointer.rs | 11 ++- .../ui-contract/src/runtime/windows/host.rs | 18 +++- crates/ui-contract/src/style/cx.rs | 13 +++ crates/ui-contract/src/style/span.rs | 8 ++ crates/ui-contract/src/testing/icon_trials.rs | 14 +++- .../ui-contract/tests/it/runtime/windows.rs | 3 +- crates/ui-widgets/src/bars/bar.rs | 7 ++ crates/ui-widgets/src/buttons/button.rs | 29 ++++++- crates/ui-widgets/src/buttons/face.rs | 3 + crates/ui-widgets/src/buttons/link.rs | 8 ++ crates/ui-widgets/src/buttons/mod.rs | 2 +- crates/ui-widgets/src/buttons/split_button.rs | 1 + .../ui-widgets/src/buttons/toggle_button.rs | 1 + crates/ui-widgets/src/choice/mod.rs | 4 +- crates/ui-widgets/src/choice/radio.rs | 7 ++ crates/ui-widgets/src/choice/segmented.rs | 1 + crates/ui-widgets/src/choice/swatch.rs | 82 +++++++++++++++++++ crates/ui-widgets/src/choice/swatch_table.rs | 48 ++++++++++- crates/ui-widgets/src/display/kbd.rs | 3 +- crates/ui-widgets/src/display/text.rs | 7 ++ crates/ui-widgets/src/form/slider_field.rs | 14 ++++ .../ui-widgets/src/layout_components/mod.rs | 8 ++ crates/ui-widgets/src/list/mod.rs | 4 +- crates/ui-widgets/src/list/row.rs | 68 +++++++++++++++ crates/ui-widgets/src/list/view.rs | 11 +++ crates/ui-widgets/src/menu/alternate.rs | 28 +++++++ crates/ui-widgets/src/menu/bar.rs | 14 +++- crates/ui-widgets/src/menu/item.rs | 11 +++ crates/ui-widgets/src/menu/mod.rs | 6 +- crates/ui-widgets/src/menu/panel.rs | 3 + crates/ui-widgets/src/menu/popup.rs | 23 ++++++ crates/ui-widgets/src/menu/search.rs | 38 ++++++++- crates/ui-widgets/src/menu/search/index.rs | 24 ++++++ crates/ui-widgets/src/menu/search/synonyms.rs | 42 ++++++++++ crates/ui-widgets/src/pickers/mod.rs | 2 +- .../ui-widgets/src/pickers/reference_point.rs | 19 ++++- crates/ui-widgets/src/popover/anchored.rs | 7 ++ crates/ui-widgets/src/text/adorn.rs | 5 ++ crates/ui-widgets/src/text/hex.rs | 5 ++ crates/ui-widgets/src/text/linked.rs | 6 ++ crates/ui-widgets/src/text/mod.rs | 6 +- crates/ui-widgets/src/text/number.rs | 20 ++++- crates/ui-widgets/src/text/number/rule.rs | 9 +- crates/ui-widgets/src/text/number/stories.rs | 3 +- crates/ui-widgets/src/text/number/value.rs | 2 + crates/ui-widgets/src/text/selectable_text.rs | 26 +++--- .../src/text/selectable_text/stories.rs | 6 +- crates/ui-widgets/src/text/zoom_field.rs | 10 ++- crates/ui-widgets/src/tile_grid/grid.rs | 18 ++++ crates/ui-widgets/src/tile_grid/mod.rs | 2 +- 92 files changed, 1222 insertions(+), 113 deletions(-) create mode 100644 crates/ui-contract/src/primitives/face.rs create mode 100644 crates/ui-contract/src/runtime/env/scrub.rs create mode 100644 crates/ui-widgets/src/menu/alternate.rs create mode 100644 crates/ui-widgets/src/menu/search/index.rs create mode 100644 crates/ui-widgets/src/menu/search/synonyms.rs diff --git a/crates/ui-contract/src/contract/body/presses.rs b/crates/ui-contract/src/contract/body/presses.rs index 6316b35a90..98296dceb0 100644 --- a/crates/ui-contract/src/contract/body/presses.rs +++ b/crates/ui-contract/src/contract/body/presses.rs @@ -19,6 +19,8 @@ struct BandDouble(bool); struct SurfacePress { pressed: bool, double: bool, + #[allow(dead_code)] // P3(chrome-w5): ch.K32 + clicked: bool, } impl BodyCx<'_> { @@ -53,6 +55,13 @@ impl BodyCx<'_> { !self.memory.is_peek() && self.memory.recall::(sub(self.id, "surface_press")).double } + /// Whether this pass's primary release ends a press that went down on the container's own surface, moved less + /// than `PointerFrame::slop` and was released inside. A drag, a cancel, a release elsewhere and a measuring run + /// give false. It takes no focus and is no Tab stop. + pub fn surface_clicked(&self) -> bool { + todo!("ch.K32") + } + /// Requests `cursor` at `priority` for this pass, in the cursor service the parts' and components' requests go /// to: the highest priority of the pass wins, the later request on a tie. A body that learns something only after /// its children ran (a drag its panes report as refused) sets the cursor in the same pass. A measuring run diff --git a/crates/ui-contract/src/contract/collection/props.rs b/crates/ui-contract/src/contract/collection/props.rs index 081ae575be..d72419ba44 100644 --- a/crates/ui-contract/src/contract/collection/props.rs +++ b/crates/ui-contract/src/contract/collection/props.rs @@ -2,7 +2,7 @@ use super::columns::{ColumnSort, ColumnSpec}; use super::events::ListDrag; -use crate::contract::Notch; +use crate::contract::{Notch, ScrollAnchor}; pub use crate::runtime::env::RowPressed; use crate::runtime::env::{Counted, Label}; use crate::style::StyleCx; @@ -241,6 +241,9 @@ pub struct CollectionProps { /// While a drag whose payload is neither the collection's own nor one of its drop kinds rests over an item that is /// not selected, the item becomes the lead and the selection in that pass. pub select_under_drag: bool, + /// Which end of the rows a collection that scrolls its own rows stays at while rows are added; `End` keeps the offset + /// at the end as long as the user left it there. + pub scroll_anchor: ScrollAnchor, } type Payload = Arc; @@ -324,6 +327,7 @@ impl CollectionProps { pages: false, current: None, select_under_drag: false, + scroll_anchor: ScrollAnchor::Start, } } diff --git a/crates/ui-contract/src/contract/container.rs b/crates/ui-contract/src/contract/container.rs index c996143d6d..1de376030f 100644 --- a/crates/ui-contract/src/contract/container.rs +++ b/crates/ui-contract/src/contract/container.rs @@ -786,6 +786,8 @@ pub struct ContainerProps { pub collection_body: bool, /// The labelled rows of the body share the widest label as one column. pub label_column: bool, + /// The rank by which a body unit of a shrinking row leaves whole; unranked units never leave by rank. + pub fit_rank: Option, /// How the labelled rows under the container show their labels; `None` keeps the scheme of the scope. pub labels: Option, /// The component whose memory holds the container's shown memory and its layer's bookkeeping, when it is another: @@ -868,6 +870,7 @@ impl ContainerProps { outer_edit: false, collection_body: false, label_column: false, + fit_rank: None, labels: None, owner: None, } @@ -1022,6 +1025,12 @@ impl ContainerProps { self } + /// Sets the rank by which the container leaves a shrinking row whole. + pub const fn fit_rank(mut self, rank: u8) -> Self { + self.fit_rank = Some(rank); + self + } + /// Makes the container an arena root. pub const fn arena(mut self, on: bool) -> Self { self.arena = on; diff --git a/crates/ui-contract/src/contract/cx/context.rs b/crates/ui-contract/src/contract/cx/context.rs index 3cc1dc3a81..bfa726920a 100644 --- a/crates/ui-contract/src/contract/cx/context.rs +++ b/crates/ui-contract/src/contract/cx/context.rs @@ -217,6 +217,11 @@ impl Cx<'_, C> { text.layout(&self.core.ctx, &Env::of_root(&self.core.ctx).tokens, craft_i18n::Direction::Ltr) } + /// Whether the control's link label was clicked in this pass. + pub fn link_activated(&self) -> bool { + todo!("wg.W08") + } + /// Asks the platform to open `url`, in a new tab where the platform has tabs and `new_tab` is set. pub fn open_url(&mut self, url: &str, new_tab: bool) { crate::runtime::egui::output::open_url(&self.core.ctx, url, new_tab); @@ -236,7 +241,8 @@ impl Cx<'_, C> { /// activation came from (`part_activated` gives it). Returns whether the command was queued. pub fn fire(&mut self, command: impl Into, source: FireSource) -> bool { let Some(resolved) = commands::resolve_scoped(&self.core.ctx, self.core.env.command_chain(), &command.into()) else { return false }; - commands::fire_resolved(&self.core.ctx, &resolved, source) + // P3(widgets-w3): ap.AP9 + commands::fire_resolved(&self.core.ctx, &resolved, source, craft_keymap::Mods::NONE) } /// Where an activation of `part` came from this pass: `Key` for a keyboard activation while `part` is the diff --git a/crates/ui-contract/src/contract/cx/item.rs b/crates/ui-contract/src/contract/cx/item.rs index 3d4ccfe7a5..a031d90d6e 100644 --- a/crates/ui-contract/src/contract/cx/item.rs +++ b/crates/ui-contract/src/contract/cx/item.rs @@ -75,6 +75,13 @@ impl<'r, K> ItemCx<'_, 'r, K> { self.tip = Some(Box::new(tip)); } + /// Shows `body` under the item, across the content width, in a child `Ui` with id `sub(item_id, "detail")`. It adds + /// its height to the item's slot, which keeps its last shown height out of view. + pub fn detail(&mut self, body: impl FnOnce(&mut Ui) + 'r) { + let _ = body; + todo!("ap.AP12") + } + /// The opener for the item's part `part`: after the collection is shown, `CollectionResponse::opener` gives the /// part's response (its click this pass and its rect), and a layer-5 menu opens from it with `opened_by`. pub fn part_opener(&mut self, part: impl Into) -> ItemOpener { diff --git a/crates/ui-contract/src/contract/cx/pointer.rs b/crates/ui-contract/src/contract/cx/pointer.rs index b7b0c4b2c8..b0c0c1dd49 100644 --- a/crates/ui-contract/src/contract/cx/pointer.rs +++ b/crates/ui-contract/src/contract/cx/pointer.rs @@ -6,7 +6,7 @@ use crate::primitives::PartResult; use crate::runtime::drag::{self, DragPreview, DropTarget, DropZone, Typed, WindowDropTarget}; use crate::runtime::egui::areas; use crate::runtime::{cursor, frame, pointer, wheel}; -use craft_behavior::{Cursor, CursorPriority, DropOperation, PartKey, PartRef, PressCancel, PressState, Wheel}; +use craft_behavior::{Cursor, CursorPriority, DropOperation, MultiTap, PartKey, PartRef, PressCancel, PressState, Wheel}; use egui::{Id, Pos2}; use std::any::{Any, TypeId}; use std::ops::Range; @@ -35,6 +35,9 @@ pub trait Pointer { fn activated_member(&self) -> Option; /// This pass's wheel share, once, with the pointer it came at (`Wheel::at`) in this component's egui layer space (8.3). fn take_wheel(&mut self) -> Option; + /// This pass's tap, once, when it lies in this component's rect and this component (an arena root with its members) + /// wins a press there. + fn take_multi_tap(&mut self) -> Option; /// Requests `cursor` at `priority`; the highest priority of the pass wins. fn cursor(&mut self, cursor: impl Into, priority: CursorPriority); /// Ends every captured press of this viewport. @@ -107,6 +110,10 @@ impl Pointer for CxCore<'_> { Some(wheel) } + fn take_multi_tap(&mut self) -> Option { + todo!("cv.F19") + } + fn cursor(&mut self, cursor: impl Into, priority: CursorPriority) { if self.cursor.as_ref().is_none_or(|(_, held)| priority > *held) { self.cursor = Some((cursor.into(), priority)); @@ -198,6 +205,10 @@ impl Pointer for Cx<'_, C> { self.core.take_wheel() } + fn take_multi_tap(&mut self) -> Option { + self.core.take_multi_tap() + } + fn cursor(&mut self, cursor: impl Into, priority: CursorPriority) { self.core.cursor(cursor, priority); } diff --git a/crates/ui-contract/src/contract/items/drag.rs b/crates/ui-contract/src/contract/items/drag.rs index 9a34cf3751..59587629fa 100644 --- a/crates/ui-contract/src/contract/items/drag.rs +++ b/crates/ui-contract/src/contract/items/drag.rs @@ -13,6 +13,7 @@ use crate::contract::collection::{ CollectionEvent, CollectionProps, ColumnKind, DropAt, DropPayload, DropPlace, ListDrag, PendingDrop, ReorderMove, ToggleColumn, ToggleEdit, }; use crate::contract::reorder; +use crate::contract::reorder::EDGE_ROWS_PER_SECOND; use crate::contract::{Collection, Cx, DragPreview, DropMark, DropTarget, Pointer as _}; use crate::runtime::drag; use crate::runtime::env::Label; @@ -23,9 +24,6 @@ use craft_behavior::{ use egui::{Pos2, Rect, Vec2}; use std::any::Any; -/// Rows per second the view scrolls at when the pointer is a full edge band beyond the view's edge. -pub(super) const EDGE_ROWS_PER_SECOND: f32 = 4.0; - /// A toggle sweep: the value it sets and the rows it has crossed. #[derive(Clone)] struct Sweep { @@ -57,6 +55,9 @@ pub enum SweepStep { Restore(ToggleEdit), /// Undo the `ShowOnly` of a cancelled Alt sweep: the cell has the value from before it. UndoShowOnly(ToggleEdit), + /// The first press held exactly one of the [`SweepApply::claims`] modifiers: it belongs to the host. It flips + /// nothing, and the cells its drag crosses give nothing. Reported once; its Cancel gives nothing. + Claimed(ToggleEdit), } /// The state a sweep needs between events: which gesture opened it and whether Alt was held. @@ -83,6 +84,8 @@ struct Run { pub struct SweepApply { run: Option, show_only: bool, + #[allow(dead_code)] // P3(appearance-w1): dp.C8 + claims: Vec, } /// A move of a collection's own items as they stand before the drop, and as the drop leaves them. @@ -96,7 +99,15 @@ impl SweepApply { /// A column where Alt plus the first press shows only that cell. pub fn show_only() -> Self { - SweepApply { run: None, show_only: true } + SweepApply { run: None, show_only: true, claims: Vec::new() } + } + + /// A first press with exactly `mods` held belongs to the host: it flips nothing, and the cells its drag crosses + /// give nothing (`SweepStep::Claimed`). Claims are checked before `show_only`'s Alt, and the method can be called + /// more than once. + pub fn claims(self, mods: craft_keymap::Mods) -> Self { + let _ = mods; + todo!("dp.C8") } /// Whether this is a [`SweepApply::show_only`] column, where Alt plus the first press shows only that cell. diff --git a/crates/ui-contract/src/contract/label.rs b/crates/ui-contract/src/contract/label.rs index 8c583a7940..31dd318fc5 100644 --- a/crates/ui-contract/src/contract/label.rs +++ b/crates/ui-contract/src/contract/label.rs @@ -13,5 +13,5 @@ mod step; pub use leaf::colon_of; pub(crate) use place::{control_after, label_gap}; pub(crate) use props::inside; -pub use props::{CellWidth, FieldLayout, GlyphLabel, InsideLabel, LabelKind, LabelScheme, Scrub, SideLabel}; +pub use props::{CellWidth, FieldLayout, GlyphLabel, InsideLabel, LabelKind, LabelPress, LabelScheme, Scrub, SideLabel}; pub(crate) use step::{LabelIn, LeafLabel, Trailing, flow_leaf, in_column, leaf, leaf_under, report_after_reach, run, show_leaf_in_flow}; diff --git a/crates/ui-contract/src/contract/label/props.rs b/crates/ui-contract/src/contract/label/props.rs index 5f80ba2a30..d77d880993 100644 --- a/crates/ui-contract/src/contract/label/props.rs +++ b/crates/ui-contract/src/contract/label/props.rs @@ -172,6 +172,18 @@ pub(crate) fn inside(env: EnvView<'_>, side: &SideLabel, enabled: bool) -> Optio /// The width of a caption's cell. pub type CellWidth = ColumnWidth; +/// What a click on a control's side label does. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum LabelPress { + /// A click focuses the control. + #[default] + Focus, + /// The label shows in the link look, and a click reports to the control's host and leaves focus alone. It is no + /// Tab stop of its own, and a drag still scrubs when `scrub` is on. + Link, +} + /// What `ContainerProps.label` holds: how the label is shown and what it does. The text is `Common.label`. #[derive(Clone, Debug, Default, PartialEq)] #[non_exhaustive] @@ -192,6 +204,8 @@ pub struct SideLabel { pub detail: Option

+ Send + Sync + 'static) -> Self { + let _ = map; + todo!("co.K6") + } + /// Whether Shift or Cmd adds cells to the selection. #[must_use] pub fn multiple(mut self, on: bool) -> Self { @@ -180,7 +220,7 @@ impl Component for SwatchTable<'_> { _ => None, }); let changed = response.events.iter().any(|event| matches!(event, CollectionEvent::Selection(_))); - SwatchTableOutput { response: response.response, selected: selection.lead.filter(|_| changed), chosen: selection.items, open } + SwatchTableOutput { response: response.response, selected: selection.lead.filter(|_| changed), chosen: selection.items, open, delete: false } // P3(color-w1): ex.E20 } } diff --git a/crates/ui-widgets/src/display/kbd.rs b/crates/ui-widgets/src/display/kbd.rs index 8649c36da7..0d4f864bfe 100644 --- a/crates/ui-widgets/src/display/kbd.rs +++ b/crates/ui-widgets/src/display/kbd.rs @@ -127,7 +127,8 @@ impl Kbd { } None => one, }; - if trigger.double { format!("{one} {one}") } else { one } + // P3(shortcuts-w3): kb.C13b + if trigger.is_double() { format!("{one} {one}") } else { one } } /// The name of `key` alone for `os`, in the language of `words`: its word when it has one, else the key as the diff --git a/crates/ui-widgets/src/display/text.rs b/crates/ui-widgets/src/display/text.rs index 666161ab61..60c124ab4c 100644 --- a/crates/ui-widgets/src/display/text.rs +++ b/crates/ui-widgets/src/display/text.rs @@ -97,6 +97,13 @@ impl Text { text } + /// Sets the text's ideal and least width to those of `sample`, so a readout keeps its width while its value changes. + #[must_use] + pub fn sample(self, sample: impl Into

{ self.offered = keeps; self } + + /// The name and captures the dialog opens with; without it, `NewWorkspace::default()`. + #[must_use] + pub fn value(self, value: NewWorkspace) -> Self { + let _ = (self, value); + todo!("ch.K26") + } } /// The command id of `WorkspaceCommands::New`, which the dialog answers for. diff --git a/crates/ui-patterns/src/patterns/form_dialogs/about/credits.rs b/crates/ui-patterns/src/patterns/form_dialogs/about/credits.rs index c6b2b56013..a0fc9845fc 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/about/credits.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/about/credits.rs @@ -3,6 +3,7 @@ use crate::runtime::env::Label; use std::borrow::Cow; +use std::sync::Arc; /// A link on the About tab. #[derive(Clone, Debug, PartialEq)] @@ -37,6 +38,8 @@ pub struct AboutInfo { pub links: Vec, /// The faint last line naming what the application is built with. pub built_with: Label, + /// The application's mark, at the start of the About tab's header row. + pub icon: Option>, } impl AboutInfo { @@ -49,6 +52,7 @@ impl AboutInfo { community: None, links: Vec::new(), built_with: Label::Empty, + icon: None, } } @@ -72,6 +76,13 @@ impl AboutInfo { self.built_with = text.into(); self } + + /// The application's mark, shown at the start of the About tab's header row. + #[must_use] + pub fn icon(self, image: Arc) -> Self { + let _ = (self, image); + todo!("sh.K26") + } } /// One contributor, as the build script bakes them. A display or real name is shown only with recorded consent; diff --git a/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs b/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs index 0a7b55ae09..83ea0e96d7 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs @@ -2,7 +2,7 @@ //! owned by a `DialogHost`. A command form is a `ParamDialog` without a preview. use super::fields::{DialogFields, FieldValue}; -use crate::patterns::presets::{PresetKind, PresetRow}; +use crate::patterns::presets::{NamedPresetEvent, PresetKind, PresetRow}; use crate::runtime::requests::{ColorRequest, EyedropperRequest, HostAnswer, ListingRequest, PathRequest}; use super::form::{FormDialog, FormDialogWords}; @@ -26,7 +26,7 @@ use crate::notices::{Notice, NoticeLayout}; use crate::runtime::env::{Env, Label}; use crate::text::RangeAlert; -use crate::runtime::memory::MemoryStage; +use crate::runtime::memory::{Lifetime, MemoryStage}; use crate::runtime::overlay::CloseReason; use crate::runtime::words::CommonWords; @@ -94,14 +94,15 @@ pub struct ParamResult { /// The id of the dialog that filed the result, instance ids included, so a family's step names the dialog that /// answered. `HostedParamDialog` sets it; a `ParamDialog` shown on its own has no host id and leaves `Id::NULL`. pub id: DialogId, - remember: Option<(SaveKey, DialogFields)>, + remember: Option<(SaveKey, Lifetime, DialogFields)>, } impl ParamResult { /// Stores the values of a dialog built with [`ParamDialog::remember`] for the next open. The app calls it after /// its command succeeds, so a failed command leaves the previous values; without a remember key it does nothing. pub fn remember(&self, ctx: &Context) { - if let Some((key, values)) = &self.remember { + if let Some((key, lifetime, values)) = &self.remember { + let _ = lifetime; // P3(forms-w1): od.OD3 crate::runtime::memory::set_saved_value::>(ctx, key, Some(values.clone())); } } @@ -139,6 +140,10 @@ pub struct ParamDialogOutput { pub preview_click: Option, /// The id of the extra footer button pressed this pass (`ParamDialog::extra_buttons`). pub footer_action: Option, + /// The preset edits of this pass: Apply, Create, Rename and Delete from the presets row (`ParamDialog::presets`). + pub presets: Vec>, + /// The help link a row's button reported in this pass. + pub help_link: Option, /// The answer OK would have given, the pass OK was pressed on a dialog that holds its OK for the host. pub(crate) held: Option, /// The picture point at the centre of the view the preview pane drew this pass; `None` without a preview. @@ -184,6 +189,12 @@ pub struct ParamDialog<'a> { /// Saves the values under `key` when the app calls [`ParamResult::remember`], and opens with them. #[prop] remember: Option, + /// How long the values `remember` keeps live; without `remember` it does nothing. + #[prop] + remember_for: Lifetime, + /// The named presets row above the rows. + #[prop] + presets: Option>, /// Whether OK can be pressed; Enter does nothing while it cannot. #[prop] ok_enabled: bool, @@ -286,6 +297,18 @@ struct Shaped<'a>(Box) -> Dialog<'a> + 'a>); type BelowRowsFn<'a> = Box; +/// The named presets a [`ParamDialog`] offers above its rows: the preset rows, the values each applies, and the names +/// the user cannot rename or delete. +#[derive(Clone, Copy, Debug)] +pub struct ParamPresets<'a> { + /// The listed presets, by name. + pub rows: &'a [PresetRow], + /// The values each preset applies, by name. + pub values: &'a [(String, DialogFields)], + /// The names of the built-in presets, which `check_name` refuses. + pub built_in: &'a [String], +} + /// What `ParamDialog::below` draws under the rows. pub struct BelowRows<'a>(BelowRowsFn<'a>); @@ -306,6 +329,8 @@ impl<'a> ParamDialog<'a> { bound: None, open: None, remember: None, + remember_for: Lifetime::default(), + presets: None, ok_enabled: true, ok_reason: None, ok_label: None, @@ -346,8 +371,9 @@ impl<'a> ParamDialog<'a> { } /// The answer OK gives with `fields`: with `remember`, it keeps the part of them the dialog saves. - fn result(key: String, params: &[Param], remember: Option, fields: DialogFields) -> ParamResult { - let remember = remember.map(|save| (save, Self::remembered(params, &fields))); + fn result(key: String, params: &[Param], remember: Option, remember_for: Lifetime, fields: DialogFields) -> ParamResult { + // P3(forms-w1): od.OD3 -- callers pass the dialog's `remember_for`. + let remember = remember.map(|save| (save, remember_for, Self::remembered(params, &fields))); ParamResult { key, fields, remember, id: DialogId::NULL } } @@ -411,6 +437,8 @@ impl<'a> ParamDialog<'a> { bound, open, remember, + remember_for, + presets: _, ok_enabled, ok_reason, ok_label, @@ -593,8 +621,8 @@ impl<'a> ParamDialog<'a> { _ => None, }; let (result, held) = match (shown.accepted, pick, latest) { - (Some(fields), _, _) => (Some(Self::result(key, ¶ms, remember, fields)), None), - (None, Some(ResetPick::Accept), Some(fields)) if hold => (None, Some(Self::result(key, ¶ms, remember, fields))), + (Some(fields), _, _) => (Some(Self::result(key, ¶ms, remember, remember_for, fields)), None), + (None, Some(ResetPick::Accept), Some(fields)) if hold => (None, Some(Self::result(key, ¶ms, remember, remember_for, fields))), _ => (None, None), }; ParamDialogOutput { @@ -607,12 +635,28 @@ impl<'a> ParamDialog<'a> { comparing: shown.comparing, preview_click: shown_preview.clicked, footer_action, + presets: Vec::new(), + help_link: None, held, preview_centre: shown_preview.centre, } } } +/// The values `ctx` remembers under `key` for `lifetime`: the saved tier for `Saved`, the session tier for `Run`. +#[allow(dead_code)] // P3(forms-w1): od.OD3 +fn remembered_values(ctx: &Context, key: &SaveKey, lifetime: Lifetime) -> Option { + let _ = (ctx, key, lifetime); + todo!("od.OD3") +} + +/// Applies the host's `answers` to `values` for `params`: a colour, path or eyedropper answer writes its row. +#[allow(dead_code)] // P3(forms-w1): fl.F35 +pub(crate) fn apply_answers(params: &[Param], values: &mut DialogFields, answers: Vec) { + let _ = (params, values, answers); + todo!("fl.F35") +} + /// What the footer of an installed Reset footer reads from the body. #[derive(Clone, Copy, Default)] struct Footing { @@ -963,6 +1007,38 @@ impl HostedParamDialog { self.held.answer(answer); } + /// `Some`: the host refuses the current values, and OK stays off with `reason` shown under the rows until the values + /// change; `None` ends the refusal. + pub fn refuse(&mut self, reason: Option

{ /// Stable id: `"photo"`. - pub id: &'static str, - /// The English title, shown when no word names the id. - pub title: &'static str, + pub id: Cow<'static, str>, + /// The title, shown when no word names the id. + pub title: Label, /// The category's cards in display order. - pub presets: Vec, + pub presets: Vec

, } -impl PresetCategory { - /// The category `id` titled `title` in English, with its `presets`. - pub fn new(id: &'static str, title: &'static str, presets: Vec) -> Self { - Self { id, title, presets } +impl

PresetCategory

{ + /// The category `id` titled `title`, with its `presets`. + pub fn new(id: impl Into>, title: impl Into

) -> Self { + Self { id: id.into(), title: title.into(), presets } } +} +impl PresetCategory { /// PhotoCraft's categories in tab order: Photo, Print, Art & Illustration, Web, Mobile, Film & Video, with their /// presets. Recent and Saved are not in this list: the dialog adds them first and last. pub fn standard() -> Vec { diff --git a/crates/ui-patterns/src/patterns/form_dialogs/new_document/settings.rs b/crates/ui-patterns/src/patterns/form_dialogs/new_document/settings.rs new file mode 100644 index 0000000000..251dc82936 --- /dev/null +++ b/crates/ui-patterns/src/patterns/form_dialogs/new_document/settings.rs @@ -0,0 +1,271 @@ +//! What New Document needs of an app's settings: [`DocumentSettings`], the cards and the details rows built from it, +//! and the raster implementation's setup. + +use super::NewDocumentWords; +use super::presets::{ColorProfiles, DocumentOptions, DocumentPreset, NewDocumentPresetWords, Orientation, PresetCategory}; +use crate::patterns::presets::PresetId; +use crate::runtime::env::{Label, Units}; +use crate::runtime::requests::ColorRequest; +use craft_behavior::PixelSize; +use egui::Ui; +use serde::Serialize; +use serde::de::DeserializeOwned; +use std::fmt::Debug; +use std::marker::PhantomData; + +/// What New Document needs of an app's settings: its cards, its details rows and how a card fills it. `fitted` runs +/// after every edit and every `set_json_field`; `Memory` lives in the dialog's session. +pub trait DocumentSettings: Clone + PartialEq + Debug + Default + Serialize + DeserializeOwned + Send + Sync + 'static { + /// What a built-in card stands for. + type Preset: Clone + Debug + PartialEq + Send + Sync + 'static; + /// What the dialog is set up with besides the cards (the clipboard, the profiles, the resolutions). + type Setup: Clone + Default + Send + Sync + 'static; + /// What the dialog's session keeps for the details rows (the linked size fields, a running gesture). + type Memory: Clone + Default + Send + Sync + 'static; + + /// The document's name. + fn name(&self) -> &str; + /// Sets the document's name. + fn set_name(&mut self, name: String); + /// The page's width and height, for a card's aspect. + fn page(&self) -> (f64, f64); + /// Whether `other` is the same document as `self`, for the recent list. + fn same_document(&self, other: &Self) -> bool; + /// Whether the settings are valid. + fn fits(&self) -> bool; + /// The settings made valid; they are unchanged by default. + fn fitted(self) -> Self { + self + } + /// Fills what the dialog adds to the settings it opens on: the clipboard's size and the default name `untitled`. + fn open(&mut self, setup: &Self::Setup, untitled: &str); + /// The card of a built-in `preset`. + fn preset_card(preset: &Self::Preset, cx: &CardCx<'_, Self>) -> DocumentCard; + /// The cards of the Recent tab. + fn recent_cards(cx: &CardCx<'_, Self>) -> Vec>; + /// The card of the saved preset `name` with the settings `saved`. + fn saved_card(name: &str, saved: &Self, cx: &CardCx<'_, Self>) -> DocumentCard; + /// Applies `card` to the settings. + fn apply_card(&mut self, card: &DocumentCard, setup: &Self::Setup, memory: &mut Self::Memory); + /// Draws the details rows over `values`. + fn details(ui: &mut Ui, values: &mut Self, cx: &mut DetailsCx<'_, Self>); +} + +/// One card or Saved row; the aspect comes from `settings.page()`. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct DocumentCard { + /// The card's title. + pub title: Label, + /// The card's second line. + pub line: String, + /// The card's hover text. + pub tooltip: Option, + /// The settings the card applies. + pub settings: S, + /// Where the card comes from. + pub source: CardSource, +} + +impl DocumentCard { + /// A card titled `title` with the second `line`, applying `settings`. + pub fn new(title: impl Into

+ Send + Sync + 'static) -> Self { + let _ = map; + todo!("co.K38") + } + /// Limit to Library: every colour snaps to the nearest of `palette`. pub fn limit(mut self, palette: &'a [Srgba]) -> Self { self.limit = Some(palette); @@ -337,7 +391,8 @@ impl<'a> HarmonyPanel<'a> { .selection(Bind::bound(&mut strip_selection)) .show_all(ui); if let Some(i) = out.selected { - chosen = strip.get(i).map(|(_, c)| *c); + // P3(widgets-w5): co.K38 + chosen = strip.get(i).map(|(_, c)| GuideCell { at: GuideCellAt::Strip(i), color: *c }); } let columns = guide.grid.first().map_or(1, Vec::len).max(1); @@ -354,13 +409,18 @@ impl<'a> HarmonyPanel<'a> { if let Some(i) = selected && cells.len() == 1 { - chosen = flat.get(i).map(|(_, c)| *c); + // P3(widgets-w5): co.K38 + chosen = flat.get(i).map(|(_, c)| GuideCell { at: GuideCellAt::Grid { row: i / columns, column: i % columns }, color: *c }); } let mut cells = selection.items.clone(); cells.sort_unstable(); cells.dedup(); - let colors: Vec = cells.iter().filter_map(|&i| flat.get(i).map(|(_, c)| *c)).collect(); - let after_picked = HarmonyPicked { selection, guide: stamp, colors }; + // P3(widgets-w5): co.K38 + let cells: Vec = cells + .iter() + .filter_map(|&i| flat.get(i).map(|(_, c)| GuideCell { at: GuideCellAt::Grid { row: i / columns, column: i % columns }, color: *c })) + .collect(); + let after_picked = HarmonyPicked { selection, guide: stamp, cells }; let (left, right) = match before.options.variation { Variation::TintsShades => (&words.shades, &words.tints), @@ -437,7 +497,7 @@ impl HarmonyMenu { variation(HarmonyCommand::TintsShades, Variation::TintsShades), variation(HarmonyCommand::WarmCool, Variation::WarmCool), variation(HarmonyCommand::VividMuted, Variation::VividMuted), - (HarmonyCommand::SaveAsSwatches, CommandState::new().enabled(!picked.colors().is_empty())), + (HarmonyCommand::SaveAsSwatches, CommandState::new().enabled(!picked.cells().is_empty())), (HarmonyCommand::Options, CommandState::new()), ] } @@ -449,7 +509,9 @@ impl HarmonyMenu { HarmonyCommand::WarmCool => state.options.variation = Variation::WarmCool, HarmonyCommand::VividMuted => state.options.variation = Variation::VividMuted, HarmonyCommand::SaveAsSwatches => { - return (!picked.colors().is_empty()).then(|| HarmonyMenuAction::SaveAsSwatches(picked.colors().to_vec())); + // P3(widgets-w5): co.K38 + return (!picked.cells().is_empty()) + .then(|| HarmonyMenuAction::SaveAsSwatches(picked.cells().iter().map(|cell| cell.color).collect())); } HarmonyCommand::Options => return Some(HarmonyMenuAction::Options), } diff --git a/crates/color-ui/src/ui/mod.rs b/crates/color-ui/src/ui/mod.rs index 16e5671cd4..2e6365b0f0 100644 --- a/crates/color-ui/src/ui/mod.rs +++ b/crates/color-ui/src/ui/mod.rs @@ -50,14 +50,14 @@ pub use area::{AreaShape, ColorArea, ColorAreaStyle}; pub use channels::finite_values; pub use choice::{ChosenColor, ColorChoice, ColorChoiceOutput, ColorChoiceWords, NamedColor}; pub use compare::{CompareSwatch, CompareSwatchOutput, CompareSwatchStyle}; -pub use disc::{ColorDisc, ColorDiscOutput, ColorDiscStyle, ColorDiscWords, DiscMove}; +pub use disc::{ColorDisc, ColorDiscOutput, ColorDiscStyle, ColorDiscWords, DiscHit, DiscLook, DiscMove, DiscRadius, patch_at}; pub use droppers::{DropperButton, DropperButtonOutput, DropperKind, DropperTool}; pub use eyedropper::{ EyedropperBar, EyedropperBarOutput, EyedropperOptions, EyedropperPick, EyedropperTool, EyedropperWords, SampleSize, SampleSource, }; pub use harmony::{ - HarmonyCommand, HarmonyMenu, HarmonyMenuAction, HarmonyPanel, HarmonyPanelOutput, HarmonyPanelState, HarmonyPicked, HarmonyWheel, - HarmonyWheelOutput, HarmonyWords, + GuideCell, GuideCellAt, HarmonyCommand, HarmonyMenu, HarmonyMenuAction, HarmonyPanel, HarmonyPanelOutput, HarmonyPanelState, HarmonyPicked, + HarmonyWheel, HarmonyWheelOutput, HarmonyWords, }; pub use hex::{HexPair, HexPairField, PairCodec}; pub use hud::{ColorHud, ColorHudOutput}; @@ -67,16 +67,20 @@ pub use paint_chip::{ FillKind, GradientPreview, ImagePreview, Paint, PaintChip, PaintChipOutput, PaintEditor, PaintLink, PaintLinkKind, PaintList, PaintListEvent, PaintListOptions, PaintListOutput, PaintRow, PaintWords, }; -pub use pair::{PairWell, SwatchPair, SwatchPairOutput, Well}; +pub use pair::{DropAccepts, PairWell, SwatchPair, SwatchPairOutput, Well}; pub use palette::{SwatchPalette, SwatchPaletteOutput}; pub use panel::{ - ColorPanel, ColorPanelCommand, ColorPanelMenu, ColorPanelMode, ColorPanelOutput, ColorPanelRamp, ColorPanelState, ColorPanelWords, PanelTarget, + ColorPanel, ColorPanelAction, ColorPanelCommand, ColorPanelLayout, ColorPanelMenu, ColorPanelMode, ColorPanelOutput, ColorPanelRamp, + ColorPanelShown, ColorPanelState, ColorPanelWords, PanelTarget, TintRow, }; -pub use picker::{ColorConstraint, ColorPicker, ColorPickerLayout, ColorPickerOutput, ColorPickerWords, PickedColor, ScreenPickGesture}; -pub use picker_dialog::{ColorPickerDialog, ColorPickerDialogWords, ColorPickerMemory, ColorPickerResult}; +pub use picker::{ + ChannelRow, ChannelRule, ChannelUnit, ColorConstraint, ColorPicker, ColorPickerLayout, ColorPickerOutput, ColorPickerWords, PickedColor, + ScreenPickGesture, TrackRamp, +}; +pub use picker_dialog::{ColorPickerDialog, ColorPickerDialogWords, ColorPickerMemory, ColorPickerResult, PickerLibrary, PickerSwatches}; pub use popover::{ColorPopover, ColorPopoverOutput}; pub use profile_prompts::{ProfileAction, ProfileAnswer, ProfileMismatchDialog, ProfileMode, ProfileQuestion, ProfileStatus, ProfileWords}; -pub use ramp::{ColorRamp, ColorRampOutput, ColorRampStyle, ColorRampWords, Gamut, RampKind, RampPick}; +pub use ramp::{ColorRamp, ColorRampOutput, ColorRampStyle, ColorRampWords, Gamut, RampKind, RampPick, RampRecolor}; pub use readout::{ChannelEdit, ColorReadout, ColorReadoutOutput, ColorReadoutWords, ReadoutChannel}; pub use sample_size::SampleSizeSelect; pub use samplers::{ @@ -91,5 +95,6 @@ pub use swatches::{ }; pub use warning::{ColorWarning, ColorWarningArrangement, ColorWarningChip, ColorWarningChipOutput, ColorWarningChipStyle}; pub use wheel::{ - ColorWheel, ColorWheelStyle, ColorWheelWords, WheelGeometry, WheelPart, hue_at, hue_direction, triangle_corners, triangle_point, triangle_sv, + ColorWheel, ColorWheelOutput, ColorWheelStyle, ColorWheelWords, WheelGeometry, WheelInner, WheelPart, hue_at, hue_direction, triangle_corners, + triangle_point, triangle_sv, }; diff --git a/crates/color-ui/src/ui/paint_chip.rs b/crates/color-ui/src/ui/paint_chip.rs index 098395b957..3539728e08 100644 --- a/crates/color-ui/src/ui/paint_chip.rs +++ b/crates/color-ui/src/ui/paint_chip.rs @@ -12,6 +12,7 @@ use std::collections::HashMap; use craft_behavior::Mixed; use craft_behavior::{Axis, EditEvent, EditEvents, Metrics, PartKey}; use craft_cms::convert::CmykConverter; +use craft_keymap::Mods; use craft_theme::Srgba; use craft_ui::buttons::Button; use craft_ui::choice::{ChoiceWords, Segmented, Swatch, SwatchFace}; @@ -21,9 +22,9 @@ use craft_ui::contract::{ }; use craft_ui::display::{Shade, Text}; use craft_ui::layout_components::Row; -use craft_ui::patterns::presets::{DefaultOpen, PresetBrowser, PresetEvent, PresetState, ThumbInfo}; +use craft_ui::patterns::presets::{DefaultOpen, PresetBrowser, PresetEvent, PresetRowMenu, PresetState, ThumbInfo}; use craft_ui::primitives::textures::CachedTexture; -use craft_ui::primitives::{ContentPainterCx, PaintShape, StrokeWidth}; +use craft_ui::primitives::{ContentPainterCx, FacePaint, PaintShape, StrokeWidth}; use craft_ui::runtime::env::{Env, Label}; use craft_ui::runtime::requests::ColorRequest; use craft_ui::style::{ComponentStyle, DataColor, FocusLook, StyleColor, StyleCx}; @@ -94,12 +95,22 @@ pub struct GradientPreview { /// Whether the host's gradient runs end to start. The ramp keeps the stops as given; the flag is part of the /// preview's value so that a Reverse edit, which leaves the stops alone, still changes the paint the chip sets. pub reverse: bool, + /// The host's painter for the preview's face; it paints over the checker, and `stops` still give the accessible + /// value. + pub face: Option, } impl GradientPreview { + /// The preview shows `face` in the paint well. + #[must_use] + pub fn face(self, face: FacePaint) -> Self { + let _ = face; + todo!("wg.W47") + } + /// A preview through `stops`, not reversed. pub fn new(stops: Vec<(f32, Srgba)>) -> Self { - GradientPreview { stops, reverse: false } + GradientPreview { stops, reverse: false, face: None } } /// The preview with the gradient reversed or not. @@ -242,6 +253,8 @@ pub struct PaintChipOutput { /// The Color Picker… button was pressed: the popover closed and the host opens the full picker with this request /// for that pass. pub pick_color: Option, + /// A click, Enter or Space on a chip without a popover: the modifiers held. + pub clicked: Option, } impl Outcome for PaintChipOutput { @@ -257,6 +270,23 @@ impl Outcome for PaintChipOutput { } } +/// The look of a paint well: the chip's own look fields. +#[allow(dead_code)] // P3(color-w4): wg.W47 +pub(crate) struct WellLook { + none_fill: StyleColor, + none_mark: StyleColor, + edge: StyleColor, + height: f32, +} + +/// One paint-well face for `PaintChip` and `SwatchPair`: none, solid, a gradient face or ramp, a pattern or a picture; +/// a face paints over the checker. +#[allow(dead_code)] // P3(color-w4): wg.W47 +pub(crate) fn paint_well(ui: &mut PaintUi<'_>, cx: &Cx<'_, impl Component>, well: Rect, paint: &Paint, style: &WellLook) { + let _ = (ui, cx, well, paint, style); + todo!("wg.W47") +} + /// A paint chip, a control high and 1.5 times as wide. /// /// - Look: a solid paint fills the chip over the checkerboard (alpha shows); a gradient is a @@ -298,6 +328,13 @@ pub struct PaintChip<'a> { /// A Color Picker… button at the end of the kind row opens the full picker. #[prop] full_picker: bool, + /// A click, Enter or Space opens the popover; on by default. Off, nothing opens and the chip reports the held + /// modifiers as [`clicked`](PaintChipOutput::clicked) (host-picker mode). + #[prop] + popover: bool, + /// The chip draws as a stroke ring through the one ring painter. + #[prop] + ring: bool, /// The request of the Color Picker… button, for this pass. pick_color: Option, } @@ -320,6 +357,8 @@ impl<'a> PaintChip<'a> { swatches: None, cmyk: None, full_picker: false, + popover: true, + ring: false, pick_color: None, } .label(label) @@ -516,10 +555,11 @@ impl Component for PaintChip<'_> { let groups: &[SwatchGroup] = groups; let rows = swatch_rows(groups, &swatch_words); let colors: HashMap<&str, &SwatchColor> = - groups.iter().flat_map(|g| g.entries.iter().map(|e| (e.name.as_str(), &e.color))).collect(); + // P3(color-w4): co.K28 + groups.iter().flat_map(|g| g.entries.iter().filter_map(|e| e.color().map(|c| (e.name.as_str(), c)))).collect(); let out = PresetBrowser::new(words.swatches.clone(), state.reborrowed(), &rows) .toolbar(false) - .row_menu(false) + .row_menu(PresetRowMenu::Off) // P3(color-w4): ap.AP5 .default_open(DefaultOpen::None) .room_height(Env::of(ui).tokens.size.control.sm * SWATCH_ROWS) .thumb(|painter: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, SwatchKey>| { @@ -627,7 +667,7 @@ impl Component for PaintChip<'_> { } fn finish(self, cx: Cx<'_, Self>) -> PaintChipOutput { - PaintChipOutput { edit: cx.edit_response(), screen_pick: self.screen_pick, pick_color: self.pick_color } + PaintChipOutput { edit: cx.edit_response(), screen_pick: self.screen_pick, pick_color: self.pick_color, clicked: None } } } diff --git a/crates/color-ui/src/ui/pair.rs b/crates/color-ui/src/ui/pair.rs index 3b1204c6db..9b983a1f4a 100644 --- a/crates/color-ui/src/ui/pair.rs +++ b/crates/color-ui/src/ui/pair.rs @@ -16,7 +16,7 @@ use egui::emath::GuiRounding as _; use egui::{Color32, CornerRadius, Painter, Pos2, Rect, Response, Shape, Stroke, StrokeKind, Vec2, pos2, vec2}; use super::popover::compact_picker; -use super::{ColorPicker, PickedColor, ScreenPickGesture}; +use super::{ColorPicker, Paint, PickedColor, ScreenPickGesture}; #[cfg(feature = "screen-testing")] mod stories; @@ -68,7 +68,7 @@ impl Well { #[non_exhaustive] pub struct PairWell { label: Label, - color: Mixed, + paint: Mixed, ring: bool, } @@ -76,7 +76,27 @@ impl PairWell { /// A well named `label` (its accessible name and tooltip, translated: "Foreground colour") of the host's `color`; /// `Mixed::Mixed` for a selection whose fills differ, shown as the mixed well. pub fn new(label: impl Into

{ /// The pair's response. pub response: Response, /// The active well after this pass: the host's, or the one the user chose. @@ -163,9 +193,13 @@ pub struct SwatchPairOutput { pub open: Option, /// The edit of the active well: another well made active is one `Set`. pub choice: EditResponse, + /// A payload released on a well that accepts it: the well and the payload. + pub dropped: Option<(Well, P)>, + /// The well a dragged payload that it accepts is over. + pub over: Option, } -impl Outcome for SwatchPairOutput { +impl

Outcome for SwatchPairOutput

{ type Value = Well; fn response(&self) -> &Response { @@ -197,8 +231,8 @@ impl Outcome for SwatchPairOutput { /// - The wells are one roving group: Tab arrives at the active well; Left and Up go to the primary one, Right and /// Down to the secondary one (mirrored right to left). #[derive(craft_ui::contract::Component, craft_ui::contract::Props)] -#[component(overlay)] -pub struct SwatchPair<'a> { +#[component(overlay, probe(SwatchPair<'static, u8>))] +pub struct SwatchPair<'a, P: Clone + Send + Sync + 'static = ()> { #[common] common: Common, wells: [PairWell; 2], @@ -225,6 +259,12 @@ pub struct SwatchPair<'a> { /// Sets up the popup's picker. #[prop(func = "Fn(ColorPicker<'a>) -> ColorPicker<'a>")] picker: Option>, + /// The payload each well drags past the slop (`None`: that well drags nothing). + #[prop] + drags: Option<[Option

; 2]>, + /// What each well accepts of a dragged payload: the well is a drop target for the payloads this allows. + #[prop(func = "Fn(Well, &P) -> bool")] + accepts: Option>, clicked: Option, double_clicked: Option, activated: bool, @@ -235,7 +275,7 @@ pub struct SwatchPair<'a> { screen_pick: Option, } -impl<'a> SwatchPair<'a> { +impl<'a, P: Clone + Send + Sync + 'static> SwatchPair<'a, P> { /// A pair named `label` of `wells`, primary first; `active` is the well in front. pub fn new(label: impl Into

; - fn style(cx: &StyleCx<'_>, _: SwatchPairStyleKey) -> SwatchPairStyle { + fn style(cx: &StyleCx<'_>, _: SwatchPairStyleKey

) -> SwatchPairStyle { let colors = &cx.tokens.color; let well = cx.tokens.size.icon.lg; let round = cx.tokens.shape.wells == WellShape::Round; @@ -352,7 +394,7 @@ impl Component for SwatchPair<'_> { let front = well == on_top; let at = flow.to_physical(logical.translate(rect.min.to_vec2())); let mut flags = Flags::empty(); - flags.set(Flags::MIXED, self.wells[i].color.same().is_none()); + flags.set(Flags::MIXED, self.wells[i].color().same().is_none()); flags.set(Flags::CHECKED, well == active); let shape = if cx.style.round { HitShape::circle(at.center(), at.width() / 2.0) } else { HitShape::Rect(at) }; let part = cx @@ -440,7 +482,7 @@ impl Component for SwatchPair<'_> { let popup = cx.popup("picker"); let opened = cx.memory::().0.map_or(Well::Primary, Well::of); let well = &self.wells[opened.index() as usize]; - let (color, name) = (*well.color.or(&Srgba::BLACK), well.label.clone()); + let (color, name) = (*well.color().or(&Srgba::BLACK), well.label.clone()); let setup = self.picker.as_ref(); let sampled = self.sampled; let shown = ui.show(popup, Overlay::popover(), |ui, _| { @@ -459,7 +501,7 @@ impl Component for SwatchPair<'_> { fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) { for (i, well) in self.wells.iter().enumerate() { - let value = match well.color.same() { + let value = match well.color().same() { Some(color) => color.to_hex(), None => cx.words::().swatch_mixed.as_str().to_owned(), }; @@ -493,7 +535,7 @@ impl Component for SwatchPair<'_> { if well == front { draw.surface_styled(at.expand(style.gap), &ground); } - match shown.color.same() { + match shown.color().same() { Some(color) if shown.ring => paint_ring(&draw, at, *color, style), color => { draw.swatch_well(at, style.radius, color.copied()); @@ -515,7 +557,7 @@ impl Component for SwatchPair<'_> { } } - fn finish(self, cx: Cx<'_, Self>) -> SwatchPairOutput { + fn finish(self, cx: Cx<'_, Self>) -> SwatchPairOutput

{ let open = cx.recall::().0.map(Well::of).filter(|_| !self.edit.is_empty() || self.edited.is_some()); let (response, active) = (cx.response.clone(), cx.value().copied().unwrap_or_default()); SwatchPairOutput { @@ -531,6 +573,8 @@ impl Component for SwatchPair<'_> { screen_pick: self.screen_pick, open, choice: cx.edit_response(), + dropped: None, + over: None, } } } diff --git a/crates/color-ui/src/ui/pair/stories.rs b/crates/color-ui/src/ui/pair/stories.rs index 69b07c192c..7625a5b37f 100644 --- a/crates/color-ui/src/ui/pair/stories.rs +++ b/crates/color-ui/src/ui/pair/stories.rs @@ -36,8 +36,10 @@ fn editing(ui: &mut Ui, data: &mut StoryData, names: [&'static str; 2], start: [ let defaults = [Srgba::rgb(0.0, 0.0, 0.0), Srgba::rgb(1.0, 1.0, 1.0)]; let state = data.value("colors", Colors { active: Well::Primary, colors: start }); let wells = [PairWell::new(names[0], state.colors[0]), PairWell::new(names[1], state.colors[1]).ring(ring)]; - let shown = - SwatchPair::new("Colours", wells, Bind::bound(&mut state.active)).swap_button("Swap colours").default_button("Default colours").show(ui); + let shown = SwatchPair::<()>::new("Colours", wells, Bind::bound(&mut state.active)) + .swap_button("Swap colours") + .default_button("Default colours") + .show(ui); // P3(widgets-w6): wg.W49 if shown.swap { state.colors.swap(0, 1); } @@ -69,13 +71,17 @@ fn swatch_pair_ring(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { #[story(SwatchPair<'static>, covers = [], drive = Drive::Never)] fn swatch_pair_host_picker(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - SwatchPair::new("Colours", wells(false), Bind::bound(data.value("active", Well::Primary))).popover(false).click_activates(false).show(ui).into() + SwatchPair::<()>::new("Colours", wells(false), Bind::bound(data.value("active", Well::Primary))) + .popover(false) + .click_activates(false) + .show(ui) + .into() // P3(widgets-w6): wg.W49 } #[story(SwatchPair<'static>, covers = [Mixed], drive = Drive::Never)] fn swatch_pair_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let wells = [PairWell::new("Fill", Mixed::::Mixed), PairWell::new("Stroke", Srgba::rgb(0.1, 0.3, 0.8)).ring(true)]; - SwatchPair::new("Fill and stroke", wells, Bind::bound(data.value("active", Well::Primary))).show(ui).into() + SwatchPair::<()>::new("Fill and stroke", wells, Bind::bound(data.value("active", Well::Primary))).show(ui).into() // P3(widgets-w6): wg.W49 } /// Opens the picker of the focused well with Enter. @@ -87,14 +93,14 @@ fn open_picker(fixture: &mut Fixture) { #[story(SwatchPair<'static>, covers = [Open], drive = Drive::Custom(open_picker))] fn swatch_pair_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - SwatchPair::new("Colours", wells(false), Bind::bound(data.value("active", Well::Primary))).show(ui).into() + SwatchPair::<()>::new("Colours", wells(false), Bind::bound(data.value("active", Well::Primary))).show(ui).into() // P3(widgets-w6): wg.W49 } #[story(SwatchPair<'static>, covers = [Invalid], drive = Drive::Never)] fn swatch_pair_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let refuse_secondary = |well: &Well| if *well == Well::Secondary { Validity::Refuse(Message::new("Only the foreground can be edited")) } else { Validity::Ok }; - SwatchPair::new("Colours", wells(false), Bind::bound(data.value("active", Well::Secondary)).check(refuse_secondary)).show(ui).into() + SwatchPair::<()>::new("Colours", wells(false), Bind::bound(data.value("active", Well::Secondary)).check(refuse_secondary)).show(ui).into() // P3(widgets-w6): wg.W49 } /// The pair in a tool rail's footer, as PhotoCraft's colour chips: the gap round the front well takes the rail's chrome. @@ -106,7 +112,7 @@ fn swatch_pair_tool_rail(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let mut shown = None; ToolRail::new("Tools", &slots, &0, &last).show_rail(ui, |ui, _| { shown = Some( - SwatchPair::new("Colours", wells.clone(), Bind::bound(&mut *active)) + SwatchPair::<()>::new("Colours", wells.clone(), Bind::bound(&mut *active)) // P3(widgets-w6): wg.W49 .popover(false) .swap_button("Swap colours") .default_button("Default colours") diff --git a/crates/color-ui/src/ui/palette.rs b/crates/color-ui/src/ui/palette.rs index c974505568..db62b23c9f 100644 --- a/crates/color-ui/src/ui/palette.rs +++ b/crates/color-ui/src/ui/palette.rs @@ -3,8 +3,8 @@ use craft_behavior::{EditEvent, Mixed, Selection}; use craft_theme::Srgba; -use craft_ui::choice::SwatchTable; -use craft_ui::contract::{Bind, Held, NoValue, Outcome, Pattern, ShowContainer as _}; +use craft_ui::choice::{SwatchSpacing, SwatchTable}; +use craft_ui::contract::{Bind, Held, ListDrag, NoValue, Outcome, Pattern, ShowContainer as _}; use craft_ui::layout_components::Stack; use craft_ui::runtime::env::Label; use egui::{Response, Ui}; @@ -57,6 +57,20 @@ impl<'a> SwatchPalette<'a> { SwatchPalette { label: label.into(), color, swatches } } + /// The gap between the cells, passed on to its `SwatchTable`. + #[must_use] + pub fn spacing(self, spacing: SwatchSpacing) -> Self { + let _ = spacing; + todo!("co.K7") + } + + /// The payload a cell drags, passed on to its `SwatchTable`. + #[must_use] + pub fn drag_payload(self, map: impl Fn(&ListDrag) -> Option

+ Send + Sync + 'static) -> Self { + let _ = map; + todo!("co.K7") + } + /// Shows the palette. pub fn show(self, ui: &mut Ui) -> SwatchPaletteOutput { let SwatchPalette { label, color, swatches } = self; diff --git a/crates/color-ui/src/ui/panel.rs b/crates/color-ui/src/ui/panel.rs index acb53d2a1d..4acac724e1 100644 --- a/crates/color-ui/src/ui/panel.rs +++ b/crates/color-ui/src/ui/panel.rs @@ -25,7 +25,7 @@ use super::channels::finite_values; use super::picker::{ChannelRow, ChannelRule, ChannelUnit, channel_name}; use super::{ AreaMode, ColorArea, ColorPickerDialogWords, ColorRamp, ColorReadout, ColorStrip, ColorWarning, ColorWarningArrangement, ColorWarningChip, - ColorWheel, PairWell, PickedColor, RampKind, SwatchPair, Well, + ColorWheel, Gamut, PairWell, PickedColor, RampKind, RampRecolor, SwatchPair, SwatchPairOutput, Well, }; use crate::{CmykModel, GrayModel, not_web_safe}; @@ -88,6 +88,20 @@ pub enum ColorPanelMode { } impl ColorPanelMode { + /// The modes of the FillStroke layout's menu, in its order; the Shift-click on the spectrum cycles through them. + pub const FILL_STROKE: [ColorPanelMode; 5] = [ + ColorPanelMode::GrayscaleSlider, + ColorPanelMode::RgbSliders, + ColorPanelMode::HsbSliders, + ColorPanelMode::CmykSliders, + ColorPanelMode::WebColorSliders, + ]; + + /// The mode after this one in [`FILL_STROKE`](Self::FILL_STROKE); a mode outside the list goes to the first. + pub fn fill_stroke_next(self) -> ColorPanelMode { + todo!("co.K20") + } + /// Every mode, in the panel menu's order (one section, no separator). pub const ALL: [ColorPanelMode; 9] = [ ColorPanelMode::HueCube, @@ -179,7 +193,7 @@ impl ColorPanelRamp { } /// The Color panel's settings, kept across runs (settings section `color_panel`). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] pub struct ColorPanelState { @@ -191,6 +205,89 @@ pub struct ColorPanelState { pub ramp: ColorPanelRamp, /// Make Ramp Web Safe: the ramp shows and picks web colours only. pub web_safe_ramp: bool, + /// Hide Options: the FillStroke layout keeps the proxy and the spectrum only. + pub hide_options: bool, + /// The FillStroke layout shows the Recent Colors slot. + pub recent_colors: bool, + /// The R, G and B rows count percents, 0 to 100, in place of 0 to 255. + pub rgb_percent: bool, +} + +impl Default for ColorPanelState { + fn default() -> Self { + ColorPanelState { + background: false, + mode: ColorPanelMode::default(), + ramp: ColorPanelRamp::default(), + web_safe_ramp: false, + hide_options: false, + recent_colors: true, + rgb_percent: false, + } + } +} + +/// How a [`ColorPanel`] arranges its body. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum ColorPanelLayout { + /// The foreground over the background wells with one view of the edited colour (Photoshop's panel). + #[default] + ForegroundBackground, + /// The fill and stroke proxy, the rows of the shown mode, the Spectrum ramp and the Recent Colors slot. + FillStroke, +} + +/// What rows a [`ColorPanel`] shows: the host's model rule. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub enum ColorPanelShown { + /// The channel rows of this mode. + Mode(ColorPanelMode), + /// The Tint row of a swatch-linked colour. + Tint(TintRow), + /// No rows. + Empty, +} + +/// The Tint row of a swatch-linked colour: a chip with the global corner and the spot dot, the name and the T row. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct TintRow { + /// The swatch's name. + pub name: Label, + /// The swatch's colour at full strength. + pub base: Srgba, + /// The swatch is global: the chip has the global corner. + pub global: bool, + /// The swatch is a spot colour: the chip has the spot dot. + pub spot: bool, + /// The tint, 0 to 100. + pub tint: f32, +} + +impl TintRow { + /// A tint of `base` named `name`, neither global nor spot. + pub fn new(name: impl Into

+ Send + Sync + 'static) -> Self { + let _ = map; + todo!("co.K18") + } + + /// The host's gamut for the out-of-gamut chip and the spectrum. + #[must_use] + pub fn gamut(self, gamut: Gamut<'a>) -> Self { + let _ = gamut; + todo!("co.K18") + } + /// Shows the panel and returns this pass's edits and requests. pub fn show(self, ui: &mut Ui) -> ColorPanelOutput { let ColorPanel { state, colors, cmyk, dynamic } = self; @@ -357,7 +513,7 @@ impl<'a> ColorPanel<'a> { held.write(cx, &before, now, words.title.as_str()); } }); - ColorPanelOutput { response: shown.output, edits, pick_color, add_to_swatches } + ColorPanelOutput { response: shown.output, edits, pick_color, add_to_swatches, pair: None, tint: None, none: None, recolor: None } } } @@ -414,6 +570,21 @@ pub enum ColorPanelCommand { /// The ramp shows and picks web colours only. #[command(label = "Make Ramp Web Safe", kind = "toggle")] WebSafeRamp, + /// Hide or show the options of the FillStroke layout. + #[command(label = "Hide Options")] + ToggleOptions, + /// Show the Recent Colors slot. + #[command(label = "Show Recent Colors", kind = "toggle")] + ShowRecentColors, + /// Invert the edited colour. + #[command(label = "Invert")] + Invert, + /// Replace the edited colour by its complement. + #[command(label = "Complement")] + Complement, + /// Create a swatch of the edited colour. + #[command(label = "Create New Swatch…")] + NewSwatch, } impl ColorPanelMode { @@ -452,7 +623,8 @@ pub struct ColorPanelMenu; impl ColorPanelMenu { /// The rows: the nine views, a separator, Copy Color as HTML and Copy Color's Hex Code, a separator, the four ramps, /// a separator, Make Ramp Web Safe. - pub fn rows() -> Vec { + pub fn rows(layout: ColorPanelLayout) -> Vec { + let _ = layout; // P3(color-w3): co.K22 let row = |command: ColorPanelCommand| PanelRow::Command(CommandRef::from(command)); let mut rows: Vec = ColorPanelMode::ALL.iter().map(|mode| row(mode.command())).collect(); rows.extend([PanelRow::Separator, row(ColorPanelCommand::CopyHtml), row(ColorPanelCommand::CopyHex), PanelRow::Separator]); @@ -469,7 +641,13 @@ impl ColorPanelMenu { } /// The state of each command: the current view and ramp checked, Make Ramp Web Safe checked when on. - pub fn states(state: &ColorPanelState) -> Vec<(ColorPanelCommand, CommandState)> { + pub fn states( + layout: ColorPanelLayout, + state: &ColorPanelState, + shown: &ColorPanelShown, + has_color: bool, + ) -> Vec<(ColorPanelCommand, CommandState)> { + let _ = (layout, shown, has_color); // P3(color-w3): co.K22 let commands = ColorPanelMode::ALL.iter().map(|mode| mode.command()); let commands = commands.chain([ColorPanelCommand::CopyHtml, ColorPanelCommand::CopyHex]); let commands = commands.chain(ColorPanelRamp::ALL.iter().map(|ramp| ramp.command())).chain([ColorPanelCommand::WebSafeRamp]); @@ -495,7 +673,7 @@ impl ColorPanelMenu { /// Carries out `command`: sets the view or the ramp, toggles Make Ramp Web Safe, or returns the text of `edited` /// for the clipboard, as HTML (`color="#rrggbb"`) or as a hex code (`rrggbb`). - pub fn run_command(state: &mut ColorPanelState, command: ColorPanelCommand, edited: Srgba) -> Option { + pub fn run_command(state: &mut ColorPanelState, command: ColorPanelCommand, edited: Srgba) -> Option { if let Some(mode) = ColorPanelMode::ALL.into_iter().find(|mode| mode.command() == command) { state.mode = mode; } else if let Some(ramp) = ColorPanelRamp::ALL.into_iter().find(|ramp| ramp.command() == command) { @@ -503,9 +681,14 @@ impl ColorPanelMenu { } else { match command { ColorPanelCommand::WebSafeRamp => state.web_safe_ramp = !state.web_safe_ramp, - ColorPanelCommand::CopyHtml => return Some(format!("color=\"{}\"", Srgba::from_rgb_array([edited.r, edited.g, edited.b]).to_hex())), + // P3(color-w3): co.K22 + ColorPanelCommand::CopyHtml => { + return Some(ColorPanelAction::Copy(format!("color=\"{}\"", Srgba::from_rgb_array([edited.r, edited.g, edited.b]).to_hex()))); + } ColorPanelCommand::CopyHex => { - return Some(Srgba::from_rgb_array([edited.r, edited.g, edited.b]).to_hex().trim_start_matches('#').to_owned()); + return Some(ColorPanelAction::Copy( + Srgba::from_rgb_array([edited.r, edited.g, edited.b]).to_hex().trim_start_matches('#').to_owned(), + )); } _ => {} } @@ -596,7 +779,8 @@ impl Body<'_> { let was = if self.now.background { Well::Secondary } else { Well::Primary }; let mut active = was; let wells = [PairWell::new(self.words.foreground.clone(), self.colors[0]), PairWell::new(self.words.background.clone(), self.colors[1])]; - let pair = SwatchPair::new(self.words.wells.clone(), wells, Bind::bound(&mut active)).popover(false).frame_active(true).show(ui); + // P3(color-w3): wg.W49 + let pair = SwatchPair::<()>::new(self.words.wells.clone(), wells, Bind::bound(&mut active)).popover(false).frame_active(true).show(ui); self.now.background = active == Well::Secondary; if pair.clicked.as_ref() == Some(&was) { let title = match self.target { @@ -766,7 +950,8 @@ impl Body<'_> { fn wheel(&mut self, ui: &mut Ui) { let values = self.values(&HsbModel); let wheel = ColorWheel::new(self.words.color_wheel.clone(), Bind::given(values)).show(ui); - for event in wheel.events { + // P3(color-w3): wg.W46 + for event in wheel.edit.events { self.model_event(&HsbModel, event); } let add = Row::new().align(RowAlign::End).show(ui, |ui, _| { @@ -790,7 +975,7 @@ impl Body<'_> { let ramp = ColorRamp::new(self.words.color_ramp.clone(), self.now.ramp.kind(), Bind::kept()) .kind_name(self.now.ramp.label(self.words)) .ends([self.colors[0], self.colors[1]]) - .gamut(gamut) + .gamut(Gamut::new(gamut)) // P3(color-w3): co.K1 .gamut_revision(hasher.finish()) .web_safe(self.now.web_safe_ramp) .sizing(Sizing::Fill) @@ -832,14 +1017,16 @@ mod tests { fn color_panel_menu_checks_follow_the_state() { let state = ColorPanelState { mode: ColorPanelMode::CmykSliders, ramp: ColorPanelRamp::GrayscaleRamp, web_safe_ramp: true, ..Default::default() }; - let checked: Vec = ColorPanelMenu::states(&state) + // P3(color-w3): co.K22 + let (layout, shown) = (ColorPanelLayout::ForegroundBackground, ColorPanelShown::Mode(state.mode)); + let checked: Vec = ColorPanelMenu::states(layout, &state, &shown, true) .into_iter() .map(|(command, _)| command) .filter(|c| ColorPanelMenu::checked(&state, *c) == Some(true)) .collect(); assert_eq!(checked, [ColorPanelCommand::CmykSliders, ColorPanelCommand::GrayscaleRamp, ColorPanelCommand::WebSafeRamp]); assert_eq!(ColorPanelMenu::checked(&state, ColorPanelCommand::CopyHex), None); - for (command, published) in ColorPanelMenu::states(&state) { + for (command, published) in ColorPanelMenu::states(layout, &state, &shown, true) { let expected = ColorPanelMenu::checked(&state, command).map_or_else(CommandState::new, |on| CommandState::new().checked(on)); assert_eq!(published, expected, "{command:?}"); } diff --git a/crates/color-ui/src/ui/picker/channel.rs b/crates/color-ui/src/ui/picker/channel.rs index a412ba1135..c3e5486026 100644 --- a/crates/color-ui/src/ui/picker/channel.rs +++ b/crates/color-ui/src/ui/picker/channel.rs @@ -17,33 +17,41 @@ use egui::{Color32, CornerRadius, Ui, Vec2}; /// How a channel's value steps and settles: a channel's or the alpha's. #[derive(Clone, Debug, PartialEq)] -pub(crate) struct ChannelRule { +pub struct ChannelRule { + /// The values the channel takes, from its least to its greatest. pub range: RangeInclusive, + /// One arrow key's step. pub step: f64, + /// The decimals the number field shows. pub decimals: u8, } impl ChannelRule { /// The alpha row's rule: 0 to 100 %, whole percents. - pub(crate) const ALPHA: ChannelRule = ChannelRule { range: RangeInclusive::new(0.0, 100.0), step: 1.0, decimals: 0 }; + pub const ALPHA: ChannelRule = ChannelRule { range: RangeInclusive::new(0.0, 100.0), step: 1.0, decimals: 0 }; - pub(crate) fn of(channel: &Channel) -> ChannelRule { + /// The rule of `channel`. + pub fn of(channel: &Channel) -> ChannelRule { ChannelRule { range: f64::from(channel.min)..=f64::from(channel.max), step: f64::from(channel.step), decimals: channel.decimals } } } /// What a channel's number counts. #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum ChannelUnit { +pub enum ChannelUnit { + /// No unit. None, + /// Percent. Percent, + /// Degrees. Degrees, /// Any other unit text a model declares. Text(&'static str), } impl ChannelUnit { - pub(crate) fn of(unit: &'static str) -> ChannelUnit { + /// The unit a model declares as text. + pub fn of(unit: &'static str) -> ChannelUnit { match unit { "" => ChannelUnit::None, "%" => ChannelUnit::Percent, @@ -77,7 +85,7 @@ pub struct TrackRampStyle { /// transparency checkerboard where `checker` is set. #[derive(Clone, craft_ui::contract::Component)] #[component(content_painter)] -pub(crate) struct TrackRamp { +pub struct TrackRamp { #[common] common: Common, stops: Vec, @@ -85,7 +93,8 @@ pub(crate) struct TrackRamp { } impl TrackRamp { - pub(crate) fn new(stops: Vec, checker: bool) -> Self { + /// A ramp through `stops`, over the checkerboard where `checker` is set. + pub fn new(stops: Vec, checker: bool) -> Self { TrackRamp { common: Common::new(), stops, checker } } } @@ -159,7 +168,7 @@ pub(crate) fn channel_slider<'a>( /// where one is given, "C"), which scrubs the value, the slider over the channel's colours with the pointer under its /// track, and the number field with its unit at the end, as wide as its widest value. #[derive(craft_ui::contract::Pattern)] -pub(crate) struct ChannelRow<'a> { +pub struct ChannelRow<'a> { label: Label, /// The text shown in place of the label: the channel's short label. short: Option<&'static str>, @@ -172,35 +181,45 @@ pub(crate) struct ChannelRow<'a> { } impl<'a> ChannelRow<'a> { - pub(crate) fn new(label: impl Into

/.log` with `RUST_LOG`-style filters, rotation to `.1`/`.2`, per-instance logs while another instance runs, a size cap; `logs::crash`: the panic hook, crash log, last panic for the error window, and `catch`. | | always | `session::Session` and `SessionKeeper`: the documents open at the last quit and where the user was in each, stored in the app's settings (serde) for a "Reopen Last Session" preference; `to_reopen` skips what is already open; a stored list longer than 64 documents is cut. No egui. | | `usage` | `usage::sample`: the process's resident memory and the memory it may still use (`MemorySample`, `None` when unknown), for the status readout's Scratch and Efficiency items. Linux reads `/proc`; other platforms return `None`. | -| always | `open::FileIntake` with `IntakeSender` (the app's Apple Events and second-instance hand-over feed it): one queue for files the OS asks the app to open and files dropped on the window (`DroppedFile`, `DropTarget`: canvas, tab strip or window); `natural_cmp` and `same_file` for opening order and duplicates; `reveal` and `open_external`; the shared open-error texts. No egui. | +| always | `open::FileIntake` with `IntakeSender` (the app's Apple Events and second-instance hand-over feed it): one queue for files the OS asks the app to open and files dropped on the window (`DroppedFile`); `natural_cmp` and `same_file` for opening order and duplicates; `reveal`, `open_external`, `open_with` and `is_application`; the shared open-error texts. No egui. | | always | `autosave::Autosave` (the timer: which documents are due, results by revision), `recovery_dir`, `adopt_legacy_recovery` and `RecoveryStore`: the recovery folder of copies with a JSON sidecar each (`RecoveryEntry`, the fields craft-ui's `RecoveryDialog` lists), `AUTOSAVE_FAILED`. The app serializes its documents. | | `clipboard` | `clipboard::Clipboard` over a `ClipboardBackend`: every copy and paste goes through it, with size limits (`ClipboardLimits`, `TooLarge`), a fence that keeps synthetic (automation) input from replacing what the user copied, and `holds_ours` to tell the app's own copy from another app's. `SystemClipboard` (arboard) reads and writes text, HTML, one bitmap and copied files; `EventClipboard` is the browser's, fed from paste events (`flavors_from_event`, `copy_through_egui` with `ui`). `EventClipboard` keeps an offered paste for the pass it was offered in and counts passes itself (`EventClipboard::for_egui` uses egui's pass number), so a menu Paste in a later pass finds nothing and the app has nothing to call at the end of a pass. A write reports which flavor the backend wrote, and `holds_ours` compares that one. The web writes only the best flavor (eframe makes each copy command its own `navigator.clipboard` write, so a second replaces the first). `has` never reads or decodes: it asks Windows and macOS for the formats on offer, Wayland for the offer's MIME types (`wl-clipboard-rs`) and X11 for the `TARGETS` list (`x11rb`); a bitmap counts only as `image/png`, the one arboard reads on Linux. `ClipboardProbe` asks a second handle on a worker thread whether Paste has anything, so a slow owner never stalls a frame. Bitmaps are read as straight RGBA8, not PNG: the `BITMAP` and `RGBA8` reads return an `image/x-rgba8` flavor (width and height as little-endian `u32`s, then the pixels) and `read_image` returns `ClipboardImage`; the crate has no PNG encoder, and `SystemClipboard::decoder` takes the app's PNG decoder for writes. SVG, PDF and RTF flavors are neither written nor read by `SystemClipboard` (a write of only those fails with `Other`); a bitmap offered only as `image/jpeg` or `image/bmp` on Wayland reads as `None`. | | always | `watch::FileWatch` and `Changed`: open files that changed on disk. One worker thread (`craft-file-watch`) compares each file's metadata (`FileStamp`) every 250 ms and sleeps while nothing is watched; a changed file is reported once it has settled and, with `ReadPolicy::Whole`, looks complete. The app's own saves are recognised by `known_now`; `disk_differs` answers at Save time; `take_changes` runs on the frame the worker's `Wake` asks for. | diff --git a/crates/platform/src/clipboard/backend.rs b/crates/platform/src/clipboard/backend.rs index c9becf3ca1..502b2fcf6e 100644 --- a/crates/platform/src/clipboard/backend.rs +++ b/crates/platform/src/clipboard/backend.rs @@ -40,8 +40,7 @@ pub trait ClipboardBackend: Send { /// As [`read`](Self::read), but the slow part (the Wayland pipe, a DIB conversion) is left in the returned /// closure, which runs off the UI thread. Reads now and wraps the result by default. fn read_later(&mut self, mimes: &[&str], limit: u64) -> Result Option + Send>>, ClipboardError> { - let _ = (mimes, limit); - todo!("sh.N1") + Ok(self.read(mimes, limit)?.map(|flavor| Box::new(move || Some(flavor)) as Box Option + Send>)) } /// Whether the clipboard can be read at any time; `false` where it can be read only inside a paste event (the /// web). diff --git a/crates/platform/src/clipboard/facade.rs b/crates/platform/src/clipboard/facade.rs index 02b6780936..a71132d91d 100644 --- a/crates/platform/src/clipboard/facade.rs +++ b/crates/platform/src/clipboard/facade.rs @@ -92,9 +92,8 @@ impl Clipboard { /// The first of `mimes` the clipboard holds, within [`ClipboardLimits::text_bytes`] for text /// types and [`ClipboardLimits::image_bytes`] for the rest. pub fn read(&mut self, mimes: &[&str]) -> Result, ClipboardError> { - let limit = if mimes.iter().all(|mime| is_text(mime)) { self.limits.text_bytes } else { self.limits.image_bytes }; - let Some(flavor) = self.backend.read(mimes, limit)? else { return Ok(None) }; - let cap = if is_text(&flavor.mime) { self.limits.text_bytes } else { self.limits.image_bytes }; + let Some(flavor) = self.backend.read(mimes, read_limit(&self.limits, mimes))? else { return Ok(None) }; + let cap = read_limit(&self.limits, &[&*flavor.mime]); if flavor.data.len() as u64 > cap { return Err(ClipboardError::TooLarge { limit: cap }); } @@ -102,10 +101,11 @@ impl Clipboard { } /// As [`read`](Self::read), with its limits and gates, but the slow part of the read is the returned closure, - /// which runs off the UI thread. + /// which runs off the UI thread. A flavour over its limit, found only once the closure has made it, is `None`. pub fn read_later(&mut self, mimes: &[&str]) -> Result Option + Send>>, ClipboardError> { - let _ = mimes; - todo!("sh.N1") + let Some(make) = self.backend.read_later(mimes, read_limit(&self.limits, mimes))? else { return Ok(None) }; + let limits = self.limits; + Ok(Some(Box::new(move || make().filter(|flavor| flavor.data.len() as u64 <= read_limit(&limits, &[&*flavor.mime]))))) } /// Whether the clipboard can be read at any time; `false` where it can be read only inside a paste event (the @@ -202,6 +202,11 @@ pub(super) fn is_text(mime: &str) -> bool { mime.starts_with("text/") || mime == SVG } +/// The byte limit a read of `mimes` runs under: text's when every type is text, else the image limit. +fn read_limit(limits: &ClipboardLimits, mimes: &[&str]) -> u64 { + if mimes.iter().all(|mime| is_text(mime)) { limits.text_bytes } else { limits.image_bytes } +} + pub(super) fn hash_bytes(bytes: &[u8]) -> u64 { let mut hasher = std::collections::hash_map::DefaultHasher::new(); bytes.hash(&mut hasher); diff --git a/crates/platform/src/clipboard/probe.rs b/crates/platform/src/clipboard/probe.rs index 007cc59bbd..4d5b54525c 100644 --- a/crates/platform/src/clipboard/probe.rs +++ b/crates/platform/src/clipboard/probe.rs @@ -8,7 +8,9 @@ use super::backend::ClipboardBackend; /// How often the probe's worker looks at the clipboard while the UI wants to know: 250 ms. pub const PROBE_INTERVAL: Duration = Duration::from_millis(250); -/// How long dropping the probe waits for the worker to let go of its handle: 27 s. +/// How long dropping the probe waits for the worker to let go of its handle: 27 s, an unanswered X11 read's limit +/// plus the worker's own stop, so on X11 the app's handle is the last one dropped and hands the copy to the clipboard +/// manager. The wait ends as soon as the worker drops its handle. pub const PROBE_STOP_WAIT: Duration = Duration::from_secs(27); /// Whether Paste has something to take from the system clipboard, asked on a worker thread. diff --git a/crates/platform/src/clipboard_tests.rs b/crates/platform/src/clipboard_tests.rs index 990189b32c..909a709540 100644 --- a/crates/platform/src/clipboard_tests.rs +++ b/crates/platform/src/clipboard_tests.rs @@ -56,3 +56,68 @@ fn synthetic_input_never_replaces_what_the_user_copied() { assert_eq!(clipboard.write_text("mine").unwrap(), Written::Written); assert_eq!(clipboard.read_text().unwrap().as_deref(), Some("mine")); } + +// A paste read off the UI thread keeps a read's limits: the fake enforces none, so a flavour over +// the text limit gets through only if `read_later` drops its gate. +#[test] +fn a_later_read_keeps_the_limits_of_a_read_now() { + let fake = Fake::default(); + let mut clipboard = Clipboard::new(fake.clone()).limits(ClipboardLimits { text_bytes: 8, ..ClipboardLimits::DEFAULT }); + assert!(clipboard.read_later(&[TEXT]).unwrap().is_none(), "nothing copied"); + fake.copy_elsewhere(vec![Flavor::text("short")]); + let make = clipboard.read_later(&[TEXT]).unwrap().unwrap(); + assert_eq!(std::thread::spawn(make).join().unwrap().map(|f| f.data), Some(b"short".to_vec())); + fake.copy_elsewhere(vec![Flavor::text("longer than eight bytes")]); + let make = clipboard.read_later(&[TEXT]).unwrap().unwrap(); + assert!(make().is_none(), "over the text limit"); +} + +// The web's clipboard is read only inside a paste event; an app that reads it at any other time +// pastes nothing. +#[test] +fn only_a_clipboard_outside_paste_events_is_readable_any_time() { + assert!(Clipboard::new(Fake::default()).readable_any_time()); + assert!(!Clipboard::new(EventClipboard::new(|| 0, |_| Ok(0))).readable_any_time()); +} + +/// A backend that takes longer to drop than the probe's old 250 ms wait, as an X11 handle does +/// while it hands the copy to the clipboard manager. +struct SlowToDrop(Arc); + +impl ClipboardBackend for SlowToDrop { + fn write(&mut self, _flavors: &[Flavor]) -> Result { + Ok(0) + } + fn read(&mut self, _mimes: &[&str], _limit: u64) -> Result, ClipboardError> { + Ok(None) + } + fn read_image(&mut self, _limit: u64) -> Result, ClipboardError> { + Ok(None) + } + fn read_files(&mut self, _limit: usize) -> Result>, ClipboardError> { + Ok(None) + } + fn has(&mut self, _mimes: &[&str]) -> bool { + false + } +} + +impl Drop for SlowToDrop { + fn drop(&mut self) { + std::thread::sleep(std::time::Duration::from_millis(400)); + self.0.store(true, std::sync::atomic::Ordering::SeqCst); + } +} + +// Quitting drops the probe before the app's own handle: a probe that stopped waiting early would +// leave its handle the last one alive, and on X11 the copy would be lost at exit. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn dropping_the_probe_waits_until_its_handle_has_dropped() { + let dropped = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let handle = dropped.clone(); + let probe = ClipboardProbe::start(Box::new(move || Box::new(SlowToDrop(handle)) as Box), vec![TEXT], craft_host::Wake::new(|| {})) + .unwrap(); + drop(probe); + assert!(dropped.load(std::sync::atomic::Ordering::SeqCst)); +} diff --git a/crates/platform/src/open.rs b/crates/platform/src/open.rs index 6d8990d2e3..a0f32f152d 100644 --- a/crates/platform/src/open.rs +++ b/crates/platform/src/open.rs @@ -2,15 +2,15 @@ //! //! - [`FileIntake`]: one queue for files the OS asks the app to open (Finder double-click, Open //! With, a Dock drop, a second launch handing its paths to the first) and files dropped on the -//! window, with where they were dropped ([`DropTarget`]). +//! window. //! - [`natural_cmp`], [`same_file`]: the order files open in and the check that keeps an open //! file from opening twice. //! - [`OPEN_FAILED`] and the other [`PlatformText`]s: the open errors every app words the same way. //! - [`reveal`], [`open_external`]: show a file in the system file manager; open a file or URL //! with the system's handler. +//! - [`open_with`], [`is_application`]: open a file in a chosen application; whether a path is one. //! -//! No egui: the app converts egui's dropped files into [`DroppedFile`]s and reads the pointer -//! position for [`DropTarget`] itself. +//! No egui: the app converts egui's dropped files into [`DroppedFile`]s itself. use std::collections::VecDeque; #[cfg(not(target_arch = "wasm32"))] @@ -43,21 +43,6 @@ pub const REVEAL_FAILED: PlatformText = PlatformText { id: "open.revealFailed", /// Every [`PlatformText`] of this module, for the missing-translation report ([`crate::texts`]). pub const TEXTS: &[PlatformText] = &[OPEN_FAILED, PLACE_FAILED, PATH_NOT_UNICODE_OPEN, PATH_NOT_UNICODE_SAVE, FILE_GONE, REVEAL_FAILED]; -/// Where files dropped on the window land. winit's drops carry no position, so the app finds it -/// from the pointer (PhotoCraft asks the OS while files hover); unknown counts as -/// [`Elsewhere`](DropTarget::Elsewhere). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum DropTarget { - /// The active document's canvas: each file is placed as a layer, one at a time, each in Free - /// Transform (Photoshop's Place Embedded). Preset files (brushes, gradients) still open into - /// their libraries. - Canvas, - /// The tab strip: opened with their tabs from this position. - Tabs(usize), - /// Anywhere else (panels, a dialog, no document): opened like File › Open. - Elsewhere, -} - /// A dropped file as the app got it. On the web there is no path, only the name and bytes. #[derive(Clone, Debug, PartialEq)] pub struct DroppedFile { @@ -75,12 +60,10 @@ pub enum Intake { /// The OS asked to open these absolute paths: open them like File › Open, focusing a /// document that is already open instead of opening it again. Open(Vec), - /// Files dropped on the window, in drop order, with where they landed. + /// Files dropped on the window, in drop order. Dropped { /// The dropped files. files: Vec, - /// Where they landed. - target: DropTarget, }, } @@ -123,7 +106,7 @@ impl IntakeSender { /// let (intake, sender) = FileIntake::new(Wake::new(move || ctx.request_repaint())); /// // macOS: the app's Apple Event handler calls `sender.open(paths)`; elsewhere its single-instance socket does. /// // each frame: -/// intake.dropped(ctx.input(|i| i.raw.dropped_files.iter().map(to_dropped).collect()), target); +/// intake.dropped(ctx.input(|i| i.raw.dropped_files.iter().map(to_dropped).collect())); /// for batch in intake.take() { app.open_batch(batch); } /// ``` pub struct FileIntake { @@ -145,9 +128,9 @@ impl FileIntake { } /// Queues files dropped this frame; an empty list is ignored. - pub fn dropped(&self, files: Vec, target: DropTarget) { + pub fn dropped(&self, files: Vec) { if !files.is_empty() { - push(&self.queue, Intake::Dropped { files, target }); + push(&self.queue, Intake::Dropped { files }); } } @@ -329,17 +312,87 @@ pub fn open_external(target: &str) -> Result<(), String> { /// Opens `target` in the application at `app` (Edit Original's chosen application), never through a shell: on /// macOS `open -a app target`, waiting at most 2 s for Launch Services to refuse; elsewhere `app` runs with /// `target` as its only argument, without waiting. A path holding `"` is refused on Windows. +/// +/// A missing `app` is [`ErrorKind::NotFound`](std::io::ErrorKind::NotFound), so a caller can fall back to its default +/// editor; a path that is not an application ([`is_application`]) is `InvalidInput`, and nothing is started. +// PLAN: the contract row sh.B2a says `Result<(), String>`; the app needs the `NotFound` kind, so the error is `io::Error`. #[cfg(not(target_arch = "wasm32"))] pub fn open_with(app: &Path, target: &Path) -> std::io::Result<()> { - let _ = (app, target); - todo!("sh.B2a") + use std::io::{Error, ErrorKind}; + if cfg!(windows) && target.as_os_str().as_encoded_bytes().contains(&b'"') { + return Err(Error::new(ErrorKind::InvalidInput, "the file name can't be passed to an application on Windows")); + } + std::fs::metadata(app)?; + if !is_application(app) { + return Err(Error::new(ErrorKind::InvalidInput, format!("{} isn't an application files can be opened in", app.display()))); + } + launch(app, target) +} + +/// `open` returns once Launch Services has the request, so a short wait reports an app it can't open (a folder named +/// `.app` that isn't a bundle). The wait is capped so a stalled `open` never holds the window: past it, the launch is +/// left to run. +#[cfg(target_os = "macos")] +fn launch(app: &Path, target: &Path) -> std::io::Result<()> { + use std::time::{Duration, Instant}; + const WAIT: Duration = Duration::from_secs(2); + let mut child = Command::new("open").arg("-a").arg(app).arg(target).stderr(Stdio::piped()).spawn()?; + let started = Instant::now(); + loop { + match child.try_wait()? { + Some(status) if status.success() => return Ok(()), + Some(status) => { + let mut why = String::new(); + if let Some(mut err) = child.stderr.take() { + // Best effort: without its message the exit status says why. + let _ = std::io::Read::read_to_string(&mut err, &mut why); + } + let why = why.trim(); + return Err(std::io::Error::other(if why.is_empty() { status.to_string() } else { why.to_owned() })); + } + None if started.elapsed() < WAIT => std::thread::sleep(Duration::from_millis(20)), + None => { + // Reaped off the UI thread once it ends. + std::thread::spawn(move || { + let _ = child.wait(); + }); + return Ok(()); + } + } + } +} + +/// The editor itself runs, so waiting would last until it closes. +#[cfg(all(not(target_arch = "wasm32"), not(target_os = "macos")))] +fn launch(app: &Path, target: &Path) -> std::io::Result<()> { + Command::new(app).arg(target).spawn().map(|_| ()) } /// Whether `path` names an application the platform can launch: an `.app` folder on macOS, an `.exe` file on /// Windows, an executable file elsewhere; `false` on wasm. pub fn is_application(path: &Path) -> bool { - let _ = path; - todo!("sh.B2b") + if cfg!(target_arch = "wasm32") { + return false; + } + let ext = path.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); + if cfg!(target_os = "macos") { + ext == "app" && path.is_dir() + } else if cfg!(windows) { + ext == "exe" && path.is_file() + } else { + executable_file(path) + } +} + +#[cfg(unix)] +fn executable_file(path: &Path) -> bool { + use std::os::unix::fs::PermissionsExt as _; + std::fs::metadata(path).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0) +} + +#[cfg(not(unix))] +fn executable_file(path: &Path) -> bool { + path.is_file() } /// The command that opens `target`; see [`open_external`]. diff --git a/crates/platform/src/open_tests.rs b/crates/platform/src/open_tests.rs index 9c05c13fb1..d097935b95 100644 --- a/crates/platform/src/open_tests.rs +++ b/crates/platform/src/open_tests.rs @@ -14,3 +14,53 @@ fn open_command_keeps_the_target_one_inert_argument() { assert_eq!(args, ["--", target]); } } + +/// Only an application counts, never a document, a folder or a missing path. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn an_application_is_what_the_platform_launches() { + use crate::open::is_application; + let temp = crate::temp::TempDir::new("craft-open-app-").unwrap(); + let dir = temp.path(); + let doc = dir.join("notes.txt"); + std::fs::write(&doc, "hi").unwrap(); + assert!(!is_application(&doc), "a document"); + assert!(!is_application(dir), "a folder"); + assert!(!is_application(&dir.join("Missing.app")), "a missing path"); + if cfg!(target_os = "macos") { + let app = dir.join("Editor.app"); + std::fs::create_dir_all(&app).unwrap(); + assert!(is_application(&app), "an .app folder"); + } + if cfg!(windows) { + let exe = dir.join("editor.exe"); + std::fs::write(&exe, "").unwrap(); + assert!(is_application(&exe), "an .exe file"); + } + #[cfg(all(unix, not(target_os = "macos")))] + { + use std::os::unix::fs::PermissionsExt as _; + let tool = dir.join("editor"); + std::fs::write(&tool, "#!/bin/sh\n").unwrap(); + assert!(!is_application(&tool), "not executable yet"); + std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap(); + assert!(is_application(&tool), "an executable file"); + } +} + +/// A missing application is `NotFound` (the caller falls back to its default editor); anything else that is not an +/// application is refused as `InvalidInput` before anything is started. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn open_with_reports_a_missing_application_and_refuses_what_is_not_one() { + use crate::open::open_with; + use std::io::ErrorKind; + let temp = crate::temp::TempDir::new("craft-open-with-").unwrap(); + let dir = temp.path(); + let doc = dir.join("notes.txt"); + std::fs::write(&doc, "not an application").unwrap(); + let kind = |app: &std::path::Path| open_with(app, std::path::Path::new("image with spaces.png")).unwrap_err().kind(); + assert_eq!(kind(&dir.join("Missing.exe")), ErrorKind::NotFound); + assert_eq!(kind(&doc), ErrorKind::InvalidInput); + assert_eq!(kind(dir), ErrorKind::InvalidInput); +} diff --git a/crates/ui-contract/src/primitives/icon.rs b/crates/ui-contract/src/primitives/icon.rs index a7fd3dee33..8be9204190 100644 --- a/crates/ui-contract/src/primitives/icon.rs +++ b/crates/ui-contract/src/primitives/icon.rs @@ -267,17 +267,26 @@ impl SvgIcon { svg_set::rasterise_entry(self.entry, self.set, px, stroke_px as f32 / 64.0, self.mirrored) } - /// Paints the icon in `color` centred in `square`, on whole pixels. + /// Paints the entry's fill in its fixed colour when it has one, then the icon in `color`, centred in `square`, on + /// whole pixels. pub(crate) fn paint(&self, painter: &Painter, square: Rect, color: Color32) { let ctx = painter.ctx(); let ppp = ctx.pixels_per_point(); let (px, stroke_px) = self.pixels(square.width(), ppp); - let key = (self.entry, self.set, px, stroke_px, self.mirrored); - let texture = TextureCache::texture(ctx, key, || self.mask(square.width(), ppp)); let side = px as f32 / ppp; let min = (square.center() - vec2(side, side) / 2.0).round_to_pixels(ppp); + let rect = Rect::from_min_size(min, vec2(side, side)); let uv = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); - crate::runtime::egui::textures::paint(painter, texture, Rect::from_min_size(min, vec2(side, side)), uv, color, egui::CornerRadius::ZERO); + // The fill flag keeps the fill's texture apart from the icon's. + let stamp = |fill: bool, tint: Color32, image: &dyn Fn() -> egui::ColorImage| { + let key = (self.entry, self.set, px, stroke_px, self.mirrored, fill); + let texture = TextureCache::texture(ctx, key, image); + crate::runtime::egui::textures::paint(painter, texture, rect, uv, tint, egui::CornerRadius::ZERO); + }; + if let Some((svg, [r, g, b, a])) = svg_set::fill_of(self.entry) { + stamp(true, Color32::from_rgba_unmultiplied(r, g, b, a), &|| svg_set::rasterise_fill(svg, px)); + } + stamp(false, color, &|| self.mask(square.width(), ppp)); } } diff --git a/crates/ui-contract/src/primitives/svg_set.rs b/crates/ui-contract/src/primitives/svg_set.rs index bede07cdc7..771371da41 100644 --- a/crates/ui-contract/src/primitives/svg_set.rs +++ b/crates/ui-contract/src/primitives/svg_set.rs @@ -99,6 +99,22 @@ fn app_icon(set: usize, icon: usize) -> (&'static str, &'static [u8], Option Option<(&'static [u8], [u8; 4])> { + let Entry::App { set, icon } = entry else { return None }; + let registry = APPS.read().unwrap_or_else(PoisonError::into_inner); + let set = registry.sets[set]; + let name = set.icons[icon].0; + set.fills.iter().find(|(fill, ..)| *fill == name).map(|&(_, svg, color)| (svg, color)) +} + +/// A fill document in white at `px` x `px` physical pixels, drawn as drawn and never mirrored: no app icon is +/// directional. +pub(crate) fn rasterise_fill(svg: &[u8], px: u32) -> ColorImage { + image(draw(svg, None, px, 0.0, false), px, || "app icon fill".to_owned()) +} + /// The position of the icon called `name` in the catalog. pub(crate) fn find(name: &str) -> Option { NAMES.binary_search(&name).ok() diff --git a/crates/ui-contract/src/runtime/lock_keys.rs b/crates/ui-contract/src/runtime/lock_keys.rs index ed3b49f61d..04804ce118 100644 --- a/crates/ui-contract/src/runtime/lock_keys.rs +++ b/crates/ui-contract/src/runtime/lock_keys.rs @@ -23,7 +23,7 @@ pub fn caps_lock(ctx: &Context) -> bool { let pass = ctx.cumulative_pass_nr(); with_session(ctx, global("craft-ui lock keys", ()), |reading: &mut Reading| { if reading.pass != Some(pass) { - *reading = Reading { pass: Some(pass), caps: craft_window::caps_lock(WindowHost::of(ctx).shell().backend) }; // P3(shell-w2): sh.K9 + *reading = Reading { pass: Some(pass), caps: craft_window::caps_lock(WindowHost::of(ctx).shell().backend) }; } reading.caps }) diff --git a/crates/ui-contract/src/testing/icon_trials.rs b/crates/ui-contract/src/testing/icon_trials.rs index 645d1e2214..48d624be68 100644 --- a/crates/ui-contract/src/testing/icon_trials.rs +++ b/crates/ui-contract/src/testing/icon_trials.rs @@ -3,11 +3,11 @@ use crate::primitives::{AppIcons, Mirror, SvgIcon, icon_names, register_app_icons}; use crate::style::UiTokens; -use crate::testing::{style, trial}; +use crate::testing::{Frames, style, trial}; use craft_behavior::IconId; use craft_i18n::Direction; use craft_theme::{AppSizes, Appearance, Contrast, IconPackId, Mode, Size, TextSize, builtins}; -use egui::ColorImage; +use egui::{Color32, ColorImage, Rect, pos2, vec2}; // Built from parts so the workspace scan of icon-id literals does not read them. const FIRST_NAME: &str = concat!("zz_t10_", "first"); @@ -21,14 +21,17 @@ const FIRST_SET: AppIcons = AppIcons { name: "t10-first", stroke_width: None, icons: &[(FIRST_NAME, DISC), (CATALOG_NAME, DISC)], - fills: &[], /* P3(shell-w2): sh.K10 */ + fills: &[], }; const SECOND_SET: AppIcons = AppIcons { name: "t10-second", stroke_width: None, icons: &[(FIRST_NAME, SQUARE), (SECOND_NAME, SQUARE)], - fills: &[], /* P3(shell-w2): sh.K10 */ + fills: &[], }; +const FILLED_NAME: &str = concat!("zz_k10_", "filled"); +const FILL_COLOR: [u8; 4] = [255, 0, 0, 255]; +const FILLED_SET: AppIcons = AppIcons::new("k10-filled", None, &[(FILLED_NAME, DISC)]).with_fills(&[(FILLED_NAME, SQUARE, FILL_COLOR)]); fn icon(name: &'static str) -> Option { let tokens = style::tokens(Mode::Light, Contrast::Standard); @@ -91,3 +94,30 @@ fn a_theme_icon_pack_picks_the_set_and_an_unknown_pack_draws_the_default() { assert_eq!(mask_under_pack(Some("craft.lucide"), CATALOG_NAME), default, "the default set by name draws the default"); assert_eq!(mask_under_pack(Some("user.missing"), CATALOG_NAME), default, "a pack that is not installed draws the default"); } + +/// The colours of the textured shapes `name` paints under the tint `color`, first to last. +fn painted(name: &'static str, color: Color32) -> Vec { + let Some(svg) = icon(name) else { return Vec::new() }; + let square = Rect::from_min_size(pos2(10.0, 10.0), vec2(24.0, 24.0)); + Frames::new() + .frame_shapes(|ui| svg.paint(ui.painter(), square, color)) + .iter() + .filter_map(|shape| match shape { + egui::Shape::Mesh(mesh) => mesh.vertices.first().map(|vertex| vertex.color), + egui::Shape::Rect(rect) if rect.brush.is_some() => Some(rect.fill), + _ => None, + }) + .collect() +} + +#[trial] +fn an_icon_with_a_fill_keeps_its_colour_under_the_tint() { + register_app_icons(&FILLED_SET); + let [r, g, b, a] = FILL_COLOR; + let fill = Color32::from_rgba_unmultiplied(r, g, b, a); + for tint in [Color32::from_rgb(10, 200, 30), Color32::WHITE] { + assert_eq!(painted(FILLED_NAME, tint), [fill, tint], "the fill keeps its colour and the icon takes the tint"); + } + let tint = Color32::from_rgb(10, 200, 30); + assert_eq!(painted(CATALOG_NAME, tint), [tint], "an icon with no fill paints the icon only"); +} diff --git a/crates/ui-widgets/src/buttons/button.rs b/crates/ui-widgets/src/buttons/button.rs index 1d74f8e584..3f924f5e04 100644 --- a/crates/ui-widgets/src/buttons/button.rs +++ b/crates/ui-widgets/src/buttons/button.rs @@ -1,20 +1,24 @@ //! `Button`: a push button with an optional leading and trailing icon and a busy state. use super::face::{self, FaceLook, FaceSpec}; -use crate::contract::{Common, Component, Cx, LeastWidth, MeasureCx, NoValue, Outcome, PaintUi, PartsCx, Pointer as _, Props, Role, Styled as _}; -use crate::display::Spinner; +use crate::contract::{ + Access, Common, Component, Cx, LeastWidth, MeasureCx, NoValue, Outcome, PaintUi, PartsCx, Pointer as _, Props, Role, Styled as _, WordSetCx as _, +}; +use crate::display::{ChordWrite, DisplayWords, Kbd, Spinner}; use crate::primitives::{HAlign, IconSpec, PaintShape}; -use crate::runtime::commands::CommandRef; +use crate::runtime::commands::{CommandRef, ResolvedCommand}; use crate::runtime::env::Label; use crate::style::{ComponentStyle, DataColor, FocusLook, IconLook, StyleColor, StyleCx, SurfaceLook, TextLook, TypeRole}; -use craft_behavior::{Metrics, PartKey, PressPhase, Sense}; -use craft_keymap::Mods; +use craft_behavior::{Metrics, PartKey, PointerButton, PressPhase, Sense}; +use craft_host::target::Os; +use craft_keymap::{Mods, Trigger}; use craft_theme::{ Rgba, Stateful, Variant, variant::{Emphasis, Tone}, }; use egui::{Color32, Rect, Response, Vec2}; use std::ops::Deref; +use std::sync::Arc; /// The part a loading button shows its spinner in. const SPINNER: PartKey = PartKey::new("spinner"); @@ -62,6 +66,7 @@ impl ButtonStyle { let ink = cx.ink_on(DataColor::new(cx.color(tint).egui())); style.text = TextLook::new(TypeRole::Label, Stateful::new(ink)); style.icon = IconLook::new(cx.control().icon, Stateful::new(ink)); + style.face.muted = Stateful::new(ink); style } } @@ -96,7 +101,8 @@ impl ButtonOutput { (true, Some(activation)) => activation.mods, _ => Mods::NONE, }; - ButtonOutput { response: cx.response.clone(), clicks, mods, held: false } // P3(shell-w2): op.F1 + let held = cx.press().phase.button_down() && cx.press().phase.start().is_some_and(|start| start.button == PointerButton::Primary); + ButtonOutput { response: cx.response.clone(), clicks, mods, held } } /// Whether the button was clicked this pass, by pointer or by key, by the framework's click rule. It stands in @@ -170,11 +176,9 @@ pub struct Button<'a> { /// A muted caption-role second line, wrapped under the icon and label. The face grows to fit it. It is the /// accessible description unless `description` is set. #[prop(into)] - #[allow(dead_code)] // P3(shell-w2): dp.R3 detail: Option