From ec93a52260a108e575c31f30e1996b2a78f06ff4 Mon Sep 17 00:00:00 2001 From: Martin Ball Date: Wed, 18 Nov 2026 08:08:21 +0000 Subject: [PATCH] Contract stubs: craft-ui-contract --- crates/theme/src/variant.rs | 6 ++ crates/ui-contract/Cargo.toml | 4 +- .../src/contract/collection/events.rs | 5 ++ crates/ui-contract/src/contract/cx/context.rs | 7 ++ crates/ui-contract/src/contract/cx/edit.rs | 1 + crates/ui-contract/src/contract/cx/pointer.rs | 12 +++- crates/ui-contract/src/contract/editor.rs | 44 +++++++++++- crates/ui-contract/src/contract/mod.rs | 3 +- .../ui-contract/src/contract/overlay/place.rs | 23 ++++-- .../ui-contract/src/contract/overlay/props.rs | 3 +- .../ui-contract/src/contract/steps/value.rs | 3 + crates/ui-contract/src/contract/text.rs | 2 +- crates/ui-contract/src/contract/values.rs | 30 ++++++++ crates/ui-contract/src/primitives/draw.rs | 19 ++++- crates/ui-contract/src/primitives/icon.rs | 40 ++++++++++- crates/ui-contract/src/primitives/kit.rs | 27 +++++-- crates/ui-contract/src/primitives/mod.rs | 10 +-- .../src/primitives/pointer_art/art.rs | 6 ++ .../src/primitives/text_adapter.rs | 3 +- .../ui-contract/src/primitives/text_input.rs | 53 +++++++++++++- .../src/primitives/textures/store.rs | 28 ++++++-- .../src/runtime/commands/clipboard.rs | 71 ++++++++++++++++++- .../ui-contract/src/runtime/commands/mod.rs | 2 + crates/ui-contract/src/runtime/egui/access.rs | 8 +++ .../ui-contract/src/runtime/egui/alt_code.rs | 14 ++++ .../ui-contract/src/runtime/egui/clipboard.rs | 48 +++++++++++++ crates/ui-contract/src/runtime/egui/input.rs | 13 ++-- crates/ui-contract/src/runtime/egui/mod.rs | 1 + .../ui-contract/src/runtime/egui/text_edit.rs | 7 ++ .../ui-contract/src/runtime/egui/textures.rs | 10 ++- crates/ui-contract/src/runtime/env.rs | 4 +- crates/ui-contract/src/runtime/env/root.rs | 20 +++++- crates/ui-contract/src/runtime/env/shell.rs | 24 +++++++ crates/ui-contract/src/runtime/env/tokens.rs | 15 +++- crates/ui-contract/src/runtime/env/values.rs | 31 ++++++++ crates/ui-contract/src/runtime/ime.rs | 3 + crates/ui-contract/src/runtime/inspect.rs | 39 ++++++++-- crates/ui-contract/src/runtime/install.rs | 10 +++ .../ui-contract/src/runtime/windows/host.rs | 7 ++ crates/ui-contract/src/style/look.rs | 4 +- crates/ui-contract/src/style/span.rs | 10 +++ crates/ui-contract/src/style/surface.rs | 5 +- 42 files changed, 626 insertions(+), 49 deletions(-) create mode 100644 crates/ui-contract/src/runtime/egui/alt_code.rs diff --git a/crates/theme/src/variant.rs b/crates/theme/src/variant.rs index 04c4b7889..345b51761 100644 --- a/crates/theme/src/variant.rs +++ b/crates/theme/src/variant.rs @@ -68,6 +68,12 @@ impl Tone { tokens.color.get(ToneTokens::of(self).soft_fill) } + /// The ink text and icons of the tone read in: `accent.text`, the status foreground, and the normal text for no status. + pub fn ink(self, tokens: &Tokens) -> Rgba { + let _ = tokens; + todo!("ch.C14a") + } + /// The ink text and icons read in on the tone's [`soft_fill`](Self::soft_fill): `accent.on_soft`, the status /// foreground, and the normal text for no status. pub fn on_soft(self, tokens: &Tokens) -> Rgba { diff --git a/crates/ui-contract/Cargo.toml b/crates/ui-contract/Cargo.toml index 112697346..5482f4930 100644 --- a/crates/ui-contract/Cargo.toml +++ b/crates/ui-contract/Cargo.toml @@ -45,7 +45,7 @@ craft-window = { workspace = true, features = ["ui"] } # `quit`, which `runtime::windows::logic` routes a root close through. craft-quit = { workspace = true } # `appearance::SystemReader`, the OS appearance the root's `System` choices resolve from. -craft-platform = { workspace = true, features = ["appearance"] } +craft-platform = { workspace = true, features = ["appearance", "clipboard"] } craft-i18n = { workspace = true, features = ["collate"] } log = "0.4" smallvec = { workspace = true } @@ -77,7 +77,7 @@ image = { version = "0.25", default-features = false, features = ["png"], option # The window host's end hook sets `NSWindow.movable` through craft-window's AppKit code. [target.'cfg(target_arch = "wasm32")'.dependencies] # `screen::available`: whether the browser has the EyeDropper, read at install for `Caps::SCREEN_CAPTURE`. -craft-platform = { workspace = true, features = ["screen", "browser"] } +craft-platform = { workspace = true, features = ["screen", "browser", "clipboard"] } [target.'cfg(target_os = "macos")'.dependencies] craft-window = { workspace = true, features = ["ui", "appkit"] } diff --git a/crates/ui-contract/src/contract/collection/events.rs b/crates/ui-contract/src/contract/collection/events.rs index 91cc9d199..b3a415869 100644 --- a/crates/ui-contract/src/contract/collection/events.rs +++ b/crates/ui-contract/src/contract/collection/events.rs @@ -178,6 +178,11 @@ pub enum ColumnEvent { Unsorted, /// The user reset the columns: the app's order, every column shown, the app's widths. The sort stays. Reset, + /// The user pressed the column's remove control. + Removed { + /// The column. + key: ColumnKey, + }, } /// What a collection reports, in drawing order. diff --git a/crates/ui-contract/src/contract/cx/context.rs b/crates/ui-contract/src/contract/cx/context.rs index 187ba8fb3..1169f43d2 100644 --- a/crates/ui-contract/src/contract/cx/context.rs +++ b/crates/ui-contract/src/contract/cx/context.rs @@ -38,6 +38,8 @@ pub(crate) trait TextResult { fn submit_mods(&self) -> craft_keymap::Mods; /// Whether Tab (`Some(true)`) or Shift+Tab (`Some(false)`) moved focus off the part this pass. fn left_by_tab(&self) -> Option; + /// Whether a `TabKey::Reports` part kept focus on Tab (`Some(true)`) or Shift+Tab (`Some(false)`) this pass. + fn tab(&self) -> Option; fn as_any(&self) -> &dyn Any; } @@ -45,6 +47,7 @@ pub(crate) struct RecordedText { pub(crate) outcome: crate::primitives::TextOutcome, pub(crate) submit_mods: craft_keymap::Mods, pub(crate) left_by_tab: Option, + pub(crate) tab: Option, } impl TextResult for RecordedText { @@ -56,6 +59,10 @@ impl TextResult for RecordedText { self.left_by_tab } + fn tab(&self) -> Option { + self.tab + } + fn as_any(&self) -> &dyn Any { self } diff --git a/crates/ui-contract/src/contract/cx/edit.rs b/crates/ui-contract/src/contract/cx/edit.rs index 3f494768a..0d0ed02e7 100644 --- a/crates/ui-contract/src/contract/cx/edit.rs +++ b/crates/ui-contract/src/contract/cx/edit.rs @@ -241,6 +241,7 @@ impl Edit for Cx<'_, C> { response.submitted = self.core.submitted; response.submit_mods = self.core.texts.as_ref().map_or(craft_keymap::Mods::NONE, |(_, text)| text.submit_mods()); response.left_by_tab = self.core.texts.as_ref().and_then(|(_, text)| text.left_by_tab()); + response.tab = self.core.texts.as_ref().and_then(|(_, text)| text.tab()); response.unparsed = self.core.text_invalid; response.value_text = self.core.value_text.borrow().clone(); response.shown = match (&self.shown, self.mixed) { diff --git a/crates/ui-contract/src/contract/cx/pointer.rs b/crates/ui-contract/src/contract/cx/pointer.rs index f405877b2..3e27d59a1 100644 --- a/crates/ui-contract/src/contract/cx/pointer.rs +++ b/crates/ui-contract/src/contract/cx/pointer.rs @@ -1,7 +1,7 @@ //! The `Pointer` trait: presses, hover, drags and cursors, on `CxCore` and `Cx`. use super::context::{Activation, Cx, CxCore}; -use crate::contract::Component; +use crate::contract::{Component, Hover}; use crate::primitives::PartResult; use crate::runtime::drag::{self, DragPreview, DropTarget, DropZone, Typed, WindowDropTarget}; use crate::runtime::egui::areas; @@ -28,6 +28,8 @@ pub trait Pointer { fn press(&self) -> &PressState; /// The pointer is over the component's own shapes. fn hit(&self) -> bool; + /// The pointer's stay over the component: over it, entered, left, and clicked while it has stayed over. + fn hover(&self) -> Hover; /// Set only when the component's own shapes won the press and it was released as a click, or /// `Intent::Activate` was routed to it. fn activation(&self) -> Option; @@ -63,6 +65,10 @@ pub trait Pointer { } impl Pointer for CxCore<'_> { + fn hover(&self) -> Hover { + todo!("cv.K45") + } + fn part(&self, part: impl Into) -> &PartResult { let part = part.into(); match self.results.get(&(part.key, part.index)) { @@ -170,6 +176,10 @@ impl CxCore<'_> { } impl Pointer for Cx<'_, C> { + fn hover(&self) -> Hover { + self.core.hover() + } + fn part(&self, part: impl Into) -> &PartResult { self.core.part(part) } diff --git a/crates/ui-contract/src/contract/editor.rs b/crates/ui-contract/src/contract/editor.rs index 7442f513a..60683312d 100644 --- a/crates/ui-contract/src/contract/editor.rs +++ b/crates/ui-contract/src/contract/editor.rs @@ -4,7 +4,7 @@ use super::Component; use super::cx::{Cx, Edit as _, PartsCx}; -use crate::primitives::{EditorPurpose, EditorState, ImeSurface}; +use crate::primitives::{EditorPurpose, EditorState, ImeStamp, ImeSurface}; use crate::runtime::access::text::{self as text_access, Line, Run, TextFacts}; use crate::runtime::egui::{editor as egui_editor, focus as egui_focus}; use crate::runtime::focus::KeyUse; @@ -86,7 +86,49 @@ pub(crate) fn run(cx: &mut Cx<'_, C>, ui: &mut Ui, step: &mut supe cx.core.editor_inputs = inputs; } +/// The editor part's widget, rect, purpose, focus and read-only state of this pass, which a body that runs inside a +/// component reports through for the component's editor part. +#[derive(Clone, Debug, PartialEq)] +pub struct EditorHandle { + #[allow(dead_code)] // P3(canvas-w2): cv.K41 + widget: egui::Id, + #[allow(dead_code)] // P3(canvas-w2): cv.K41 + rect: Rect, + #[allow(dead_code)] // P3(canvas-w2): cv.K41 + purpose: EditorPurpose, + #[allow(dead_code)] // P3(canvas-w2): cv.K41 + focused: bool, + #[allow(dead_code)] // P3(canvas-w2): cv.K41 + read_only: bool, +} + +impl EditorHandle { + /// Reports the caret and composition to the input-method engine and puts the text facts in the running pass's + /// editor record, which the owning component's report step reads in the same pass. + pub fn report(&self, ctx: &egui::Context, state: EditorState<'_>) { + let _ = (ctx, state); + todo!("cv.K41") + } +} + impl Cx<'_, C> { + /// The editor part of this pass, `None` when the component registered none. + pub fn editor_handle(&self) -> Option { + todo!("cv.K41") + } + + /// Notes the input-method receipt between the stamps `before` and `after` on the egui fork's tracker for this + /// viewport and frame; true when the stamps prove the engine applied it. + pub fn ime_receipt(&self, before: ImeStamp, after: ImeStamp) -> bool { + let _ = (before, after); + todo!("cv.K27") + } + + /// Notes an input-method application change on the egui fork's tracker for this viewport and frame. + pub fn ime_application_change(&self) { + todo!("cv.K27") + } + /// The editor part's inputs of this pass in the order they arrived; call it in `update`. The editor applies them /// to its own document. pub fn editor_input(&mut self) -> impl Iterator + '_ { diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index c756b6d3d..3f40a1ed4 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -5,6 +5,7 @@ mod collection; mod container; mod cx; pub(crate) mod editor; +pub use editor::EditorHandle; mod entry; mod faces; pub mod ghost; @@ -100,7 +101,7 @@ pub use registry::{CollectionEntry, ContainerEntry, Exemption, LeafEntry, Patter pub use sampler::{CanvasGesture, Sampler}; pub use settle::SettleCx; pub use text::EDIT_MENU; -pub use values::{Bind, BindMut, EditResponse, ItemOutput, NoValue, Outcome, Validity, ValueOf, clicked, pressed}; +pub use values::{Bind, BindMut, EditResponse, Hover, ItemOutput, NoValue, Outcome, Validity, ValueOf, clicked, pressed}; use crate::runtime::memory::sub; use crate::runtime::overlay::CloseReason; diff --git a/crates/ui-contract/src/contract/overlay/place.rs b/crates/ui-contract/src/contract/overlay/place.rs index ac085d4ec..103afd2fd 100644 --- a/crates/ui-contract/src/contract/overlay/place.rs +++ b/crates/ui-contract/src/contract/overlay/place.rs @@ -21,22 +21,35 @@ pub enum Anchor { } /// Where a floating layer sits. -#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub struct FloatPlace { - /// A position for the layer's left-top, in the layer's parent space; `None` centres it in the viewport. + /// Where the layer's `corner` sits, in the layer's parent space; `None` centres it in the viewport. pub pos: Option, + /// The corner of the layer that sits at `pos`. + pub corner: Align2, +} + +impl Default for FloatPlace { + fn default() -> Self { + FloatPlace::centred() + } } impl FloatPlace { /// Centred in the viewport. pub const fn centred() -> Self { - FloatPlace { pos: None } + FloatPlace { pos: None, corner: Align2::LEFT_TOP } } - /// At `pos`. + /// With its left-top at `pos`. pub const fn at(pos: Pos2) -> Self { - FloatPlace { pos: Some(pos) } + FloatPlace { pos: Some(pos), corner: Align2::LEFT_TOP } + } + + /// With its `corner` at `pos`. + pub const fn corner_at(pos: Pos2, corner: Align2) -> Self { + FloatPlace { pos: Some(pos), corner } } } diff --git a/crates/ui-contract/src/contract/overlay/props.rs b/crates/ui-contract/src/contract/overlay/props.rs index 5f1f18842..431694fe3 100644 --- a/crates/ui-contract/src/contract/overlay/props.rs +++ b/crates/ui-contract/src/contract/overlay/props.rs @@ -189,7 +189,8 @@ impl Overlay { mapped.placed = mapped.placed.map(|rect| to_screen * rect); mapped.placed_at = mapped.placed_at.map(|pos| to_screen * pos); mapped.bounds = mapped.bounds.map(|rect| to_screen * rect); - if let Place::Float(FloatPlace { pos: Some(pos) }) = &mut mapped.place { + // P3(chrome-w7): ch.C20a: the pattern ignores the new `corner`. + if let Place::Float(FloatPlace { pos: Some(pos), .. }) = &mut mapped.place { *pos = to_screen * *pos; } Cow::Owned(mapped) diff --git a/crates/ui-contract/src/contract/steps/value.rs b/crates/ui-contract/src/contract/steps/value.rs index f1a3b1150..9554846a3 100644 --- a/crates/ui-contract/src/contract/steps/value.rs +++ b/crates/ui-contract/src/contract/steps/value.rs @@ -23,6 +23,9 @@ pub(crate) struct Shown { #[derive(Clone, Default)] pub(crate) struct ShownState { pub last_state: (bool, bool), + /// A pointer click on the control, while the pointer has stayed over it since. + #[allow(dead_code)] // P3(ribbon-w2): cv.K45 + pub clicked_over: bool, pub tweens: Option, } diff --git a/crates/ui-contract/src/contract/text.rs b/crates/ui-contract/src/contract/text.rs index cb5a98056..fd70e9d50 100644 --- a/crates/ui-contract/src/contract/text.rs +++ b/crates/ui-contract/src/contract/text.rs @@ -512,7 +512,7 @@ pub(crate) fn run( outcome.clicked = out.clicked; // The focus service moved focus off the widget with Tab before this pass's widgets ran. let left_by_tab = if was_focused && !out.focused { crate::runtime::focus::tabbed_off(&ctx, widget) } else { None }; - cx.core.texts = Some((decl.key, Box::new(RecordedText { outcome, submit_mods: resolved.submit_mods, left_by_tab }))); + cx.core.texts = Some((decl.key, Box::new(RecordedText { outcome, submit_mods: resolved.submit_mods, left_by_tab, tab: None }))); apply_events(cx, resolved.events); cx.core.memory.shown::(state_id).seen = shown_copy(cx); cx.core.submitted |= resolved.submitted; diff --git a/crates/ui-contract/src/contract/values.rs b/crates/ui-contract/src/contract/values.rs index a19e87a01..4f0b9a509 100644 --- a/crates/ui-contract/src/contract/values.rs +++ b/crates/ui-contract/src/contract/values.rs @@ -436,6 +436,27 @@ pub struct EditResponse { /// The shown value as the component words it to assistive technology ("40.0", "50 %"); `None` for a component /// that gives no such text. pub value_text: Option, + /// A `TabKey::Reports` text part kept focus on Tab (`Some(true)`) or Shift+Tab (`Some(false)`) in this pass; + /// `left_by_tab` stays the fact that focus left by Tab, which such a part never does. + pub tab: Option, + /// The bound caret (byte offset) after the pass. + pub caret: Option, + /// The pointer's stay over the control. + pub hover: Hover, +} + +/// A command-bound control's report of the pointer's stay over it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub struct Hover { + /// The pointer is over the control in this pass. + pub over: bool, + /// The pointer entered the control in this pass. + pub entered: bool, + /// The pointer left the control in this pass. + pub left: bool, + /// The control was clicked with the pointer, which has stayed over it since. + pub clicked: bool, } impl EditResponse { @@ -451,6 +472,9 @@ impl EditResponse { validity, shown: None, value_text: None, + tab: None, + caret: None, + hover: Hover::default(), } } @@ -470,6 +494,9 @@ impl EditResponse { validity: Validity::Ok, shown, value_text: None, + tab: None, + caret: None, + hover: Hover::default(), } } @@ -507,6 +534,9 @@ impl EditResponse { validity, shown, value_text: self.value_text, + tab: self.tab, + caret: self.caret, + hover: self.hover, } } } diff --git a/crates/ui-contract/src/primitives/draw.rs b/crates/ui-contract/src/primitives/draw.rs index 095991727..5f687bb2f 100644 --- a/crates/ui-contract/src/primitives/draw.rs +++ b/crates/ui-contract/src/primitives/draw.rs @@ -372,7 +372,8 @@ impl<'a> Draw<'a> { } _ => super::icon::paint(self.painter, self.env.tokens, self.env.direction, rect, icon), } - if let Some(badge) = icon.badge { + // P3(canvas-w3): rb.R18: only the dot paints; the bar's painting comes with its writer. + if let Some(super::IconMark::Dot(badge)) = icon.badge { let radius = self.env.tokens.size.handle.sm / 2.0; let centre = if self.env.direction == Direction::Rtl { square.left_bottom() + Vec2::new(radius, -radius) @@ -491,6 +492,14 @@ impl<'a> Draw<'a> { data_picture(self.painter, self.env.tokens, self.data, texture, rect, uv, CornerRadius::ZERO); } + /// Paints `uv` of `texture` onto the clockwise quad `corners` (from `uv`'s top left), untinted, as data: a + /// disabled component paints it at `Opacity::DISABLED`, and for an inactive part the quad is filled with the + /// theme's disabled fill. A quad has square corners. + pub fn texture_quad(&self, corners: [Pos2; 4], texture: TextureId, uv: Rect) { + let _ = (corners, texture, uv); + todo!("cv.K30") + } + /// Paints `checker` over `rect` with corners `radius`, a light cell at the rect's top left. It shows through data, /// so it paints as the data over it: at `Opacity::DISABLED` for a disabled component, and for an inactive part as /// the theme's disabled fill, as `data_fill` does. @@ -604,6 +613,14 @@ pub(super) fn data_picture(painter: &Painter, tokens: &UiTokens, mode: DataMode, } } +/// Paints `uv` of `texture` onto the clockwise quad `corners` as the data in `mode`: untinted through `paint_quad`, +/// or for an inactive part the quad filled with the disabled fill, as `data_picture` fills its rect. +#[allow(dead_code)] // P3(canvas-w3): cv.K30 +pub(super) fn data_quad(painter: &Painter, tokens: &UiTokens, mode: DataMode, texture: TextureId, corners: [Pos2; 4], uv: Rect) { + let _ = (painter, tokens, mode, texture, corners, uv); + todo!("cv.K30") +} + /// Paints `checker` over `rect` with corners `radius`, a light cell at the rect's top left, as the data over it in /// `mode`: mapped as `mode` maps a colour, or for an inactive part `rect` in the theme's disabled fill. `Draw::checker` /// and `ContentPainterCx::checker_with` paint through it. diff --git a/crates/ui-contract/src/primitives/icon.rs b/crates/ui-contract/src/primitives/icon.rs index 017b30e68..7d894dbc4 100644 --- a/crates/ui-contract/src/primitives/icon.rs +++ b/crates/ui-contract/src/primitives/icon.rs @@ -97,8 +97,36 @@ pub struct IconSpec<'a> { pub mirror: Mirror, /// The set an SVG icon is drawn from. pub set: IconSet, - /// A dot of a colour from data at the icon's bottom-trailing corner; see [`badge`](Self::badge). - pub badge: Option, + /// A data-colour mark on the icon: a dot at the bottom-trailing corner (see [`badge`](Self::badge)) or a bar across + /// the bottom (see [`with_mark`](Self::with_mark)). + pub badge: Option, +} + +/// A data-colour mark on an icon. +#[derive(Clone, Copy, Debug, PartialEq)] +#[non_exhaustive] +pub enum IconMark { + /// A dot at the icon's bottom-trailing corner, ringed in the icon's colour. + Dot(DataColor), + /// A bar across the bottom of the icon square, inside it; `weight` is its thickness in points, else `StrokeWidth::Thick`. + Bar { + /// The bar's colour. + color: DataColor, + /// The thickness in points; `None` takes `StrokeWidth::Thick`. + weight: Option, + }, +} + +impl IconMark { + /// A bar of `color` with the default thickness. + pub const fn bar(color: DataColor) -> Self { + IconMark::Bar { color, weight: None } + } + + /// A bar of `color` `weight` points thick. + pub const fn weighted_bar(color: DataColor, weight: f32) -> Self { + IconMark::Bar { color, weight: Some(weight) } + } } impl<'a> IconSpec<'a> { @@ -184,9 +212,15 @@ impl<'a> IconSpec<'a> { /// Adds a dot of `color` at the bottom-trailing corner of an SVG or glyph icon, ringed in the icon's colour: the /// tone a point picker sets. The dot is a data colour (`Draw::data_fill`); the ring follows the icon's colour. pub fn badge(mut self, color: DataColor) -> Self { - self.badge = Some(color); + self.badge = Some(IconMark::Dot(color)); self } + + /// Puts `mark` on the icon in place of any mark it has. + pub fn with_mark(self, mark: IconMark) -> Self { + let _ = mark; + todo!("rb.R18") + } } impl IconSpec<'_> { diff --git a/crates/ui-contract/src/primitives/kit.rs b/crates/ui-contract/src/primitives/kit.rs index a20d020f3..089f5b52d 100644 --- a/crates/ui-contract/src/primitives/kit.rs +++ b/crates/ui-contract/src/primitives/kit.rs @@ -344,6 +344,17 @@ const MINOR_SHARE: f32 = 0.45; /// The radius of a dot, in screen points. const DOT_RADIUS: f32 = 0.6; +/// What a grid does when its lines come closer than the minimum step. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum GridCrowding { + /// Draws nothing for an axis whose lines are too close. + #[default] + Hide, + /// Doubles the step, at most 32 times, until the lines fit. + Thin, +} + /// The lines of one axis: positions along it, in the grid's space. #[derive(Clone, Debug, Default, PartialEq)] #[non_exhaustive] @@ -358,7 +369,8 @@ impl GridAxis { /// The lines of one axis between `lo` and `hi`: majors every `step` from `origin`, minors between them when the /// minor step is at least [`MIN_STEP`] screen points at `zoom`. An axis whose major step is under `MIN_STEP` /// draws nothing; at most [`MAX_LINES`] lines are given. - fn spaced(step: f64, subdivisions: u32, origin: f64, (lo, hi): (f64, f64), zoom: f64) -> GridAxis { + fn spaced(step: f64, subdivisions: u32, origin: f64, (lo, hi): (f64, f64), zoom: f64, crowding: GridCrowding) -> GridAxis { + let _ = crowding; // P3(canvas-w3): cv.K31 if !(step.is_finite() && step > 0.0 && zoom.is_finite() && zoom > 0.0) || step * zoom < MIN_STEP { return GridAxis::default(); } @@ -398,10 +410,17 @@ pub struct GridLines { impl GridLines { /// The lines of a grid in document units: majors every `spacing` from `origin`, `subdivisions` steps to a major /// (1 or 0 is no minor lines), across `extent` as `view` shows it. - pub fn document(view: &CanvasView, extent: kurbo::Rect, spacing: kurbo::Vec2, origin: kurbo::Point, subdivisions: u32) -> Self { + pub fn document( + view: &CanvasView, + extent: kurbo::Rect, + spacing: kurbo::Vec2, + origin: kurbo::Point, + subdivisions: u32, + crowding: GridCrowding, + ) -> Self { let subdivisions = subdivisions.max(1); - let x = GridAxis::spaced(spacing.x, subdivisions, origin.x, (extent.x0, extent.x1), view.zoom_x()); - let y = GridAxis::spaced(spacing.y, subdivisions, origin.y, (extent.y0, extent.y1), view.zoom); + let x = GridAxis::spaced(spacing.x, subdivisions, origin.x, (extent.x0, extent.x1), view.zoom_x(), crowding); + let y = GridAxis::spaced(spacing.y, subdivisions, origin.y, (extent.y0, extent.y1), view.zoom, crowding); let crossings = spacing.x * view.zoom_x() >= CROSSING_MIN && spacing.y * view.zoom >= CROSSING_MIN; GridLines { x, y, extent: Some(extent), crossings, view: Some(*view) } } diff --git a/crates/ui-contract/src/primitives/mod.rs b/crates/ui-contract/src/primitives/mod.rs index d302024b4..6510fb055 100644 --- a/crates/ui-contract/src/primitives/mod.rs +++ b/crates/ui-contract/src/primitives/mod.rs @@ -37,11 +37,11 @@ pub use faces::FacesCx; pub use focus_ring::{FocusKind, FocusRing}; pub use handle::{Handle, HandleShape}; pub(crate) use icon::SvgIcon; -pub use icon::{Glyph, IconSet, IconSource, IconSpec, Mirror, has_icon, icon_names}; +pub use icon::{Glyph, IconMark, IconSet, IconSource, IconSpec, Mirror, has_icon, icon_names}; pub use ime_surface::ImeSurface; pub use kit::{ - Checker, CheckerArea, GridAxis, GridInk, GridLines, GridLook, GridStroke, MAX_LINES, Tick, TickEdge, TickRank, dashed, drop_mark, ellipse, - fill_polygon, grid_lines, grid_lines_with, marching_ants, outline, ramp, ticks, + Checker, CheckerArea, GridAxis, GridCrowding, GridInk, GridLines, GridLook, GridStroke, MAX_LINES, Tick, TickEdge, TickRank, dashed, drop_mark, + ellipse, fill_polygon, grid_lines, grid_lines_with, marching_ants, outline, ramp, ticks, }; pub use marker::{Marker, MarkerSize}; pub use paint_slot::PaintSlot; @@ -55,7 +55,9 @@ pub(crate) use surface::SurfaceSlot; pub use surround::paint_surround; pub use svg_set::{AppIcons, register_app_icons}; pub use text::{ChordText, HAlign, LayoutRun, ReadingMeasure, Span, TextLayout, TextRun, Wrap}; -pub use text_input::{Completer, Completion, EditorLine, EditorPurpose, EditorRun, EditorState, TextKey, TextOptions}; +pub use text_input::{ + Completer, Completion, EditorLine, EditorPurpose, EditorRun, EditorState, EditorSurrounding, ImeStamp, TabKey, TextKey, TextOptions, +}; pub use textures::TextureCache; pub use tool::ToolIcon; diff --git a/crates/ui-contract/src/primitives/pointer_art/art.rs b/crates/ui-contract/src/primitives/pointer_art/art.rs index 6e4a230a4..a739c9eb3 100644 --- a/crates/ui-contract/src/primitives/pointer_art/art.rs +++ b/crates/ui-contract/src/primitives/pointer_art/art.rs @@ -17,6 +17,9 @@ const ARC_HANDLE: f32 = 0.552_284_8; pub(crate) enum Mark { /// A straight line with square-cut ends. Line(Vec2, Vec2, Stroke), + /// A straight line snapped to whole device pixels at the raster scale. + #[allow(dead_code)] // P3(canvas-w3): cv.K29 + Rule(Vec2, Vec2, Stroke), /// A circle's outline. Ring(Vec2, f32, Stroke), /// A rectangle's outline, centred on its edges. @@ -40,6 +43,7 @@ impl Mark { |points: &[Vec2], stroke: &Stroke| Rect::from_points(&points.iter().map(|p| p.to_pos2()).collect::>()).expand(stroke.width / 2.0); match self { Mark::Line(a, b, stroke) => around(&[*a, *b], stroke), + Mark::Rule(..) => todo!("cv.K29"), Mark::Ring(centre, radius, stroke) => Rect::from_center_size(centre.to_pos2(), Vec2::splat(2.0 * radius + stroke.width)), Mark::Frame(rect, stroke) => rect.expand(stroke.width / 2.0), Mark::Disc(centre, radius, _) => Rect::from_center_size(centre.to_pos2(), Vec2::splat(2.0 * radius)), @@ -69,6 +73,7 @@ impl Art { Mark::Line(a, b, stroke) => { painter.line_segment([at + *a, at + *b], *stroke); } + Mark::Rule(..) => todo!("cv.K29"), Mark::Ring(centre, radius, stroke) => { painter.circle_stroke(at + *centre, *radius, *stroke); } @@ -193,6 +198,7 @@ fn rounded_path(rect: Rect, round: f32) -> Option { fn draw(pixmap: &mut tiny_skia::Pixmap, mark: &Mark, transform: tiny_skia::Transform, scale: f32, origin: f32) { match mark { Mark::Line(a, b, stroke) => stroke_path(pixmap, polyline(&[*a, *b], false), *stroke, transform), + Mark::Rule(..) => todo!("cv.K29"), Mark::Ring(centre, radius, stroke) => { stroke_path(pixmap, tiny_skia::PathBuilder::from_circle(centre.x, centre.y, *radius), *stroke, transform) } diff --git a/crates/ui-contract/src/primitives/text_adapter.rs b/crates/ui-contract/src/primitives/text_adapter.rs index 3217d7577..767d2e603 100644 --- a/crates/ui-contract/src/primitives/text_adapter.rs +++ b/crates/ui-contract/src/primitives/text_adapter.rs @@ -391,7 +391,8 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut } let separated = input.focused && !input.read_only && state.preedit.is_none() && egui_input::take_separator(ctx, input.options.commit_on); // The part keeps Tab (`keys_of`), so the focus service left it here; it is taken before the widget would insert it. - if input.focused && input.options.tab_rewrites && !input.read_only && state.preedit.is_none() && egui_input::take_tab(ctx) { + // P3(chrome-w6): dg.F20a: `take_tab` gave a bool. + if input.focused && input.options.tab_rewrites && !input.read_only && state.preedit.is_none() && egui_input::take_tab(ctx).is_some() { state.end = Some(End::Rewrite { refuses: true }); } let filter = egui_focus::event_filter(input.keys.keep, false); diff --git a/crates/ui-contract/src/primitives/text_input.rs b/crates/ui-contract/src/primitives/text_input.rs index 178475fe4..68ac811ed 100644 --- a/crates/ui-contract/src/primitives/text_input.rs +++ b/crates/ui-contract/src/primitives/text_input.rs @@ -34,6 +34,21 @@ impl TextKey { } } +/// What Tab does in a text field. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum TabKey { + /// Tab moves focus. + #[default] + Moves, + /// Tab inserts a tab. + Inserts, + /// Tab and Shift+Tab rewrite the draft (the text part selects it and refuses). + Rewrites, + /// Tab keeps focus and is handed back as `EditResponse::tab`: `Some(true)` for Tab, `Some(false)` for Shift+Tab. + Reports, +} + /// How a text part behaves beyond its codec. #[derive(Clone)] pub struct TextOptions { @@ -57,6 +72,10 @@ pub struct TextOptions { pub ink: Option, /// Tab inserts a tab instead of moving focus. pub tab_inserts: bool, + /// What Tab does in this field; replaces `tab_inserts` and `tab_rewrites`. + pub tab: TabKey, + /// The bound caret as a byte offset, read and written through its binding; the adapter keeps no caret of its own. + pub caret: Option, /// Candidates for the text before the caret. pub complete: Option>, /// Enter accepts the highlighted candidate, as Tab does; off, Enter stays the field's own (a cell commits on it). @@ -112,6 +131,8 @@ impl Default for TextOptions { role: TypeRole::Body, ink: None, tab_inserts: false, + tab: TabKey::default(), + caret: None, complete: None, complete_on_enter: false, replace_selection: None, @@ -272,12 +293,42 @@ pub struct EditorState<'a> { pub can_undo: bool, /// Whether redo has something to do. pub can_redo: bool, + /// The committed text around the caret, or why there is none, with the input-method target's epoch. + pub surrounding: Option<(u64, EditorSurrounding<'a>)>, } +/// The committed window around the caret that an editor reports to the input method, or why there is none. +#[derive(Clone, Debug)] +#[non_exhaustive] +pub enum EditorSurrounding<'a> { + /// The text around the caret, with UTF-8 offsets of the cursor and the selection anchor into it. + Text { + /// The committed text. + text: &'a str, + /// The cursor's byte offset into `text`. + cursor: usize, + /// The selection anchor's byte offset into `text`. + anchor: usize, + }, + /// The editor has no text to report. + Unavailable { + /// The revision the editor reports it at, if it keeps one. + revision: Option, + }, +} + +pub use egui::ime_context::ImeMutationStamp as ImeStamp; + impl<'a> EditorState<'a> { + /// Reports `s` as the committed text around the caret, for the input-method target at `epoch`. + pub fn surrounding(self, epoch: u64, s: EditorSurrounding<'a>) -> Self { + let _ = (epoch, s); + todo!("cv.K26") + } + /// A state with no selection, no marked text and nothing to undo. pub const fn new(caret: Rect, lines: &'a [EditorLine<'a>], caret_at: TextPos) -> Self { - EditorState { caret, lines, caret_at, selection: None, composing: false, can_undo: false, can_redo: false } + EditorState { caret, lines, caret_at, selection: None, composing: false, can_undo: false, can_redo: false, surrounding: None } } } diff --git a/crates/ui-contract/src/primitives/textures/store.rs b/crates/ui-contract/src/primitives/textures/store.rs index dc768870d..8c0dac632 100644 --- a/crates/ui-contract/src/primitives/textures/store.rs +++ b/crates/ui-contract/src/primitives/textures/store.rs @@ -7,7 +7,7 @@ use crate::runtime::egui::pass; use crate::runtime::egui::textures; use craft_behavior::PixelSize; use egui::load::SizedTexture; -use egui::{ColorImage, Context, TextureHandle, TextureId, TextureOptions, Vec2}; +use egui::{ColorImage, Context, Rect, TextureHandle, TextureId, TextureOptions, Vec2}; use std::collections::HashMap; use std::collections::hash_map::DefaultHasher; use std::fmt::Debug; @@ -90,6 +90,8 @@ pub struct TextureStoreOptions { /// The sampling of every texture: `TextureOptions::LINEAR` by default; the clipping overlay and pixel-exact /// previews use `TextureOptions::NEAREST`. pub filter: TextureOptions, + /// The largest side of a picture the store puts on shared pages; `None` gives every picture a texture of its own. + pub packed: Option, } impl TextureStoreOptions { @@ -109,7 +111,15 @@ impl TextureStoreOptions { } const fn with_budget(max_bytes: usize, max_entries: usize) -> Self { - Self { budget: TextureBudget::new(max_bytes, max_entries), filter: TextureOptions::LINEAR } + Self { budget: TextureBudget::new(max_bytes, max_entries), filter: TextureOptions::LINEAR, packed: None } + } + + /// Puts pictures up to `max_side` on shared pages written in place; when full, the store recycles the least + /// recently drawn page, never one drawn this pass. A const fn, so it carries the setting without `todo!`. + #[must_use] + pub const fn packed(mut self, max_side: u32) -> Self { + self.packed = Some(max_side); + self } /// The sampling of every texture. @@ -142,9 +152,18 @@ pub struct CachedTexture { pub id: TextureId, /// The texture's size in texels (reduced when the image was past the device limit). pub size: PixelSize, + /// The picture's top-left texel on its page; `[0, 0]` for an unpacked texture. + pub origin: [u32; 2], + /// The size of the page texture the picture sits on; `size` for an unpacked texture. + pub page: PixelSize, } impl CachedTexture { + /// The picture's part of its page texture, in uv coordinates, to paint with `id`. + pub fn uv(&self) -> Rect { + todo!("rb.R20") + } + /// `size` as a vector, for fitting: only the aspect matters to a cell. pub fn size_vec2(&self) -> Vec2 { Vec2::new(self.size.width as f32, self.size.height as f32) @@ -342,7 +361,7 @@ impl TextureStore { } (None, name) => textures::load(ctx, name.unwrap_or_default(), image, filter), }; - let texture = CachedTexture { id: handle.id(), size }; + let texture = CachedTexture { id: handle.id(), size, origin: [0, 0], page: size }; let bytes = byte_size(size); self.with(ctx, |inner| { inner.roll_uploads(frame); @@ -499,7 +518,8 @@ fn texture_size(source: PixelSize, factor: u32) -> PixelSize { } fn cached(handle: &TextureHandle, source: PixelSize, factor: u32) -> CachedTexture { - CachedTexture { id: handle.id(), size: texture_size(source, factor) } + let size = texture_size(source, factor); + CachedTexture { id: handle.id(), size, origin: [0, 0], page: size } } fn picture_bytes(picture: &Picture) -> usize { diff --git a/crates/ui-contract/src/runtime/commands/clipboard.rs b/crates/ui-contract/src/runtime/commands/clipboard.rs index 584253f44..d74cecff2 100644 --- a/crates/ui-contract/src/runtime/commands/clipboard.rs +++ b/crates/ui-contract/src/runtime/commands/clipboard.rs @@ -3,7 +3,9 @@ use crate::runtime::egui::clipboard; use crate::runtime::keys; use crate::runtime::pending::Pending; +use craft_platform::clipboard::{ClipboardError, ClipboardImage, Flavor, Written}; use egui::{ColorImage, Context, Id}; +use std::path::PathBuf; use std::sync::Arc; /// One clipboard item. @@ -16,6 +18,10 @@ pub enum ClipItem { Html(Arc), /// An image. Image(Arc), + /// Rich text. + Rtf(Arc), + /// MathML. + MathMl(Arc), /// An item of an app-defined type. #[non_exhaustive] Custom { @@ -26,6 +32,14 @@ pub enum ClipItem { }, } +impl ClipItem { + /// An item of an app-defined type: `bytes` under the MIME type `mime`. + pub fn custom(mime: impl Into>, bytes: impl Into>) -> ClipItem { + let _ = (mime.into(), bytes.into()); + todo!("pf.C-R3") + } +} + /// What a paste delivers. #[derive(Clone, Debug, Default, PartialEq)] #[non_exhaustive] @@ -55,6 +69,60 @@ impl ClipboardHandle { ClipboardHandle { ctx: ctx.clone(), slot } } + /// The clipboard handle of `ctx`, over the installed clipboard. + pub fn of(ctx: &Context) -> ClipboardHandle { + let _ = ctx; + todo!("pf.C-R3") + } + + /// Offers `items` in the caller's order, as one offer, and says which flavour the clipboard kept. + pub fn offer(&self, items: &[ClipItem]) -> Result { + let _ = items; + todo!("pf.C-R3") + } + + /// The first of `mimes` the installed clipboard holds. + pub fn read(&self, mimes: &[&str]) -> Result, ClipboardError> { + let _ = mimes; + todo!("pf.C-R3") + } + + /// The clipboard's text. + pub fn read_text(&self) -> Result, ClipboardError> { + todo!("pf.C-R3") + } + + /// The clipboard's image as straight-alpha RGBA8 pixels. + pub fn read_image(&self) -> Result, ClipboardError> { + todo!("pf.C-R3") + } + + /// The files the clipboard holds. + pub fn read_files(&self) -> Result>, ClipboardError> { + todo!("pf.C-R3") + } + + /// Whether the clipboard holds one of `mimes`. + pub fn has(&self, mimes: &[&str]) -> bool { + let _ = mimes; + todo!("pf.C-R3") + } + + /// Whether the clipboard still holds what this app last offered. + pub fn holds_ours(&self) -> bool { + todo!("pf.C-R3") + } + + /// The MIME names of the formats on the clipboard. + pub fn formats(&self) -> Vec { + todo!("pf.C-R3") + } + + /// Whether a late paste offer arrived this frame; true in every pass of that frame. + pub fn arrived(&self) -> bool { + todo!("pf.C-R3") + } + /// Writes every flavour of `items` that the clipboard carries. pub fn put(&self, items: &[ClipItem]) { if !crate::runtime::measure::effect(&self.ctx, "clipboard::put") { @@ -64,7 +132,8 @@ impl ClipboardHandle { match item { ClipItem::Text(text) => clipboard::copy_text(&self.ctx, text.to_string()), ClipItem::Image(image) => clipboard::copy_image(&self.ctx, (**image).clone()), - ClipItem::Html(_) | ClipItem::Custom { .. } => {} + // P3(platform-w3): pf.C-R3: the new items are written through `offer`. + ClipItem::Html(_) | ClipItem::Rtf(_) | ClipItem::MathMl(_) | ClipItem::Custom { .. } => {} } } } diff --git a/crates/ui-contract/src/runtime/commands/mod.rs b/crates/ui-contract/src/runtime/commands/mod.rs index e7f5ca7af..5bbdc2f30 100644 --- a/crates/ui-contract/src/runtime/commands/mod.rs +++ b/crates/ui-contract/src/runtime/commands/mod.rs @@ -163,6 +163,8 @@ pub enum FireSource { Automation, /// An AccessKit action on a part of a component. Access, + /// A keytip badge, sequence or digit. + Keytip, } /// The phase of the key press that fired a command. diff --git a/crates/ui-contract/src/runtime/egui/access.rs b/crates/ui-contract/src/runtime/egui/access.rs index 8eee24e44..63af4040d 100644 --- a/crates/ui-contract/src/runtime/egui/access.rs +++ b/crates/ui-contract/src/runtime/egui/access.rs @@ -48,6 +48,14 @@ fn behind_modal(ctx: &Context, viewport: ViewportId, layer: egui::LayerId) -> bo #[cfg(feature = "testing")] pub type NodeId = accesskit::NodeId; +/// Settles the AccessKit update's focus: when it is not among the update's nodes, focus goes to the tree root. The +/// runtime plugin's output hook calls it once per pass. +#[allow(dead_code)] // P3(chrome-w7): ch.C18 +pub(crate) fn settle_focus(output: &mut egui::FullOutput) { + let _ = output; + todo!("ch.C18") +} + /// The AccessKit id of the node of `id`. #[cfg(feature = "testing")] pub(crate) fn node_id(id: Id) -> NodeId { diff --git a/crates/ui-contract/src/runtime/egui/alt_code.rs b/crates/ui-contract/src/runtime/egui/alt_code.rs new file mode 100644 index 000000000..31d50709b --- /dev/null +++ b/crates/ui-contract/src/runtime/egui/alt_code.rs @@ -0,0 +1,14 @@ +//! Alt+numpad code entry, folded into the input events in the raw-input step. + +use crate::runtime::env::AltCodePages; + +/// The Alt+numpad entry in progress in one viewport. +#[derive(Default)] +pub(crate) struct AltCodeEntry; + +/// Folds Alt+numpad entry out of `events` and into text events, decoding with `pages`. +#[allow(dead_code)] // P3(shell-w1): sh.K5 +pub(crate) fn fold(entry: &mut AltCodeEntry, events: &mut Vec, pages: AltCodePages) { + let _ = (entry, events, pages); + todo!("sh.K5") +} diff --git a/crates/ui-contract/src/runtime/egui/clipboard.rs b/crates/ui-contract/src/runtime/egui/clipboard.rs index e658bec0c..25a762c33 100644 --- a/crates/ui-contract/src/runtime/egui/clipboard.rs +++ b/crates/ui-contract/src/runtime/egui/clipboard.rs @@ -1,6 +1,54 @@ //! Clipboard output commands. +use craft_platform::clipboard::{Clipboard, ClipboardBackend, ClipboardError, ClipboardImage, Flavor}; use egui::{ColorImage, Context}; +use std::path::PathBuf; + +/// The backend the runtime installs when the host gives no clipboard: egui's own copy and paste commands. +#[allow(dead_code)] // P3(platform-w3): pf.C-R2 +pub(crate) struct EguiClipboard; + +impl ClipboardBackend for EguiClipboard { + fn write(&mut self, flavors: &[Flavor]) -> Result { + let _ = flavors; + todo!("pf.C-R2") + } + + /// egui delivers pasted text only as an input event, so a read finds nothing. + fn read(&mut self, mimes: &[&str], limit: u64) -> Result, ClipboardError> { + let _ = (mimes, limit); + Ok(None) + } + + fn read_image(&mut self, limit: u64) -> Result, ClipboardError> { + let _ = limit; + todo!("pf.C-R2") + } + + fn read_files(&mut self, limit: usize) -> Result>, ClipboardError> { + let _ = limit; + todo!("pf.C-R2") + } + + fn has(&mut self, mimes: &[&str]) -> bool { + let _ = mimes; + todo!("pf.C-R2") + } +} + +/// Runs `f` on the clipboard installed in `ctx`'s runtime memory. +#[allow(dead_code)] // P3(platform-w3): pf.C-R2 +pub(crate) fn with(ctx: &Context, f: impl FnOnce(&mut Clipboard) -> R) -> R { + let _ = (ctx, f); + todo!("pf.C-R2") +} + +/// Once per frame, in the pass that receives input: takes a late paste offer for this frame. +#[allow(dead_code)] // P3(platform-w3): pf.C-R2 +pub(crate) fn begin_frame(ctx: &Context) { + let _ = ctx; + todo!("pf.C-R2") +} /// Puts `text` on the system clipboard. pub(crate) fn copy_text(ctx: &Context, text: String) { diff --git a/crates/ui-contract/src/runtime/egui/input.rs b/crates/ui-contract/src/runtime/egui/input.rs index c7121511c..a27f21567 100644 --- a/crates/ui-contract/src/runtime/egui/input.rs +++ b/crates/ui-contract/src/runtime/egui/input.rs @@ -657,6 +657,9 @@ pub(crate) struct RawState { /// The input time of the last Ctrl+wheel folded into a pinch step. last_pinch: Option, control_click: ControlClick, + /// The Alt+numpad entry in progress. + #[allow(dead_code)] // P3(shell-w1): sh.K5 + alt_code: super::alt_code::AltCodeEntry, } /// The input hook's raw-input step for every viewport, after the injected step joined the input and before the key @@ -690,15 +693,17 @@ pub(crate) fn step_key_pressed(ctx: &Context) -> bool { ctx.input(|input| [Key::ArrowUp, Key::ArrowDown, Key::PageUp, Key::PageDown].into_iter().any(|key| input.key_pressed(key))) } -/// Removes this pass's Tab and Shift+Tab presses from the input events; returns whether there was one. A Tab with -/// Ctrl, Cmd or Alt is the window's, not the field's, and stays. -pub(crate) fn take_tab(ctx: &Context) -> bool { +/// Removes this pass's Tab and Shift+Tab presses from the input events; returns the direction of one if there was +/// one: `Some(true)` for Tab, `Some(false)` for Shift+Tab. A Tab with Ctrl, Cmd or Alt is the window's, not the +/// field's, and stays. +pub(crate) fn take_tab(ctx: &Context) -> Option { ctx.input_mut(|input| { let before = input.events.len(); input.events.retain(|event| { !matches!(event, Event::Key { key: Key::Tab, pressed: true, modifiers, .. } if !modifiers.ctrl && !modifiers.command && !modifiers.mac_cmd && !modifiers.alt) }); - input.events.len() != before + // P3(shell-w1): dg.F20a: the direction is not read yet; every taken press reports Tab. + (input.events.len() != before).then_some(true) }) } diff --git a/crates/ui-contract/src/runtime/egui/mod.rs b/crates/ui-contract/src/runtime/egui/mod.rs index cb380be57..340b21a69 100644 --- a/crates/ui-contract/src/runtime/egui/mod.rs +++ b/crates/ui-contract/src/runtime/egui/mod.rs @@ -2,6 +2,7 @@ pub mod access; pub mod alloc; +pub(crate) mod alt_code; pub mod areas; pub mod child; pub mod clipboard; diff --git a/crates/ui-contract/src/runtime/egui/text_edit.rs b/crates/ui-contract/src/runtime/egui/text_edit.rs index 0170bb71d..2af40cc67 100644 --- a/crates/ui-contract/src/runtime/egui/text_edit.rs +++ b/crates/ui-contract/src/runtime/egui/text_edit.rs @@ -248,6 +248,13 @@ pub(crate) fn select(ctx: &Context, id: Id, anchor: usize, caret: usize) { state.store(ctx, id); } +/// Whether the widget's field has an undo step and a redo step, as `(undo, redo)`. +#[allow(dead_code)] // P3(chrome-w6): ch.C17a +pub(crate) fn history(ctx: &Context, id: Id) -> (bool, bool) { + let _ = (ctx, id); + todo!("ch.C17a") +} + /// The undo steps of the widget: `Some(text)` when `step` changed it. pub(crate) fn undo(ctx: &Context, id: Id, current: &str, redo: bool) -> Option { let mut state = TextEditState::load(ctx, id)?; diff --git a/crates/ui-contract/src/runtime/egui/textures.rs b/crates/ui-contract/src/runtime/egui/textures.rs index 28ac316fd..ba5477bcf 100644 --- a/crates/ui-contract/src/runtime/egui/textures.rs +++ b/crates/ui-contract/src/runtime/egui/textures.rs @@ -1,6 +1,6 @@ //! Texture uploads and painting: the one place egui's texture calls are made. -use egui::{Color32, ColorImage, Context, CornerRadius, Painter, Rect, TextureHandle, TextureId, TextureOptions}; +use egui::{Color32, ColorImage, Context, CornerRadius, Painter, Pos2, Rect, TextureHandle, TextureId, TextureOptions}; /// Uploads `image` as a texture called `name`, sampled with `filter`. The texture lives as long as the handle. pub(crate) fn load(ctx: &Context, name: String, image: ColorImage, filter: TextureOptions) -> TextureHandle { @@ -17,6 +17,14 @@ pub(crate) fn replace_region(handle: &mut TextureHandle, origin: [u32; 2], image handle.set_partial(origin.map(|n| n as usize), image, filter); } +/// Paints the part `uv` of `texture` onto the clockwise quad `corners` (from `uv`'s top left), tinted by `tint`, as one +/// textured mesh of two triangles. +#[allow(dead_code)] // P3(canvas-w3): cv.K30 +pub(crate) fn paint_quad(painter: &Painter, texture: TextureId, corners: [Pos2; 4], uv: Rect, tint: Color32) { + let _ = (painter, texture, corners, uv, tint); + todo!("cv.K30") +} + /// Paints `texture` in `rect`, the part `uv` of it, tinted by `tint`, with corners rounded by `radius`. #[doc(hidden)] pub fn paint(painter: &Painter, texture: TextureId, rect: Rect, uv: Rect, tint: Color32, radius: CornerRadius) { diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index 2809caf04..489a80330 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -8,7 +8,7 @@ mod units; pub use label::{Label, Message, Word}; #[doc(hidden)] pub use shell::ShellEntry; -pub use shell::{BodyMode, RevealEdge, ShellCx, ShellRegions, SlotKey, WindowKey}; +pub use shell::{BodyMode, PageBandRoom, RevealEdge, ShellCx, ShellRegions, SlotKey, WindowKey}; pub use units::{ColumnSize, LengthUnits, PointSize, UnitKind, UnitWords, Units}; use crate::runtime::commands::CommandChain; @@ -51,7 +51,7 @@ pub(crate) use tokens::TokenInputs; #[cfg(feature = "testing")] pub(crate) use tokens::root_token_resolves; use tokens::tokens_for; -pub use values::{ArenaId, ColumnAlign, InBar, MotionPolicy, PaneEdge, RowPressed, Scale}; +pub use values::{AltCodePages, ArenaId, ColumnAlign, InBar, MotionPolicy, PaneEdge, RowPressed, Scale, WheelSpeed}; pub use view::EnvView; /// The inherited context of a `Ui`: one `Arc` clone per read. diff --git a/crates/ui-contract/src/runtime/env/root.rs b/crates/ui-contract/src/runtime/env/root.rs index 56c1837a0..1e1a595fc 100644 --- a/crates/ui-contract/src/runtime/env/root.rs +++ b/crates/ui-contract/src/runtime/env/root.rs @@ -1,7 +1,7 @@ //! RootEnv, the app's root values each frame, and their resolved form. use super::app_values::AppValues; -use super::values::Scale; +use super::values::{AltCodePages, Scale, WheelSpeed}; use crate::runtime::egui::memory::Service; use crate::runtime::focus::TabReach; use craft_behavior::MotionMode; @@ -51,6 +51,10 @@ pub struct RootEnv { pub values: AppValues, /// Today's date in the host's time zone; the runtime reads no wall clock. pub today: Option, + /// This frame's wheel speed. + pub wheel: WheelSpeed, + /// The code pages that decode Alt+numpad codes. + pub alt_codes: AltCodePages, } impl Default for RootEnv { @@ -72,6 +76,8 @@ impl Default for RootEnv { theme_def: None, values: AppValues::default(), today: None, + wheel: WheelSpeed::default(), + alt_codes: AltCodePages::default(), } } } @@ -197,6 +203,18 @@ impl RootEnv { self.today = Some(date); self } + + /// Sets this frame's wheel speed. + pub fn wheel_speed(self, speed: WheelSpeed) -> Self { + let _ = speed; + todo!("sh.K3") + } + + /// Sets the code pages that decode Alt+numpad codes. + pub fn alt_code_pages(self, pages: AltCodePages) -> Self { + let _ = pages; + todo!("sh.K4") + } } /// The mode, contrast and motion of a pass, with `System` resolved. diff --git a/crates/ui-contract/src/runtime/env/shell.rs b/crates/ui-contract/src/runtime/env/shell.rs index 3e36d5e4a..7e72311d3 100644 --- a/crates/ui-contract/src/runtime/env/shell.rs +++ b/crates/ui-contract/src/runtime/env/shell.rs @@ -125,6 +125,18 @@ struct Inner { region: Option, revealed_rects: RevealedRects, dialog: DialogRecord, + page_band: Option, +} + +/// The room of the page band while a full-window page shows. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PageBandRoom { + /// The band's rect. + pub rect: Rect, + /// Where the band starts along its axis. + pub start: f32, + /// Where the band ends along its axis. + pub end: f32, } /// The rects that body content registered this pass for the edge it was revealed from. The registry is shared by the @@ -166,6 +178,7 @@ impl ShellCx { region: None, revealed_rects: RevealedRects::default(), dialog: DialogRecord::default(), + page_band: None, }; ShellCx { inner: Arc::new(inner) } } @@ -310,6 +323,17 @@ impl ShellCx { pub fn float_bounds(&self) -> Rect { self.inner.float_bounds } + + /// The page band's room while a full-window page shows, else `None`. + pub fn page_band(&self) -> Option { + todo!("ch.C5a") + } + + /// Sets the page band's room. + pub fn with_page_band(self, room: Option) -> Self { + let _ = room; + todo!("ch.C5a") + } } /// The env entry that carries the shell to its slots and body. A context with no shell holds `None`. diff --git a/crates/ui-contract/src/runtime/env/tokens.rs b/crates/ui-contract/src/runtime/env/tokens.rs index 1c9f71ac1..9a94dd235 100644 --- a/crates/ui-contract/src/runtime/env/tokens.rs +++ b/crates/ui-contract/src/runtime/env/tokens.rs @@ -3,7 +3,7 @@ use super::root::{ResolvedRoot, RootEnv}; use crate::runtime::pass_state; use crate::style::UiTokens; -use craft_theme::{AppSizes, Appearance, Contrast, Mode, SUITE_DEFAULT, Size, TextSize, ThemeDef, ThemeId, builtins, resolve_sized}; +use craft_theme::{AppId, AppSizes, Appearance, Contrast, Mode, SUITE_DEFAULT, Size, TextSize, ThemeDef, ThemeId, builtins, resolve_sized}; use egui::Context; use std::sync::Arc; @@ -82,11 +82,15 @@ fn resolve_inputs(inputs: &TokenInputs) -> Arc { Appearance { mode: inputs.mode, contrast: inputs.contrast, size: inputs.density, text_size: inputs.text_size, reduced_motion: false }; let themes = builtins(); if let Some(def) = &inputs.theme_def { - return Arc::new(UiTokens::new(Arc::new(resolve_sized(def, appearance, None, &inputs.sizes).tokens), inputs.contrast, inputs.density)); + return Arc::new(UiTokens::new( + Arc::new(resolve_sized(def, appearance, inputs.app.as_ref(), &inputs.sizes).tokens), + inputs.contrast, + inputs.density, + )); } let theme: &ThemeDef = [inputs.theme.as_str(), SUITE_DEFAULT].into_iter().find_map(|id| themes.iter().find(|theme| theme.id.as_str() == id)).unwrap_or(&themes[0]); - Arc::new(UiTokens::new(Arc::new(resolve_sized(theme, appearance, None, &inputs.sizes).tokens), inputs.contrast, inputs.density)) + Arc::new(UiTokens::new(Arc::new(resolve_sized(theme, appearance, inputs.app.as_ref(), &inputs.sizes).tokens), inputs.contrast, inputs.density)) } /// What the resolved root tokens depend on. The sizes are compared by identity, as `set_input` does. @@ -99,6 +103,8 @@ pub(crate) struct TokenInputs { pub(super) contrast: Contrast, pub(super) density: Size, pub(super) text_size: TextSize, + /// The app whose `[apps.]` theme pins apply over the chosen theme. + pub(super) app: Option, } impl TokenInputs { @@ -111,6 +117,7 @@ impl TokenInputs { contrast: resolved.contrast, density: root.density, text_size: root.text_size, + app: None, // P3(shell-w1): sh.K8 } } @@ -124,6 +131,7 @@ impl TokenInputs { && self.contrast == other.contrast && self.density == other.density && self.text_size == other.text_size + && self.app == other.app } fn same(&self, other: &TokenInputs) -> bool { @@ -134,6 +142,7 @@ impl TokenInputs { && self.contrast == other.contrast && self.density == other.density && self.text_size == other.text_size + && self.app == other.app } } diff --git a/crates/ui-contract/src/runtime/env/values.rs b/crates/ui-contract/src/runtime/env/values.rs index 2c61c3e52..dce3947d0 100644 --- a/crates/ui-contract/src/runtime/env/values.rs +++ b/crates/ui-contract/src/runtime/env/values.rs @@ -24,6 +24,37 @@ impl Default for Scale { } } +/// The user's wheel multipliers: `line` for notches, `point` for touchpad deltas. Distinct from +/// [`WheelScope`](super::WheelScope), which says who takes the wheel, not how far it moves. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct WheelSpeed { + /// The multiplier for line (notch) scrolling. + pub line: f32, + /// The multiplier for point (touchpad) scrolling. + pub point: f32, +} + +impl Default for WheelSpeed { + fn default() -> Self { + WheelSpeed { line: 1.0, point: 1.0 } + } +} + +/// Code pages that decode Alt+numpad codes; the app sets them from the system locale. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct AltCodePages { + /// The ANSI code page, for codes typed with a leading zero. + pub ansi: u16, + /// The OEM code page, for codes typed without one. + pub oem: u16, +} + +impl Default for AltCodePages { + fn default() -> Self { + AltCodePages { ansi: 1252, oem: 437 } + } +} + /// The motion mode in effect, carried in `Env.motion`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] diff --git a/crates/ui-contract/src/runtime/ime.rs b/crates/ui-contract/src/runtime/ime.rs index a9797ec9d..76de8536d 100644 --- a/crates/ui-contract/src/runtime/ime.rs +++ b/crates/ui-contract/src/runtime/ime.rs @@ -18,6 +18,9 @@ struct Engine { queue: Vec, owner: Option, generation: u64, + /// The egui fork's input-method context tracker; replaces `generation`, which stays until canvas-w2 moves its readers. + #[allow(dead_code)] // P3(canvas-w2): cv.K28 + tracker: egui::ime_context::ImeContextTracker, composing: bool, guard: u8, /// A reset was asked for; events of the old composition are dropped until its completion arrives. diff --git a/crates/ui-contract/src/runtime/inspect.rs b/crates/ui-contract/src/runtime/inspect.rs index 18e4138cf..db61675fc 100644 --- a/crates/ui-contract/src/runtime/inspect.rs +++ b/crates/ui-contract/src/runtime/inspect.rs @@ -8,6 +8,7 @@ use crate::runtime::egui::sizing::{Rerun, request_discard}; use crate::runtime::reads::{self, BindKey}; use crate::runtime::{focus, measure, pass_state, pointer}; use craft_behavior::PartRef; +use craft_keymap::CommandRef; use egui::{Context, Id, IdMap, IdSet, Rect, Ui}; use std::sync::Arc; @@ -145,6 +146,8 @@ pub struct Element { pub facts: Option, /// Its place in Tab order within the region, from 1, when keyboard focus reaches it. pub stop: Option, + /// The command bound to the control, when it has one. + pub command: Option, } /// A hit area the sensing core registered for a component of the region. @@ -328,7 +331,8 @@ fn finish(ctx: &Context, open: Open) -> Recorded { let Some(owner) = elements.iter().position(|element| element.id == id && element.part.is_none()) else { continue }; let rect = hits.iter().find(|hit| hit.owner == id && hit.part == part).map_or(elements[owner].rect, |hit| hit.rect); let depth = elements[owner].depth + 1; - let element = Element { id, part, component: elements[owner].component, depth, rect, content: rect, facts: None, stop: None }; + let element = + Element { id, part, component: elements[owner].component, depth, rect, content: rect, facts: None, stop: None, command: None }; elements.insert(owner + 1, element); owner + 1 } @@ -381,8 +385,17 @@ pub(crate) fn open_element(ui: &Ui, id: Id, component: &'static str) -> bool { let Some(open) = log.open.last_mut() else { return false }; let component = component.rsplit("::").next().unwrap_or(component); let component = component.split('<').next().unwrap_or(component); - let element = - Element { id, part: None, component, depth: open.stack.len(), rect: Rect::NOTHING, content: Rect::NOTHING, facts: None, stop: None }; + let element = Element { + id, + part: None, + component, + depth: open.stack.len(), + rect: Rect::NOTHING, + content: Rect::NOTHING, + facts: None, + stop: None, + command: None, + }; open.stack.push(open.elements.len()); open.elements.push((element, layer)); true @@ -402,6 +415,14 @@ pub(crate) fn close_element(ctx: &Context, id: Id, rect: Rect, content: Rect) { }); } +/// Notes the command bound to the control `id` in the open region's record; the report step calls it with the +/// component's resolved command. +#[allow(dead_code)] // P3(ribbon-w5): rb.R17 +pub(crate) fn note_command(ctx: &Context, id: Id, command: Option) { + let _ = (ctx, id, command); + todo!("rb.R17") +} + /// Records what the node of the component `id`, or of its part `part` at `rect`, says. pub(crate) fn node_facts(ctx: &Context, id: Id, part: Option, rect: Rect, facts: Facts) { pass_state::with::(ctx, |log| { @@ -412,7 +433,17 @@ pub(crate) fn node_facts(ctx: &Context, id: Id, part: Option, rect: Rec Some(part) => { let (component, depth) = (owner.0.component, owner.0.depth + 1); open.parts.retain(|element| !(element.id == id && element.part == Some(part))); - open.parts.push(Element { id, part: Some(part), component, depth, rect, content: rect, facts: Some(facts), stop: None }); + open.parts.push(Element { + id, + part: Some(part), + component, + depth, + rect, + content: rect, + facts: Some(facts), + stop: None, + command: None, + }); } } }); diff --git a/crates/ui-contract/src/runtime/install.rs b/crates/ui-contract/src/runtime/install.rs index 06ec4dc31..354100a78 100644 --- a/crates/ui-contract/src/runtime/install.rs +++ b/crates/ui-contract/src/runtime/install.rs @@ -42,6 +42,9 @@ pub struct InstallSpec { /// Whether the stories' command sets (`#[command(story)]`) load: the gallery and the story fixtures show /// stories, an app does not, so a story's keys never reach an app's keymap. pub stories: bool, + /// The clipboard the host installs (system, browser event, memory); without one the runtime uses + /// `Clipboard::new(EguiClipboard)`. + pub clipboard: Option, } /// The modifiers the mouse wheel zooms and scrolls sideways with. @@ -82,9 +85,16 @@ impl InstallSpec { app_id: String::new(), pen: None, stories: false, + clipboard: None, } } + /// Installs the host's clipboard (system, browser event, memory) in place of the runtime's own. + pub fn clipboard(self, clipboard: craft_platform::clipboard::Clipboard) -> Self { + let _ = clipboard; + todo!("pf.C-R1") + } + /// Loads the stories' command sets too, for an install that shows stories. pub fn stories(mut self) -> Self { self.stories = true; diff --git a/crates/ui-contract/src/runtime/windows/host.rs b/crates/ui-contract/src/runtime/windows/host.rs index 5ce81ebda..b1de2d369 100644 --- a/crates/ui-contract/src/runtime/windows/host.rs +++ b/crates/ui-contract/src/runtime/windows/host.rs @@ -117,6 +117,13 @@ impl WindowHost { screenshot::facts(&self.ctx, viewport) } + /// The viewport's latest settled AccessKit update, a host fact of the window as its screenshot facts are; `None` + /// while AccessKit is off. + pub fn access_tree(&self, viewport: ViewportId) -> Option { + let _ = viewport; + todo!("ch.C19a") + } + /// Queues a pointer move to `at` in `viewport` with `mods` held, delivered on a pass of its own; the modifiers stay /// held after it, and a button held by earlier injected input stays down, so the move drags. With `rest` (seconds) /// the input counts as processed only once the pointer has rested that long. As a window never reports a NaN or diff --git a/crates/ui-contract/src/style/look.rs b/crates/ui-contract/src/style/look.rs index 0bf3dfe9c..176789d4b 100644 --- a/crates/ui-contract/src/style/look.rs +++ b/crates/ui-contract/src/style/look.rs @@ -67,13 +67,15 @@ pub enum SurfaceKind { Scrim, /// An outlined box without fill. Frame, + /// The app's colour as a surface: the strong accent, square corners, no edge. + Brand, } impl SurfaceKind { /// The ink text and icons read on this surface. pub const fn ink(self) -> super::Ink { match self { - SurfaceKind::Scrim => super::Ink::OnDark, + SurfaceKind::Scrim | SurfaceKind::Brand => super::Ink::OnDark, _ => super::Ink::OnPanel, } } diff --git a/crates/ui-contract/src/style/span.rs b/crates/ui-contract/src/style/span.rs index b75ed4afb..7c1151069 100644 --- a/crates/ui-contract/src/style/span.rs +++ b/crates/ui-contract/src/style/span.rs @@ -1,5 +1,6 @@ //! `Span`: one styled stretch of a text run. +use craft_theme::variant::Tone; use std::borrow::Cow; /// One styled stretch of a run. @@ -24,6 +25,8 @@ pub struct Span<'a> { pub underline: bool, /// The role's semibold face, at the role's size. pub strong: bool, + /// Underlined in the ink of this tone. + pub flag: Option, } impl<'a> Span<'a> { @@ -39,9 +42,16 @@ impl<'a> Span<'a> { highlight: false, underline: false, strong: false, + flag: None, } } + /// Underlines the span in the ink of `tone` (spelling `Bad`, grammar `Info`). + pub fn flag(self, tone: Tone) -> Self { + let _ = tone; + todo!("ch.C14a") + } + /// Italic. pub fn italic(mut self) -> Self { self.italic = true; diff --git a/crates/ui-contract/src/style/surface.rs b/crates/ui-contract/src/style/surface.rs index 98c5b6c61..fb9317aed 100644 --- a/crates/ui-contract/src/style/surface.rs +++ b/crates/ui-contract/src/style/surface.rs @@ -115,9 +115,10 @@ pub(crate) fn surface_style(tokens: &UiTokens, kind: SurfaceKind) -> SurfaceStyl K::Knob => c.surface.knob, K::Scrim => c.surface.scrim, K::Frame => Rgba::TRANSPARENT, + K::Brand => c.accent.strong, }; let radius = match kind { - K::Background | K::Canvas | K::Chrome | K::Scrim => 0.0, + K::Background | K::Canvas | K::Chrome | K::Scrim | K::Brand => 0.0, K::Panel | K::Frame => r.panel, K::Raised | K::Pressed | K::Sunken | K::Well | K::Knob => r.control, K::Popup | K::Dialog => r.surface, @@ -132,7 +133,7 @@ pub(crate) fn surface_style(tokens: &UiTokens, kind: SurfaceKind) -> SurfaceStyl let width = StrokeStep::W1.width(1.0); let stroke = |c: Rgba| SurfaceEdge::Border(Stroke::new(width, color(c))); let edge = match (tokens.shape.edge, kind) { - (_, K::Background | K::Canvas | K::Chrome | K::Panel | K::Scrim) => SurfaceEdge::None, + (_, K::Background | K::Canvas | K::Chrome | K::Panel | K::Scrim | K::Brand) => SurfaceEdge::None, (_, K::Popup | K::Dialog | K::Floating | K::Frame) => stroke(c.line.border), (Edge::Flat, K::Raised) => stroke(c.line.border), (Edge::Flat, K::Sunken | K::Pressed | K::Well) => stroke(c.line.control_edge),